context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
/*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* 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.
******************************************************************************/
/**
* Created at 6:24:51 AM Jan 20, 2011
*/
using SharpBox2D.Common;
using SharpBox2D.Pooling;
using SharpBox2D.Pooling.Normal;
using SharpBox2D.TestBed.Profile;
namespace SharpBox2D.TestBed.Perf
{
//Test Name Milliseconds Avg
//Pop2Sep 6.9922
//Pop2Cont 7.0805
//Pop3Sep 9.9359
//Pop3Cont 10.1472
//Pop4Sep 13.8380
//Pop4Cont 14.0874
//Pop9Sep 31.5494
//Pop9Cont 31.0169
/**
* @author Daniel Murphy
*/
public class StackTest : BasicPerformanceTest
{
public static int INNER_ITERS = 50000;
public static int OUTER_ITERS = 200;
public static string[] tests = new string[]
{
"Pop2Sep", "Pop2Cont", "Pop3Sep", "Pop3Cont",
"Pop4Sep", "Pop4Cont", "Pop9Sep", "Pop9Cont"
};
public static float aStore = 0;
public StackTest() : base(8, OUTER_ITERS, INNER_ITERS)
{
}
public float op(Vec2 argVec)
{
argVec.set(MathUtils.randomFloat(-100, 100), MathUtils.randomFloat(-100, 100));
argVec.mulLocal(3.2f);
float s = argVec.length();
argVec.normalize();
return s;
}
private IWorldPool wp = new DefaultWorldPool(100, 10);
public override void step(int argNum)
{
float a = 0;
for (int i = 0; i < INNER_ITERS; i++)
{
switch (argNum)
{
case 0:
{
Vec2 v1 = wp.popVec2();
Vec2 v2 = wp.popVec2();
a += op(v1);
a += op(v2);
wp.pushVec2(2);
break;
}
case 1:
{
Vec2[] pc = wp.popVec2(2);
a += op(pc[0]);
a += op(pc[1]);
wp.pushVec2(2);
break;
}
case 2:
{
Vec2 v1 = wp.popVec2();
Vec2 v2 = wp.popVec2();
Vec2 v3 = wp.popVec2();
a += op(v1);
a += op(v2);
a += op(v3);
wp.pushVec2(3);
break;
}
case 3:
{
Vec2[] pc = wp.popVec2(3);
a += op(pc[0]);
a += op(pc[1]);
a += op(pc[2]);
wp.pushVec2(3);
break;
}
case 4:
{
Vec2 v1 = wp.popVec2();
Vec2 v2 = wp.popVec2();
Vec2 v3 = wp.popVec2();
Vec2 v4 = wp.popVec2();
a += op(v1);
a += op(v2);
a += op(v3);
a += op(v4);
wp.pushVec2(4);
break;
}
case 5:
{
Vec2[] pc = wp.popVec2(4);
a += op(pc[0]);
a += op(pc[1]);
a += op(pc[2]);
a += op(pc[3]);
wp.pushVec2(4);
}
break;
case 6:
{
Vec2 v1 = wp.popVec2();
Vec2 v2 = wp.popVec2();
Vec2 v3 = wp.popVec2();
Vec2 v4 = wp.popVec2();
Vec2 v5 = wp.popVec2();
Vec2 v6 = wp.popVec2();
Vec2 v7 = wp.popVec2();
Vec2 v8 = wp.popVec2();
Vec2 v9 = wp.popVec2();
a += op(v1);
a += op(v2);
a += op(v3);
a += op(v4);
a += op(v5);
a += op(v6);
a += op(v7);
a += op(v8);
a += op(v9);
wp.pushVec2(9);
break;
}
case 7:
{
Vec2[] pc = wp.popVec2(9);
a += op(pc[0]);
a += op(pc[1]);
a += op(pc[2]);
a += op(pc[3]);
a += op(pc[4]);
a += op(pc[5]);
a += op(pc[6]);
a += op(pc[7]);
a += op(pc[8]);
wp.pushVec2(9);
break;
}
}
}
aStore += a;
}
public override string getTestName(int argNum)
{
return tests[argNum];
}
public static void main(string[] c)
{
(new StackTest()).go();
}
}
}
| |
using System;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using Orleans.Core;
using Orleans.Serialization;
namespace Orleans.Runtime
{
[Serializable]
internal class GrainId : UniqueIdentifier, IEquatable<GrainId>, IGrainIdentity
{
private static readonly object lockable = new object();
private const int INTERN_CACHE_INITIAL_SIZE = InternerConstants.SIZE_LARGE;
private static readonly TimeSpan internCacheCleanupInterval = InternerConstants.DefaultCacheCleanupFreq;
private static Interner<UniqueKey, GrainId> grainIdInternCache;
public UniqueKey.Category Category { get { return Key.IdCategory; } }
public bool IsSystemTarget { get { return Key.IsSystemTargetKey; } }
public bool IsGrain { get { return Category == UniqueKey.Category.Grain || Category == UniqueKey.Category.KeyExtGrain; } }
public bool IsClient { get { return Category == UniqueKey.Category.Client || Category == UniqueKey.Category.GeoClient; } }
private GrainId(UniqueKey key)
: base(key)
{
}
public static GrainId NewId()
{
return FindOrCreateGrainId(UniqueKey.NewKey(Guid.NewGuid(), UniqueKey.Category.Grain));
}
public static GrainId NewClientId(string clusterId = null)
{
return NewClientId(Guid.NewGuid(), clusterId);
}
internal static GrainId NewClientId(Guid id, string clusterId = null)
{
return FindOrCreateGrainId(UniqueKey.NewKey(id,
clusterId == null ? UniqueKey.Category.Client : UniqueKey.Category.GeoClient, 0, clusterId));
}
internal static GrainId GetGrainId(UniqueKey key)
{
return FindOrCreateGrainId(key);
}
internal static GrainId GetSystemGrainId(Guid guid)
{
return FindOrCreateGrainId(UniqueKey.NewKey(guid, UniqueKey.Category.SystemGrain));
}
// For testing only.
internal static GrainId GetGrainIdForTesting(Guid guid)
{
return FindOrCreateGrainId(UniqueKey.NewKey(guid, UniqueKey.Category.None));
}
internal static GrainId NewSystemTargetGrainIdByTypeCode(int typeData)
{
return FindOrCreateGrainId(UniqueKey.NewSystemTargetKey(Guid.NewGuid(), typeData));
}
internal static GrainId GetSystemTargetGrainId(short systemGrainId)
{
return FindOrCreateGrainId(UniqueKey.NewSystemTargetKey(systemGrainId));
}
internal static GrainId GetGrainId(long typeCode, long primaryKey, string keyExt=null)
{
return FindOrCreateGrainId(UniqueKey.NewKey(primaryKey,
keyExt == null ? UniqueKey.Category.Grain : UniqueKey.Category.KeyExtGrain,
typeCode, keyExt));
}
internal static GrainId GetGrainId(long typeCode, Guid primaryKey, string keyExt=null)
{
return FindOrCreateGrainId(UniqueKey.NewKey(primaryKey,
keyExt == null ? UniqueKey.Category.Grain : UniqueKey.Category.KeyExtGrain,
typeCode, keyExt));
}
internal static GrainId GetGrainId(long typeCode, string primaryKey)
{
return FindOrCreateGrainId(UniqueKey.NewKey(0L,
UniqueKey.Category.KeyExtGrain,
typeCode, primaryKey));
}
internal static GrainId GetGrainServiceGrainId(short id, int typeData)
{
return FindOrCreateGrainId(UniqueKey.NewGrainServiceKey(id, typeData));
}
public Guid PrimaryKey
{
get { return GetPrimaryKey(); }
}
public long PrimaryKeyLong
{
get { return GetPrimaryKeyLong(); }
}
public string PrimaryKeyString
{
get { return GetPrimaryKeyString(); }
}
public string IdentityString
{
get { return ToDetailedString(); }
}
public bool IsLongKey
{
get { return Key.IsLongKey; }
}
public long GetPrimaryKeyLong(out string keyExt)
{
return Key.PrimaryKeyToLong(out keyExt);
}
internal long GetPrimaryKeyLong()
{
return Key.PrimaryKeyToLong();
}
public Guid GetPrimaryKey(out string keyExt)
{
return Key.PrimaryKeyToGuid(out keyExt);
}
internal Guid GetPrimaryKey()
{
return Key.PrimaryKeyToGuid();
}
internal string GetPrimaryKeyString()
{
string key;
var tmp = GetPrimaryKey(out key);
return key;
}
internal int GetTypeCode()
{
return Key.BaseTypeCode;
}
private static GrainId FindOrCreateGrainId(UniqueKey key)
{
// Note: This is done here to avoid a wierd cyclic dependency / static initialization ordering problem involving the GrainId, Constants & Interner classes
if (grainIdInternCache != null) return grainIdInternCache.FindOrCreate(key, () => new GrainId(key));
lock (lockable)
{
if (grainIdInternCache == null)
{
grainIdInternCache = new Interner<UniqueKey, GrainId>(INTERN_CACHE_INITIAL_SIZE, internCacheCleanupInterval);
}
}
return grainIdInternCache.FindOrCreate(key, () => new GrainId(key));
}
#region IEquatable<GrainId> Members
public bool Equals(GrainId other)
{
return other != null && Key.Equals(other.Key);
}
#endregion
public override bool Equals(UniqueIdentifier obj)
{
var o = obj as GrainId;
return o != null && Key.Equals(o.Key);
}
public override bool Equals(object obj)
{
var o = obj as GrainId;
return o != null && Key.Equals(o.Key);
}
// Keep compiler happy -- it does not like classes to have Equals(...) without GetHashCode() methods
public override int GetHashCode()
{
return Key.GetHashCode();
}
/// <summary>
/// Get a uniformly distributed hash code value for this grain, based on Jenkins Hash function.
/// NOTE: Hash code value may be positive or NEGATIVE.
/// </summary>
/// <returns>Hash code for this GrainId</returns>
public uint GetUniformHashCode()
{
return Key.GetUniformHashCode();
}
public override string ToString()
{
return ToStringImpl(false);
}
// same as ToString, just full primary key and type code
internal string ToDetailedString()
{
return ToStringImpl(true);
}
// same as ToString, just full primary key and type code
private string ToStringImpl(bool detailed)
{
string name = string.Empty;
if (Constants.TryGetSystemGrainName(this, out name))
{
return name;
}
var keyString = Key.ToString();
// this should grab the least-significant half of n1, suffixing it with the key extension.
string idString = keyString;
if (!detailed)
{
if (keyString.Length >= 48)
idString = keyString.Substring(24, 8) + keyString.Substring(48);
else
idString = keyString.Substring(24, 8);
}
string fullString = null;
switch (Category)
{
case UniqueKey.Category.Grain:
case UniqueKey.Category.KeyExtGrain:
var typeString = GetTypeCode().ToString("X");
if (!detailed) typeString = typeString.Tail(8);
fullString = String.Format("*grn/{0}/{1}", typeString, idString);
break;
case UniqueKey.Category.Client:
fullString = "*cli/" + idString;
break;
case UniqueKey.Category.GeoClient:
fullString = string.Format("*gcl/{0}/{1}", Key.KeyExt, idString);
break;
case UniqueKey.Category.SystemTarget:
string explicitName = Constants.SystemTargetName(this);
if (GetTypeCode() != 0)
{
var typeStr = GetTypeCode().ToString("X");
return String.Format("{0}/{1}/{2}", explicitName, typeStr, idString);
}
fullString = explicitName;
break;
default:
fullString = "???/" + idString;
break;
}
return detailed ? String.Format("{0}-0x{1, 8:X8}", fullString, GetUniformHashCode()) : fullString;
}
internal string ToFullString()
{
string kx;
string pks =
Key.IsLongKey ?
GetPrimaryKeyLong(out kx).ToString(CultureInfo.InvariantCulture) :
GetPrimaryKey(out kx).ToString();
string pksHex =
Key.IsLongKey ?
GetPrimaryKeyLong(out kx).ToString("X") :
GetPrimaryKey(out kx).ToString("X");
return
String.Format(
"[GrainId: {0}, IdCategory: {1}, BaseTypeCode: {2} (x{3}), PrimaryKey: {4} (x{5}), UniformHashCode: {6} (0x{7, 8:X8}){8}]",
ToDetailedString(), // 0
Category, // 1
GetTypeCode(), // 2
GetTypeCode().ToString("X"), // 3
pks, // 4
pksHex, // 5
GetUniformHashCode(), // 6
GetUniformHashCode(), // 7
Key.HasKeyExt ? String.Format(", KeyExtension: {0}", kx) : ""); // 8
}
internal string ToStringWithHashCode()
{
return String.Format("{0}-0x{1, 8:X8}", this.ToString(), this.GetUniformHashCode());
}
/// <summary>
/// Return this GrainId in a standard string form, suitable for later use with the <c>FromParsableString</c> method.
/// </summary>
/// <returns>GrainId in a standard string format.</returns>
internal string ToParsableString()
{
// NOTE: This function must be the "inverse" of FromParsableString, and data must round-trip reliably.
return Key.ToHexString();
}
/// <summary>
/// Create a new GrainId object by parsing string in a standard form returned from <c>ToParsableString</c> method.
/// </summary>
/// <param name="grainId">String containing the GrainId info to be parsed.</param>
/// <returns>New GrainId object created from the input data.</returns>
internal static GrainId FromParsableString(string grainId)
{
// NOTE: This function must be the "inverse" of ToParsableString, and data must round-trip reliably.
var key = UniqueKey.Parse(grainId);
return FindOrCreateGrainId(key);
}
internal byte[] ToByteArray()
{
var writer = new BinaryTokenStreamWriter();
writer.Write(this);
var result = writer.ToByteArray();
writer.ReleaseBuffers();
return result;
}
internal static GrainId FromByteArray(byte[] byteArray)
{
var reader = new BinaryTokenStreamReader(byteArray);
return reader.ReadGrainId();
}
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
// MONO 1.0 Beta mcs does not like #if !A && !B && !C syntax
// .NET Compact Framework 1.0 has no support for Win32 NetMessageBufferSend API
#if !NETCF
// MONO 1.0 has no support for Win32 NetMessageBufferSend API
#if !MONO
// SSCLI 1.0 has no support for Win32 NetMessageBufferSend API
#if !SSCLI
// We don't want framework or platform specific code in the CLI version of log4net
#if !CLI_1_0
#if !NETMF
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using log4net.Util;
using log4net.Layout;
using log4net.Core;
namespace log4net.Appender
{
/// <summary>
/// Logs entries by sending network messages using the
/// <see cref="NetMessageBufferSend" /> native function.
/// </summary>
/// <remarks>
/// <para>
/// You can send messages only to names that are active
/// on the network. If you send the message to a user name,
/// that user must be logged on and running the Messenger
/// service to receive the message.
/// </para>
/// <para>
/// The receiver will get a top most window displaying the
/// messages one at a time, therefore this appender should
/// not be used to deliver a high volume of messages.
/// </para>
/// <para>
/// The following table lists some possible uses for this appender :
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Action</term>
/// <description>Property Value(s)</description>
/// </listheader>
/// <item>
/// <term>Send a message to a user account on the local machine</term>
/// <description>
/// <para>
/// <see cref="NetSendAppender.Server"/> = <name of the local machine>
/// </para>
/// <para>
/// <see cref="NetSendAppender.Recipient"/> = <user name>
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>Send a message to a user account on a remote machine</term>
/// <description>
/// <para>
/// <see cref="NetSendAppender.Server"/> = <name of the remote machine>
/// </para>
/// <para>
/// <see cref="NetSendAppender.Recipient"/> = <user name>
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>Send a message to a domain user account</term>
/// <description>
/// <para>
/// <see cref="NetSendAppender.Server"/> = <name of a domain controller | uninitialized>
/// </para>
/// <para>
/// <see cref="NetSendAppender.Recipient"/> = <user name>
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>Send a message to all the names in a workgroup or domain</term>
/// <description>
/// <para>
/// <see cref="NetSendAppender.Recipient"/> = <workgroup name | domain name>*
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>Send a message from the local machine to a remote machine</term>
/// <description>
/// <para>
/// <see cref="NetSendAppender.Server"/> = <name of the local machine | uninitialized>
/// </para>
/// <para>
/// <see cref="NetSendAppender.Recipient"/> = <name of the remote machine>
/// </para>
/// </description>
/// </item>
/// </list>
/// </para>
/// <para>
/// <b>Note :</b> security restrictions apply for sending
/// network messages, see <see cref="NetMessageBufferSend" />
/// for more information.
/// </para>
/// </remarks>
/// <example>
/// <para>
/// An example configuration section to log information
/// using this appender from the local machine, named
/// LOCAL_PC, to machine OPERATOR_PC :
/// </para>
/// <code lang="XML" escaped="true">
/// <appender name="NetSendAppender_Operator" type="log4net.Appender.NetSendAppender">
/// <server value="LOCAL_PC" />
/// <recipient value="OPERATOR_PC" />
/// <layout type="log4net.Layout.PatternLayout" value="%-5p %c [%x] - %m%n" />
/// </appender>
/// </code>
/// </example>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public class NetSendAppender : AppenderSkeleton
{
#region Member Variables
/// <summary>
/// The DNS or NetBIOS name of the server on which the function is to execute.
/// </summary>
private string m_server;
/// <summary>
/// The sender of the network message.
/// </summary>
private string m_sender;
/// <summary>
/// The message alias to which the message should be sent.
/// </summary>
private string m_recipient;
/// <summary>
/// The security context to use for privileged calls
/// </summary>
private SecurityContext m_securityContext;
#endregion
#region Constructors
/// <summary>
/// Initializes the appender.
/// </summary>
/// <remarks>
/// The default constructor initializes all fields to their default values.
/// </remarks>
public NetSendAppender()
{
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the sender of the message.
/// </summary>
/// <value>
/// The sender of the message.
/// </value>
/// <remarks>
/// If this property is not specified, the message is sent from the local computer.
/// </remarks>
public string Sender
{
get { return m_sender; }
set { m_sender = value; }
}
/// <summary>
/// Gets or sets the message alias to which the message should be sent.
/// </summary>
/// <value>
/// The recipient of the message.
/// </value>
/// <remarks>
/// This property should always be specified in order to send a message.
/// </remarks>
public string Recipient
{
get { return m_recipient; }
set { m_recipient = value; }
}
/// <summary>
/// Gets or sets the DNS or NetBIOS name of the remote server on which the function is to execute.
/// </summary>
/// <value>
/// DNS or NetBIOS name of the remote server on which the function is to execute.
/// </value>
/// <remarks>
/// <para>
/// For Windows NT 4.0 and earlier, the string should begin with \\.
/// </para>
/// <para>
/// If this property is not specified, the local computer is used.
/// </para>
/// </remarks>
public string Server
{
get { return m_server; }
set { m_server = value; }
}
/// <summary>
/// Gets or sets the <see cref="SecurityContext"/> used to call the NetSend method.
/// </summary>
/// <value>
/// The <see cref="SecurityContext"/> used to call the NetSend method.
/// </value>
/// <remarks>
/// <para>
/// Unless a <see cref="SecurityContext"/> specified here for this appender
/// the <see cref="SecurityContextProvider.DefaultProvider"/> is queried for the
/// security context to use. The default behavior is to use the security context
/// of the current thread.
/// </para>
/// </remarks>
public SecurityContext SecurityContext
{
get { return m_securityContext; }
set { m_securityContext = value; }
}
#endregion
#region Implementation of IOptionHandler
/// <summary>
/// Initialize the appender based on the options set.
/// </summary>
/// <remarks>
/// <para>
/// This is part of the <see cref="IOptionHandler"/> delayed object
/// activation scheme. The <see cref="ActivateOptions"/> method must
/// be called on this object after the configuration properties have
/// been set. Until <see cref="ActivateOptions"/> is called this
/// object is in an undefined state and must not be used.
/// </para>
/// <para>
/// If any of the configuration properties are modified then
/// <see cref="ActivateOptions"/> must be called again.
/// </para>
/// <para>
/// The appender will be ignored if no <see cref="Recipient" /> was specified.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException">The required property <see cref="Recipient" /> was not specified.</exception>
public override void ActivateOptions()
{
base.ActivateOptions();
if (this.Recipient == null)
{
throw new ArgumentNullException("Recipient", "The required property 'Recipient' was not specified.");
}
if (m_securityContext == null)
{
m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this);
}
}
#endregion
#region Override implementation of AppenderSkeleton
/// <summary>
/// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(LoggingEvent)"/> method.
/// </summary>
/// <param name="loggingEvent">The event to log.</param>
/// <remarks>
/// <para>
/// Sends the event using a network message.
/// </para>
/// </remarks>
#if NET_4_0
[System.Security.SecuritySafeCritical]
#endif
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)]
protected override void Append(LoggingEvent loggingEvent)
{
NativeError nativeError = null;
// Render the event in the callers security context
string renderedLoggingEvent = RenderLoggingEvent(loggingEvent);
using(m_securityContext.Impersonate(this))
{
// Send the message
int returnValue = NetMessageBufferSend(this.Server, this.Recipient, this.Sender, renderedLoggingEvent, renderedLoggingEvent.Length * Marshal.SystemDefaultCharSize);
// Log the error if the message could not be sent
if (returnValue != 0)
{
// Lookup the native error
nativeError = NativeError.GetError(returnValue);
}
}
if (nativeError != null)
{
// Handle the error over to the ErrorHandler
ErrorHandler.Error(nativeError.ToString() + " (Params: Server=" + this.Server + ", Recipient=" + this.Recipient + ", Sender=" + this.Sender + ")");
}
}
/// <summary>
/// This appender requires a <see cref="Layout"/> to be set.
/// </summary>
/// <value><c>true</c></value>
/// <remarks>
/// <para>
/// This appender requires a <see cref="Layout"/> to be set.
/// </para>
/// </remarks>
override protected bool RequiresLayout
{
get { return true; }
}
#endregion
#region Stubs For Native Function Calls
/// <summary>
/// Sends a buffer of information to a registered message alias.
/// </summary>
/// <param name="serverName">The DNS or NetBIOS name of the server on which the function is to execute.</param>
/// <param name="msgName">The message alias to which the message buffer should be sent</param>
/// <param name="fromName">The originator of the message.</param>
/// <param name="buffer">The message text.</param>
/// <param name="bufferSize">The length, in bytes, of the message text.</param>
/// <remarks>
/// <para>
/// The following restrictions apply for sending network messages:
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Platform</term>
/// <description>Requirements</description>
/// </listheader>
/// <item>
/// <term>Windows NT</term>
/// <description>
/// <para>
/// No special group membership is required to send a network message.
/// </para>
/// <para>
/// Admin, Accounts, Print, or Server Operator group membership is required to
/// successfully send a network message on a remote server.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>Windows 2000 or later</term>
/// <description>
/// <para>
/// If you send a message on a domain controller that is running Active Directory,
/// access is allowed or denied based on the access control list (ACL) for the securable
/// object. The default ACL permits only Domain Admins and Account Operators to send a network message.
/// </para>
/// <para>
/// On a member server or workstation, only Administrators and Server Operators can send a network message.
/// </para>
/// </description>
/// </item>
/// </list>
/// </para>
/// <para>
/// For more information see <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/netmgmt/netmgmt/security_requirements_for_the_network_management_functions.asp">Security Requirements for the Network Management Functions</a>.
/// </para>
/// </remarks>
/// <returns>
/// <para>
/// If the function succeeds, the return value is zero.
/// </para>
/// </returns>
[DllImport("netapi32.dll", SetLastError=true)]
protected static extern int NetMessageBufferSend(
[MarshalAs(UnmanagedType.LPWStr)] string serverName,
[MarshalAs(UnmanagedType.LPWStr)] string msgName,
[MarshalAs(UnmanagedType.LPWStr)] string fromName,
[MarshalAs(UnmanagedType.LPWStr)] string buffer,
int bufferSize);
#endregion
}
}
#endif
#endif // !CLI_1_0
#endif // !SSCLI
#endif // !MONO
#endif // !NETCF
| |
/* Generated SBE (Simple Binary Encoding) message codec */
#pragma warning disable 1591 // disable warning on missing comments
using System;
using Adaptive.SimpleBinaryEncoding;
namespace Adaptive.SimpleBinaryEncoding.Tests.Generated
{
public class MDIncrementalRefreshLimtsBanding
{
public const ushort TemplateId = (ushort)8;
public const byte TemplateVersion = (byte)1;
public const ushort BlockLength = (ushort)9;
public const string SematicType = "X";
private readonly MDIncrementalRefreshLimtsBanding _parentMessage;
private DirectBuffer _buffer;
private int _offset;
private int _limit;
private int _actingBlockLength;
private int _actingVersion;
public int Offset { get { return _offset; } }
public MDIncrementalRefreshLimtsBanding()
{
_parentMessage = this;
}
public void WrapForEncode(DirectBuffer buffer, int offset)
{
_buffer = buffer;
_offset = offset;
_actingBlockLength = BlockLength;
_actingVersion = TemplateVersion;
Limit = offset + _actingBlockLength;
}
public void WrapForDecode(DirectBuffer buffer, int offset,
int actingBlockLength, int actingVersion)
{
_buffer = buffer;
_offset = offset;
_actingBlockLength = actingBlockLength;
_actingVersion = actingVersion;
Limit = offset + _actingBlockLength;
}
public int Size
{
get
{
return _limit - _offset;
}
}
public int Limit
{
get
{
return _limit;
}
set
{
_buffer.CheckLimit(value);
_limit = value;
}
}
public const int TransactTimeSchemaId = 60;
public static string TransactTimeMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "UTCTimestamp";
}
return "";
}
public const ulong TransactTimeNullValue = 0x8000000000000000UL;
public const ulong TransactTimeMinValue = 0x0UL;
public const ulong TransactTimeMaxValue = 0x7fffffffffffffffUL;
public ulong TransactTime
{
get
{
return _buffer.Uint64GetLittleEndian(_offset + 0);
}
set
{
_buffer.Uint64PutLittleEndian(_offset + 0, value);
}
}
public const int MatchEventIndicatorSchemaId = 5799;
public static string MatchEventIndicatorMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "MultipleCharValue";
}
return "";
}
public MatchEventIndicator MatchEventIndicator
{
get
{
return (MatchEventIndicator)_buffer.Uint8Get(_offset + 8);
}
set
{
_buffer.Uint8Put(_offset + 8, (byte)value);
}
}
private readonly NoMDEntriesGroup _noMDEntries = new NoMDEntriesGroup();
public const long NoMDEntriesSchemaId = 268;
public NoMDEntriesGroup NoMDEntries
{
get
{
_noMDEntries.WrapForDecode(_parentMessage, _buffer, _actingVersion);
return _noMDEntries;
}
}
public NoMDEntriesGroup NoMDEntriesCount(int count)
{
_noMDEntries.WrapForEncode(_parentMessage, _buffer, count);
return _noMDEntries;
}
public class NoMDEntriesGroup
{
private readonly GroupSize _dimensions = new GroupSize();
private MDIncrementalRefreshLimtsBanding _parentMessage;
private DirectBuffer _buffer;
private int _blockLength;
private int _actingVersion;
private int _count;
private int _index;
private int _offset;
public void WrapForDecode(MDIncrementalRefreshLimtsBanding parentMessage, DirectBuffer buffer, int actingVersion)
{
_parentMessage = parentMessage;
_buffer = buffer;
_dimensions.Wrap(buffer, parentMessage.Limit, actingVersion);
_count = _dimensions.NumInGroup;
_blockLength = _dimensions.BlockLength;
_actingVersion = actingVersion;
_index = -1;
_parentMessage.Limit = parentMessage.Limit + 3;
}
public void WrapForEncode(MDIncrementalRefreshLimtsBanding parentMessage, DirectBuffer buffer, int count)
{
_parentMessage = parentMessage;
_buffer = buffer;
_dimensions.Wrap(buffer, parentMessage.Limit, _actingVersion);
_dimensions.NumInGroup = (byte)count;
_dimensions.BlockLength = (ushort)32;
_index = -1;
_count = count;
_blockLength = 32;
parentMessage.Limit = parentMessage.Limit + 3;
}
public int Count { get { return _count; } }
public bool HasNext { get { return _index + 1 < _count; } }
public NoMDEntriesGroup Next()
{
if (_index + 1 >= _count)
{
throw new InvalidOperationException();
}
_offset = _parentMessage.Limit;
_parentMessage.Limit = _offset + _blockLength;
++_index;
return this;
}
public const int MDUpdateActionSchemaId = 279;
public static string MDUpdateActionMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "int";
}
return "";
}
public const sbyte MDUpdateActionNullValue = (sbyte)-128;
public const sbyte MDUpdateActionMinValue = (sbyte)-127;
public const sbyte MDUpdateActionMaxValue = (sbyte)127;
public sbyte MDUpdateAction { get { return (sbyte)0; } }
public const int MDEntryTypeSchemaId = 269;
public static string MDEntryTypeMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "char";
}
return "";
}
public const byte MDEntryTypeNullValue = (byte)0;
public const byte MDEntryTypeMinValue = (byte)32;
public const byte MDEntryTypeMaxValue = (byte)126;
private static readonly byte[] _MDEntryTypeValue = {103};
public const int MDEntryTypeLength = 1;
public byte MDEntryType(int index)
{
return _MDEntryTypeValue[index];
}
public int GetMDEntryType(byte[] dst, int offset, int length)
{
int bytesCopied = Math.Min(length, 1);
Array.Copy(_MDEntryTypeValue, 0, dst, offset, bytesCopied);
return bytesCopied;
}
public const int SecurityIDSchemaId = 48;
public static string SecurityIDMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "int";
}
return "";
}
public const int SecurityIDNullValue = -2147483648;
public const int SecurityIDMinValue = -2147483647;
public const int SecurityIDMaxValue = 2147483647;
public int SecurityID
{
get
{
return _buffer.Int32GetLittleEndian(_offset + 0);
}
set
{
_buffer.Int32PutLittleEndian(_offset + 0, value);
}
}
public const int RptSeqSchemaId = 83;
public static string RptSeqMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "int";
}
return "";
}
public const int RptSeqNullValue = -2147483648;
public const int RptSeqMinValue = -2147483647;
public const int RptSeqMaxValue = 2147483647;
public int RptSeq
{
get
{
return _buffer.Int32GetLittleEndian(_offset + 4);
}
set
{
_buffer.Int32PutLittleEndian(_offset + 4, value);
}
}
public const int LowLimitPriceSchemaId = 1148;
public static string LowLimitPriceMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "Price";
}
return "";
}
private readonly PRICENULL _lowLimitPrice = new PRICENULL();
public PRICENULL LowLimitPrice
{
get
{
_lowLimitPrice.Wrap(_buffer, _offset + 8, _actingVersion);
return _lowLimitPrice;
}
}
public const int HighLimitPriceSchemaId = 1149;
public static string HighLimitPriceMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "Price";
}
return "";
}
private readonly PRICENULL _highLimitPrice = new PRICENULL();
public PRICENULL HighLimitPrice
{
get
{
_highLimitPrice.Wrap(_buffer, _offset + 16, _actingVersion);
return _highLimitPrice;
}
}
public const int MaxPriceVariationSchemaId = 1143;
public static string MaxPriceVariationMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "Price";
}
return "";
}
private readonly PRICENULL _maxPriceVariation = new PRICENULL();
public PRICENULL MaxPriceVariation
{
get
{
_maxPriceVariation.Wrap(_buffer, _offset + 24, _actingVersion);
return _maxPriceVariation;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NuGet;
using Splat;
using Squirrel;
using Squirrel.Tests.TestHelpers;
using Xunit;
namespace Squirrel.Tests
{
public class FakeUrlDownloader : IFileDownloader
{
public Task<byte[]> DownloadUrl(string url)
{
return Task.FromResult(new byte[0]);
}
public async Task DownloadFile(string url, string targetFile, Action<int> progress)
{
}
}
public class ApplyReleasesTests : IEnableLogger
{
[Fact]
public async Task CleanInstallRunsSquirrelAwareAppsWithInstallFlag()
{
string tempDir;
string remotePkgDir;
using (Utility.WithTempDirectory(out tempDir))
using (Utility.WithTempDirectory(out remotePkgDir)) {
IntegrationTestHelper.CreateFakeInstalledApp("0.1.0", remotePkgDir);
var pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir);
ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES"));
using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) {
await fixture.FullInstall();
// NB: We execute the Squirrel-aware apps, so we need to give
// them a minute to settle or else the using statement will
// try to blow away a running process
await Task.Delay(1000);
Assert.False(File.Exists(Path.Combine(tempDir, "theApp", "app-0.1.0", "args2.txt")));
Assert.True(File.Exists(Path.Combine(tempDir, "theApp", "app-0.1.0", "args.txt")));
var text = File.ReadAllText(Path.Combine(tempDir, "theApp", "app-0.1.0", "args.txt"), Encoding.UTF8);
Assert.Contains("firstrun", text);
}
}
}
[Fact]
public async Task UpgradeRunsSquirrelAwareAppsWithUpgradeFlag()
{
string tempDir;
string remotePkgDir;
using (Utility.WithTempDirectory(out tempDir))
using (Utility.WithTempDirectory(out remotePkgDir)) {
IntegrationTestHelper.CreateFakeInstalledApp("0.1.0", remotePkgDir);
var pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir);
ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES"));
using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) {
await fixture.FullInstall();
}
await Task.Delay(1000);
IntegrationTestHelper.CreateFakeInstalledApp("0.2.0", remotePkgDir);
pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir);
ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES"));
using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) {
await fixture.UpdateApp();
}
await Task.Delay(1000);
Assert.False(File.Exists(Path.Combine(tempDir, "theApp", "app-0.2.0", "args2.txt")));
Assert.True(File.Exists(Path.Combine(tempDir, "theApp", "app-0.2.0", "args.txt")));
var text = File.ReadAllText(Path.Combine(tempDir, "theApp", "app-0.2.0", "args.txt"), Encoding.UTF8);
Assert.Contains("updated|0.2.0", text);
}
}
[Fact]
public async Task RunningUpgradeAppTwiceDoesntCrash()
{
string tempDir;
string remotePkgDir;
using (Utility.WithTempDirectory(out tempDir))
using (Utility.WithTempDirectory(out remotePkgDir)) {
IntegrationTestHelper.CreateFakeInstalledApp("0.1.0", remotePkgDir);
var pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir);
ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES"));
using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) {
await fixture.FullInstall();
}
await Task.Delay(1000);
IntegrationTestHelper.CreateFakeInstalledApp("0.2.0", remotePkgDir);
pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir);
ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES"));
using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) {
await fixture.UpdateApp();
}
await Task.Delay(1000);
// NB: The 2nd time we won't have any updates to apply. We should just do nothing!
using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) {
await fixture.UpdateApp();
}
await Task.Delay(1000);
}
}
[Fact]
public async Task FullUninstallRemovesAllVersions()
{
string tempDir;
string remotePkgDir;
using (Utility.WithTempDirectory(out tempDir))
using (Utility.WithTempDirectory(out remotePkgDir)) {
IntegrationTestHelper.CreateFakeInstalledApp("0.1.0", remotePkgDir);
var pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir);
ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES"));
using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) {
await fixture.FullInstall();
}
await Task.Delay(1000);
IntegrationTestHelper.CreateFakeInstalledApp("0.2.0", remotePkgDir);
pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir);
ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES"));
using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) {
await fixture.UpdateApp();
}
await Task.Delay(1000);
using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) {
await fixture.FullUninstall();
}
Assert.False(File.Exists(Path.Combine(tempDir, "theApp", "app-0.1.0", "args.txt")));
Assert.False(File.Exists(Path.Combine(tempDir, "theApp", "app-0.2.0", "args.txt")));
Assert.True(File.Exists(Path.Combine(tempDir, "theApp", ".dead")));
}
}
[Fact]
public void WhenNoNewReleasesAreAvailableTheListIsEmpty()
{
string tempDir;
using (Utility.WithTempDirectory(out tempDir)) {
var appDir = Directory.CreateDirectory(Path.Combine(tempDir, "theApp"));
var packages = Path.Combine(appDir.FullName, "packages");
Directory.CreateDirectory(packages);
var package = "Squirrel.Core.1.0.0.0-full.nupkg";
File.Copy(IntegrationTestHelper.GetPath("fixtures", package), Path.Combine(packages, package));
var aGivenPackage = Path.Combine(packages, package);
var baseEntry = ReleaseEntry.GenerateFromFile(aGivenPackage);
var updateInfo = UpdateInfo.Create(baseEntry, new[] { baseEntry }, "dontcare");
Assert.Empty(updateInfo.ReleasesToApply);
}
}
[Fact]
public void ThrowsWhenOnlyDeltaReleasesAreAvailable()
{
string tempDir;
using (Utility.WithTempDirectory(out tempDir))
{
var appDir = Directory.CreateDirectory(Path.Combine(tempDir, "theApp"));
var packages = Path.Combine(appDir.FullName, "packages");
Directory.CreateDirectory(packages);
var baseFile = "Squirrel.Core.1.0.0.0-full.nupkg";
File.Copy(IntegrationTestHelper.GetPath("fixtures", baseFile),
Path.Combine(packages, baseFile));
var basePackage = Path.Combine(packages, baseFile);
var baseEntry = ReleaseEntry.GenerateFromFile(basePackage);
var deltaFile = "Squirrel.Core.1.1.0.0-delta.nupkg";
File.Copy(IntegrationTestHelper.GetPath("fixtures", deltaFile),
Path.Combine(packages, deltaFile));
var deltaPackage = Path.Combine(packages, deltaFile);
var deltaEntry = ReleaseEntry.GenerateFromFile(deltaPackage);
Assert.Throws<Exception>(
() => UpdateInfo.Create(baseEntry, new[] { deltaEntry }, "dontcare"));
}
}
[Fact]
public async Task ApplyReleasesWithOneReleaseFile()
{
string tempDir;
using (Utility.WithTempDirectory(out tempDir)) {
string appDir = Path.Combine(tempDir, "theApp");
string packagesDir = Path.Combine(appDir, "packages");
Directory.CreateDirectory(packagesDir);
new[] {
"Squirrel.Core.1.0.0.0-full.nupkg",
"Squirrel.Core.1.1.0.0-full.nupkg",
}.ForEach(x => File.Copy(IntegrationTestHelper.GetPath("fixtures", x), Path.Combine(packagesDir, x)));
var fixture = new UpdateManager.ApplyReleasesImpl(appDir);
var baseEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.0.0.0-full.nupkg"));
var latestFullEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.1.0.0-full.nupkg"));
var updateInfo = UpdateInfo.Create(baseEntry, new[] { latestFullEntry }, packagesDir);
updateInfo.ReleasesToApply.Contains(latestFullEntry).ShouldBeTrue();
var progress = new List<int>();
await fixture.ApplyReleases(updateInfo, false, false, progress.Add);
this.Log().Info("Progress: [{0}]", String.Join(",", progress));
progress
.Aggregate(0, (acc, x) => { x.ShouldBeGreaterThan(acc); return x; })
.ShouldEqual(100);
var filesToFind = new[] {
new {Name = "NLog.dll", Version = new Version("2.0.0.0")},
new {Name = "NSync.Core.dll", Version = new Version("1.1.0.0")},
};
filesToFind.ForEach(x => {
var path = Path.Combine(tempDir, "theApp", "app-1.1.0.0", x.Name);
this.Log().Info("Looking for {0}", path);
File.Exists(path).ShouldBeTrue();
var vi = FileVersionInfo.GetVersionInfo(path);
var verInfo = new Version(vi.FileVersion ?? "1.0.0.0");
x.Version.ShouldEqual(verInfo);
});
}
}
[Fact]
public async Task ApplyReleaseWhichRemovesAFile()
{
string tempDir;
using (Utility.WithTempDirectory(out tempDir)) {
string appDir = Path.Combine(tempDir, "theApp");
string packagesDir = Path.Combine(appDir, "packages");
Directory.CreateDirectory(packagesDir);
new[] {
"Squirrel.Core.1.1.0.0-full.nupkg",
"Squirrel.Core.1.2.0.0-full.nupkg",
}.ForEach(x => File.Copy(IntegrationTestHelper.GetPath("fixtures", x), Path.Combine(packagesDir, x)));
var fixture = new UpdateManager.ApplyReleasesImpl(appDir);
var baseEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.1.0.0-full.nupkg"));
var latestFullEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.2.0.0-full.nupkg"));
var updateInfo = UpdateInfo.Create(baseEntry, new[] { latestFullEntry }, packagesDir);
updateInfo.ReleasesToApply.Contains(latestFullEntry).ShouldBeTrue();
var progress = new List<int>();
await fixture.ApplyReleases(updateInfo, false, false, progress.Add);
this.Log().Info("Progress: [{0}]", String.Join(",", progress));
progress
.Aggregate(0, (acc, x) => { x.ShouldBeGreaterThan(acc); return x; })
.ShouldEqual(100);
var rootDirectory = Path.Combine(tempDir, "theApp", "app-1.2.0.0");
new[] {
new {Name = "NLog.dll", Version = new Version("2.0.0.0")},
new {Name = "NSync.Core.dll", Version = new Version("1.1.0.0")},
}.ForEach(x => {
var path = Path.Combine(rootDirectory, x.Name);
this.Log().Info("Looking for {0}", path);
File.Exists(path).ShouldBeTrue();
});
var removedFile = Path.Combine("sub", "Ionic.Zip.dll");
var deployedPath = Path.Combine(rootDirectory, removedFile);
File.Exists(deployedPath).ShouldBeFalse();
}
}
[Fact]
public async Task ApplyReleaseWhichMovesAFileToADifferentDirectory()
{
string tempDir;
using (Utility.WithTempDirectory(out tempDir))
{
string appDir = Path.Combine(tempDir, "theApp");
string packagesDir = Path.Combine(appDir, "packages");
Directory.CreateDirectory(packagesDir);
new[] {
"Squirrel.Core.1.1.0.0-full.nupkg",
"Squirrel.Core.1.3.0.0-full.nupkg",
}.ForEach(x => File.Copy(IntegrationTestHelper.GetPath("fixtures", x), Path.Combine(packagesDir, x)));
var fixture = new UpdateManager.ApplyReleasesImpl(appDir);
var baseEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.1.0.0-full.nupkg"));
var latestFullEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.3.0.0-full.nupkg"));
var updateInfo = UpdateInfo.Create(baseEntry, new[] { latestFullEntry }, packagesDir);
updateInfo.ReleasesToApply.Contains(latestFullEntry).ShouldBeTrue();
var progress = new List<int>();
await fixture.ApplyReleases(updateInfo, false, false, progress.Add);
this.Log().Info("Progress: [{0}]", String.Join(",", progress));
progress
.Aggregate(0, (acc, x) => { x.ShouldBeGreaterThan(acc); return x; })
.ShouldEqual(100);
var rootDirectory = Path.Combine(tempDir, "theApp", "app-1.3.0.0");
new[] {
new {Name = "NLog.dll", Version = new Version("2.0.0.0")},
new {Name = "NSync.Core.dll", Version = new Version("1.1.0.0")},
}.ForEach(x => {
var path = Path.Combine(rootDirectory, x.Name);
this.Log().Info("Looking for {0}", path);
File.Exists(path).ShouldBeTrue();
});
var oldFile = Path.Combine(rootDirectory, "sub", "Ionic.Zip.dll");
File.Exists(oldFile).ShouldBeFalse();
var newFile = Path.Combine(rootDirectory, "other", "Ionic.Zip.dll");
File.Exists(newFile).ShouldBeTrue();
}
}
[Fact]
public async Task ApplyReleasesWithDeltaReleases()
{
string tempDir;
using (Utility.WithTempDirectory(out tempDir)) {
string appDir = Path.Combine(tempDir, "theApp");
string packagesDir = Path.Combine(appDir, "packages");
Directory.CreateDirectory(packagesDir);
new[] {
"Squirrel.Core.1.0.0.0-full.nupkg",
"Squirrel.Core.1.1.0.0-delta.nupkg",
"Squirrel.Core.1.1.0.0-full.nupkg",
}.ForEach(x => File.Copy(IntegrationTestHelper.GetPath("fixtures", x), Path.Combine(packagesDir, x)));
var fixture = new UpdateManager.ApplyReleasesImpl(appDir);
var baseEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.0.0.0-full.nupkg"));
var deltaEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.1.0.0-delta.nupkg"));
var latestFullEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.1.0.0-full.nupkg"));
var updateInfo = UpdateInfo.Create(baseEntry, new[] { deltaEntry, latestFullEntry }, packagesDir);
updateInfo.ReleasesToApply.Contains(deltaEntry).ShouldBeTrue();
var progress = new List<int>();
await fixture.ApplyReleases(updateInfo, false, false, progress.Add);
this.Log().Info("Progress: [{0}]", String.Join(",", progress));
progress
.Aggregate(0, (acc, x) => { x.ShouldBeGreaterThan(acc); return x; })
.ShouldEqual(100);
var filesToFind = new[] {
new {Name = "NLog.dll", Version = new Version("2.0.0.0")},
new {Name = "NSync.Core.dll", Version = new Version("1.1.0.0")},
};
filesToFind.ForEach(x => {
var path = Path.Combine(tempDir, "theApp", "app-1.1.0.0", x.Name);
this.Log().Info("Looking for {0}", path);
File.Exists(path).ShouldBeTrue();
var vi = FileVersionInfo.GetVersionInfo(path);
var verInfo = new Version(vi.FileVersion ?? "1.0.0.0");
x.Version.ShouldEqual(verInfo);
});
}
}
[Fact]
public async Task CreateFullPackagesFromDeltaSmokeTest()
{
string tempDir;
using (Utility.WithTempDirectory(out tempDir)) {
string appDir = Path.Combine(tempDir, "theApp");
string packagesDir = Path.Combine(appDir, "packages");
Directory.CreateDirectory(packagesDir);
new[] {
"Squirrel.Core.1.0.0.0-full.nupkg",
"Squirrel.Core.1.1.0.0-delta.nupkg"
}.ForEach(x => File.Copy(IntegrationTestHelper.GetPath("fixtures", x), Path.Combine(tempDir, "theApp", "packages", x)));
var urlDownloader = new FakeUrlDownloader();
var fixture = new UpdateManager.ApplyReleasesImpl(appDir);
var baseEntry = ReleaseEntry.GenerateFromFile(Path.Combine(tempDir, "theApp", "packages", "Squirrel.Core.1.0.0.0-full.nupkg"));
var deltaEntry = ReleaseEntry.GenerateFromFile(Path.Combine(tempDir, "theApp", "packages", "Squirrel.Core.1.1.0.0-delta.nupkg"));
var resultObs = (Task<ReleaseEntry>)fixture.GetType().GetMethod("createFullPackagesFromDeltas", BindingFlags.NonPublic | BindingFlags.Instance)
.Invoke(fixture, new object[] { new[] {deltaEntry}, baseEntry });
var result = await resultObs;
var zp = new ZipPackage(Path.Combine(tempDir, "theApp", "packages", result.Filename));
zp.Version.ToString().ShouldEqual("1.1.0.0");
}
}
[Fact]
public async Task CreateShortcutsRoundTrip()
{
string remotePkgPath;
string path;
using (Utility.WithTempDirectory(out path)) {
using (Utility.WithTempDirectory(out remotePkgPath))
using (var mgr = new UpdateManager(remotePkgPath, "theApp", path)) {
IntegrationTestHelper.CreateFakeInstalledApp("1.0.0.1", remotePkgPath);
await mgr.FullInstall();
}
var fixture = new UpdateManager.ApplyReleasesImpl(Path.Combine(path, "theApp"));
fixture.CreateShortcutsForExecutable("SquirrelAwareApp.exe", ShortcutLocation.Desktop | ShortcutLocation.StartMenu | ShortcutLocation.Startup | ShortcutLocation.AppRoot, false, null, null);
// NB: COM is Weird.
Thread.Sleep(1000);
fixture.RemoveShortcutsForExecutable("SquirrelAwareApp.exe", ShortcutLocation.Desktop | ShortcutLocation.StartMenu | ShortcutLocation.Startup | ShortcutLocation.AppRoot);
// NB: Squirrel-Aware first-run might still be running, slow
// our roll before blowing away the temp path
Thread.Sleep(1000);
}
}
[Fact]
public void UnshimOurselvesSmokeTest()
{
// NB: This smoke test is really more of a manual test - try it
// by shimming Slack, then verifying the shim goes away
var appDir = Environment.ExpandEnvironmentVariables(@"%LocalAppData%\Slack");
var fixture = new UpdateManager.ApplyReleasesImpl(appDir);
fixture.unshimOurselves();
}
[Fact]
public async Task GetShortcutsSmokeTest()
{
string remotePkgPath;
string path;
using (Utility.WithTempDirectory(out path)) {
using (Utility.WithTempDirectory(out remotePkgPath))
using (var mgr = new UpdateManager(remotePkgPath, "theApp", path)) {
IntegrationTestHelper.CreateFakeInstalledApp("1.0.0.1", remotePkgPath);
await mgr.FullInstall();
}
var fixture = new UpdateManager.ApplyReleasesImpl(Path.Combine(path, "theApp"));
var result = fixture.GetShortcutsForExecutable("SquirrelAwareApp.exe", ShortcutLocation.Desktop | ShortcutLocation.StartMenu | ShortcutLocation.Startup, null);
Assert.Equal(3, result.Keys.Count);
// NB: Squirrel-Aware first-run might still be running, slow
// our roll before blowing away the temp path
Thread.Sleep(1000);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Bigvgames.Models;
using Bigvgames.Models.ManageViewModels;
using Bigvgames.Services;
namespace Bigvgames.Controllers
{
[Authorize]
public class ManageController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
private readonly ILogger _logger;
public ManageController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ISmsSender smsSender,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
_logger = loggerFactory.CreateLogger<ManageController>();
}
//
// GET: /Manage/Index
[HttpGet]
public async Task<IActionResult> Index(ManageMessageId? message = null)
{
ViewData["StatusMessage"] =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
: message == ManageMessageId.Error ? "An error has occurred."
: message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
: message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
: "";
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var model = new IndexViewModel
{
HasPassword = await _userManager.HasPasswordAsync(user),
PhoneNumber = await _userManager.GetPhoneNumberAsync(user),
TwoFactor = await _userManager.GetTwoFactorEnabledAsync(user),
Logins = await _userManager.GetLoginsAsync(user),
BrowserRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user)
};
return View(model);
}
//
// POST: /Manage/RemoveLogin
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel account)
{
ManageMessageId? message = ManageMessageId.Error;
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.RemoveLoginAsync(user, account.LoginProvider, account.ProviderKey);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
message = ManageMessageId.RemoveLoginSuccess;
}
}
return RedirectToAction(nameof(ManageLogins), new { Message = message });
}
//
// GET: /Manage/AddPhoneNumber
public IActionResult AddPhoneNumber()
{
return View();
}
//
// POST: /Manage/AddPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Generate the token and send it
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber);
await _smsSender.SendSmsAsync(model.PhoneNumber, "Your security code is: " + code);
return RedirectToAction(nameof(VerifyPhoneNumber), new { PhoneNumber = model.PhoneNumber });
}
//
// POST: /Manage/EnableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EnableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, true);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(1, "User enabled two-factor authentication.");
}
return RedirectToAction(nameof(Index), "Manage");
}
//
// POST: /Manage/DisableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DisableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, false);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(2, "User disabled two-factor authentication.");
}
return RedirectToAction(nameof(Index), "Manage");
}
//
// GET: /Manage/VerifyPhoneNumber
[HttpGet]
public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber)
{
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, phoneNumber);
// Send an SMS to verify the phone number
return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber });
}
//
// POST: /Manage/VerifyPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.AddPhoneSuccess });
}
}
// If we got this far, something failed, redisplay the form
ModelState.AddModelError(string.Empty, "Failed to verify phone number");
return View(model);
}
//
// POST: /Manage/RemovePhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemovePhoneNumber()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.SetPhoneNumberAsync(user, null);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.RemovePhoneSuccess });
}
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/ChangePassword
[HttpGet]
public IActionResult ChangePassword()
{
return View();
}
//
// POST: /Manage/ChangePassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User changed their password successfully.");
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/SetPassword
[HttpGet]
public IActionResult SetPassword()
{
return View();
}
//
// POST: /Manage/SetPassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SetPassword(SetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.AddPasswordAsync(user, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetPasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//GET: /Manage/ManageLogins
[HttpGet]
public async Task<IActionResult> ManageLogins(ManageMessageId? message = null)
{
ViewData["StatusMessage"] =
message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: message == ManageMessageId.AddLoginSuccess ? "The external login was added."
: message == ManageMessageId.Error ? "An error has occurred."
: "";
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var userLogins = await _userManager.GetLoginsAsync(user);
var otherLogins = _signInManager.GetExternalAuthenticationSchemes().Where(auth => userLogins.All(ul => auth.AuthenticationScheme != ul.LoginProvider)).ToList();
ViewData["ShowRemoveButton"] = user.PasswordHash != null || userLogins.Count > 1;
return View(new ManageLoginsViewModel
{
CurrentLogins = userLogins,
OtherLogins = otherLogins
});
}
//
// POST: /Manage/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult LinkLogin(string provider)
{
// Request a redirect to the external login provider to link a login for the current user
var redirectUrl = Url.Action("LinkLoginCallback", "Manage");
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User));
return Challenge(properties, provider);
}
//
// GET: /Manage/LinkLoginCallback
[HttpGet]
public async Task<ActionResult> LinkLoginCallback()
{
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var info = await _signInManager.GetExternalLoginInfoAsync(await _userManager.GetUserIdAsync(user));
if (info == null)
{
return RedirectToAction(nameof(ManageLogins), new { Message = ManageMessageId.Error });
}
var result = await _userManager.AddLoginAsync(user, info);
var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error;
return RedirectToAction(nameof(ManageLogins), new { Message = message });
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
public enum ManageMessageId
{
AddPhoneSuccess,
AddLoginSuccess,
ChangePasswordSuccess,
SetTwoFactorSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
RemovePhoneSuccess,
Error
}
private Task<ApplicationUser> GetCurrentUserAsync()
{
return _userManager.GetUserAsync(HttpContext.User);
}
#endregion
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
namespace Community.CsharpSqlite
{
public partial class Sqlite3
{
/*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** An tokenizer for SQL
**
** This file contains C code that splits an SQL input string up into
** individual tokens and sends those tokens one-by-one over to the
** parser for analysis.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
**
*************************************************************************
*/
//#include "sqliteInt.h"
//#include <stdlib.h>
/*
** The charMap() macro maps alphabetic characters into their
** lower-case ASCII equivalent. On ASCII machines, this is just
** an upper-to-lower case map. On EBCDIC machines we also need
** to adjust the encoding. Only alphabetic characters and underscores
** need to be translated.
*/
#if SQLITE_ASCII
//# define charMap(X) sqlite3UpperToLower[(unsigned char)X]
#endif
//#if SQLITE_EBCDIC
//# define charMap(X) ebcdicToAscii[(unsigned char)X]
//const unsigned char ebcdicToAscii[] = {
///* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
// 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
// 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
// 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
// 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
// 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
// 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
//};
//#endif
/*
** The sqlite3KeywordCode function looks up an identifier to determine if
** it is a keyword. If it is a keyword, the token code of that keyword is
** returned. If the input is not a keyword, TK_ID is returned.
**
** The implementation of this routine was generated by a program,
** mkkeywordhash.h, located in the tool subdirectory of the distribution.
** The output of the mkkeywordhash.c program is written into a file
** named keywordhash.h and then included into this source file by
** the #include below.
*/
//#include "keywordhash.h"
/*
** If X is a character that can be used in an identifier then
** IdChar(X) will be true. Otherwise it is false.
**
** For ASCII, any character with the high-order bit set is
** allowed in an identifier. For 7-bit characters,
** sqlite3IsIdChar[X] must be 1.
**
** For EBCDIC, the rules are more complex but have the same
** end result.
**
** Ticket #1066. the SQL standard does not allow '$' in the
** middle of identfiers. But many SQL implementations do.
** SQLite will allow '$' in identifiers for compatibility.
** But the feature is undocumented.
*/
#if SQLITE_ASCII
//#define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
#endif
//#if SQLITE_EBCDIC
//const char sqlite3IsEbcdicIdChar[] = {
///* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
// 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
// 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
// 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
// 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
// 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
// 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
// 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
// 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
// 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
// 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
// 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
//};
//#define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
//#endif
/*
** Return the length of the token that begins at z[iOffset + 0].
** Store the token type in *tokenType before returning.
*/
static int sqlite3GetToken( string z, int iOffset, ref int tokenType )
{
int i;
byte c = 0;
switch ( z[iOffset + 0] )
{
case ' ':
case '\t':
case '\n':
case '\f':
case '\r':
{
testcase( z[iOffset + 0] == ' ' );
testcase( z[iOffset + 0] == '\t' );
testcase( z[iOffset + 0] == '\n' );
testcase( z[iOffset + 0] == '\f' );
testcase( z[iOffset + 0] == '\r' );
for ( i = 1; z.Length > iOffset + i && sqlite3Isspace( z[iOffset + i] ); i++ )
{
}
tokenType = TK_SPACE;
return i;
}
case '-':
{
if ( z.Length > iOffset + 1 && z[iOffset + 1] == '-' )
{
/* IMP: R-15891-05542 -- syntax diagram for comments */
for ( i = 2; z.Length > iOffset + i && ( c = (byte)z[iOffset + i] ) != 0 && c != '\n'; i++ )
{
}
tokenType = TK_SPACE; /* IMP: R-22934-25134 */
return i;
}
tokenType = TK_MINUS;
return 1;
}
case '(':
{
tokenType = TK_LP;
return 1;
}
case ')':
{
tokenType = TK_RP;
return 1;
}
case ';':
{
tokenType = TK_SEMI;
return 1;
}
case '+':
{
tokenType = TK_PLUS;
return 1;
}
case '*':
{
tokenType = TK_STAR;
return 1;
}
case '/':
{
if ( iOffset + 2 >= z.Length || z[iOffset + 1] != '*' )
{
tokenType = TK_SLASH;
return 1;
}
/* IMP: R-15891-05542 -- syntax diagram for comments */
for ( i = 3, c = (byte)z[iOffset + 2]; iOffset + i < z.Length && ( c != '*' || ( z[iOffset + i] != '/' ) && ( c != 0 ) ); i++ )
{
c = (byte)z[iOffset + i];
}
if ( iOffset + i == z.Length )
c = 0;
if ( c != 0 )
i++;
tokenType = TK_SPACE; /* IMP: R-22934-25134 */
return i;
}
case '%':
{
tokenType = TK_REM;
return 1;
}
case '=':
{
tokenType = TK_EQ;
return 1 + ( z[iOffset + 1] == '=' ? 1 : 0 );
}
case '<':
{
if ( ( c = (byte)z[iOffset + 1] ) == '=' )
{
tokenType = TK_LE;
return 2;
}
else if ( c == '>' )
{
tokenType = TK_NE;
return 2;
}
else if ( c == '<' )
{
tokenType = TK_LSHIFT;
return 2;
}
else
{
tokenType = TK_LT;
return 1;
}
}
case '>':
{
if ( z.Length > iOffset + 1 && ( c = (byte)z[iOffset + 1] ) == '=' )
{
tokenType = TK_GE;
return 2;
}
else if ( c == '>' )
{
tokenType = TK_RSHIFT;
return 2;
}
else
{
tokenType = TK_GT;
return 1;
}
}
case '!':
{
if ( z[iOffset + 1] != '=' )
{
tokenType = TK_ILLEGAL;
return 2;
}
else
{
tokenType = TK_NE;
return 2;
}
}
case '|':
{
if ( z[iOffset + 1] != '|' )
{
tokenType = TK_BITOR;
return 1;
}
else
{
tokenType = TK_CONCAT;
return 2;
}
}
case ',':
{
tokenType = TK_COMMA;
return 1;
}
case '&':
{
tokenType = TK_BITAND;
return 1;
}
case '~':
{
tokenType = TK_BITNOT;
return 1;
}
case '`':
case '\'':
case '"':
{
int delim = z[iOffset + 0];
testcase( delim == '`' );
testcase( delim == '\'' );
testcase( delim == '"' );
for ( i = 1; ( iOffset + i ) < z.Length && ( c = (byte)z[iOffset + i] ) != 0; i++ )
{
if ( c == delim )
{
if ( z.Length > iOffset + i + 1 && z[iOffset + i + 1] == delim )
{
i++;
}
else
{
break;
}
}
}
if ( ( iOffset + i == z.Length && c != delim ) || z[iOffset + i] != delim )
{
tokenType = TK_ILLEGAL;
return i + 1;
}
if ( c == '\'' )
{
tokenType = TK_STRING;
return i + 1;
}
else if ( c != 0 )
{
tokenType = TK_ID;
return i + 1;
}
else
{
tokenType = TK_ILLEGAL;
return i;
}
}
case '.':
{
#if !SQLITE_OMIT_FLOATING_POINT
if ( !sqlite3Isdigit( z[iOffset + 1] ) )
#endif
{
tokenType = TK_DOT;
return 1;
}
/* If the next character is a digit, this is a floating point
** number that begins with ".". Fall thru into the next case */
goto case '0';
}
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
testcase( z[iOffset] == '0' );
testcase( z[iOffset] == '1' );
testcase( z[iOffset] == '2' );
testcase( z[iOffset] == '3' );
testcase( z[iOffset] == '4' );
testcase( z[iOffset] == '5' );
testcase( z[iOffset] == '6' );
testcase( z[iOffset] == '7' );
testcase( z[iOffset] == '8' );
testcase( z[iOffset] == '9' );
tokenType = TK_INTEGER;
for ( i = 0; z.Length > iOffset + i && sqlite3Isdigit( z[iOffset + i] ); i++ )
{
}
#if !SQLITE_OMIT_FLOATING_POINT
if ( z.Length > iOffset + i && z[iOffset + i] == '.' )
{
i++;
while ( z.Length > iOffset + i && sqlite3Isdigit( z[iOffset + i] ) )
{
i++;
}
tokenType = TK_FLOAT;
}
if ( z.Length > iOffset + i + 1 && ( z[iOffset + i] == 'e' || z[iOffset + i] == 'E' ) &&
( sqlite3Isdigit( z[iOffset + i + 1] )
|| z.Length > iOffset + i + 2 && ( ( z[iOffset + i + 1] == '+' || z[iOffset + i + 1] == '-' ) && sqlite3Isdigit( z[iOffset + i + 2] ) )
)
)
{
i += 2;
while ( z.Length > iOffset + i && sqlite3Isdigit( z[iOffset + i] ) )
{
i++;
}
tokenType = TK_FLOAT;
}
#endif
while ( iOffset + i < z.Length && IdChar( (byte)z[iOffset + i] ) )
{
tokenType = TK_ILLEGAL;
i++;
}
return i;
}
case '[':
{
for ( i = 1, c = (byte)z[iOffset + 0]; c != ']' && ( iOffset + i ) < z.Length && ( c = (byte)z[iOffset + i] ) != 0; i++ )
{
}
tokenType = c == ']' ? TK_ID : TK_ILLEGAL;
return i;
}
case '?':
{
tokenType = TK_VARIABLE;
for ( i = 1; z.Length > iOffset + i && sqlite3Isdigit( z[iOffset + i] ); i++ )
{
}
return i;
}
case '#':
{
for ( i = 1; z.Length > iOffset + i && sqlite3Isdigit( z[iOffset + i] ); i++ )
{
}
if ( i > 1 )
{
/* Parameters of the form #NNN (where NNN is a number) are used
** internally by sqlite3NestedParse. */
tokenType = TK_REGISTER;
return i;
}
/* Fall through into the next case if the '#' is not followed by
** a digit. Try to match #AAAA where AAAA is a parameter name. */
goto case ':';
}
#if !SQLITE_OMIT_TCL_VARIABLE
case '$':
#endif
case '@': /* For compatibility with MS SQL Server */
case ':':
{
int n = 0;
testcase( z[iOffset + 0] == '$' );
testcase( z[iOffset + 0] == '@' );
testcase( z[iOffset + 0] == ':' );
tokenType = TK_VARIABLE;
for ( i = 1; z.Length > iOffset + i && ( c = (byte)z[iOffset + i] ) != 0; i++ )
{
if ( IdChar( c ) )
{
n++;
#if !SQLITE_OMIT_TCL_VARIABLE
}
else if ( c == '(' && n > 0 )
{
do
{
i++;
} while ( ( iOffset + i ) < z.Length && ( c = (byte)z[iOffset + i] ) != 0 && !sqlite3Isspace( c ) && c != ')' );
if ( c == ')' )
{
i++;
}
else
{
tokenType = TK_ILLEGAL;
}
break;
}
else if ( c == ':' && z[iOffset + i + 1] == ':' )
{
i++;
#endif
}
else
{
break;
}
}
if ( n == 0 )
tokenType = TK_ILLEGAL;
return i;
}
#if !SQLITE_OMIT_BLOB_LITERAL
case 'x':
case 'X':
{
testcase( z[iOffset + 0] == 'x' );
testcase( z[iOffset + 0] == 'X' );
if ( z.Length > iOffset + 1 && z[iOffset + 1] == '\'' )
{
tokenType = TK_BLOB;
for ( i = 2; z.Length > iOffset + i && sqlite3Isxdigit( z[iOffset + i] ); i++ )
{
}
if ( iOffset + i == z.Length || z[iOffset + i] != '\'' || i % 2 != 0 )
{
tokenType = TK_ILLEGAL;
while ( z.Length > iOffset + i && z[iOffset + i] != '\'' )
{
i++;
}
}
if ( z.Length > iOffset + i )
i++;
return i;
}
goto default;
/* Otherwise fall through to the next case */
}
#endif
default:
{
if ( !IdChar( (byte)z[iOffset] ) )
{
break;
}
for ( i = 1; i < z.Length - iOffset && IdChar( (byte)z[iOffset + i] ); i++ )
{
}
tokenType = keywordCode( z, iOffset, i );
return i;
}
}
tokenType = TK_ILLEGAL;
return 1;
}
/*
** Run the parser on the given SQL string. The parser structure is
** passed in. An SQLITE_ status code is returned. If an error occurs
** then an and attempt is made to write an error message into
** memory obtained from sqlite3_malloc() and to make pzErrMsg point to that
** error message.
*/
static int sqlite3RunParser( Parse pParse, string zSql, ref string pzErrMsg )
{
int nErr = 0; /* Number of errors encountered */
int i; /* Loop counter */
yyParser pEngine; /* The LEMON-generated LALR(1) parser */
int tokenType = 0; /* type of the next token */
int lastTokenParsed = -1; /* type of the previous token */
byte enableLookaside; /* Saved value of db->lookaside.bEnabled */
sqlite3 db = pParse.db; /* The database connection */
int mxSqlLen; /* Max length of an SQL string */
mxSqlLen = db.aLimit[SQLITE_LIMIT_SQL_LENGTH];
if ( db.activeVdbeCnt == 0 )
{
db.u1.isInterrupted = false;
}
pParse.rc = SQLITE_OK;
pParse.zTail = new StringBuilder( zSql );
i = 0;
Debug.Assert( pzErrMsg != null );
pEngine = sqlite3ParserAlloc();//sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
//if ( pEngine == null )
//{
// db.mallocFailed = 1;
// return SQLITE_NOMEM;
//}
Debug.Assert( pParse.pNewTable == null );
Debug.Assert( pParse.pNewTrigger == null );
Debug.Assert( pParse.nVar == 0 );
Debug.Assert( pParse.nzVar == 0 );
Debug.Assert( pParse.azVar == null );
enableLookaside = db.lookaside.bEnabled;
if ( db.lookaside.pStart != 0 )
db.lookaside.bEnabled = 1;
while ( /* 0 == db.mallocFailed && */ i < zSql.Length )
{
Debug.Assert( i >= 0 );
//pParse->sLastToken.z = &zSql[i];
pParse.sLastToken.n = sqlite3GetToken( zSql, i, ref tokenType );
pParse.sLastToken.z = zSql.Substring( i );
i += pParse.sLastToken.n;
if ( i > mxSqlLen )
{
pParse.rc = SQLITE_TOOBIG;
break;
}
switch ( tokenType )
{
case TK_SPACE:
{
if ( db.u1.isInterrupted )
{
sqlite3ErrorMsg( pParse, "interrupt" );
pParse.rc = SQLITE_INTERRUPT;
goto abort_parse;
}
break;
}
case TK_ILLEGAL:
{
sqlite3DbFree( db, ref pzErrMsg );
pzErrMsg = sqlite3MPrintf( db, "unrecognized token: \"%T\"",
(object)pParse.sLastToken );
nErr++;
goto abort_parse;
}
case TK_SEMI:
{
//pParse.zTail = new StringBuilder(zSql.Substring( i,zSql.Length-i ));
/* Fall thru into the default case */
goto default;
}
default:
{
sqlite3Parser( pEngine, tokenType, pParse.sLastToken, pParse );
lastTokenParsed = tokenType;
if ( pParse.rc != SQLITE_OK )
{
goto abort_parse;
}
break;
}
}
}
abort_parse:
pParse.zTail = new StringBuilder( zSql.Length <= i ? "" : zSql.Substring( i, zSql.Length - i ) );
if ( zSql.Length >= i && nErr == 0 && pParse.rc == SQLITE_OK )
{
if ( lastTokenParsed != TK_SEMI )
{
sqlite3Parser( pEngine, TK_SEMI, pParse.sLastToken, pParse );
}
sqlite3Parser( pEngine, 0, pParse.sLastToken, pParse );
}
#if YYTRACKMAXSTACKDEPTH
sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
sqlite3ParserStackPeak(pEngine)
);
#endif //* YYDEBUG */
sqlite3ParserFree( pEngine, null );//sqlite3_free );
db.lookaside.bEnabled = enableLookaside;
//if ( db.mallocFailed != 0 )
//{
// pParse.rc = SQLITE_NOMEM;
//}
if ( pParse.rc != SQLITE_OK && pParse.rc != SQLITE_DONE && pParse.zErrMsg == "" )
{
sqlite3SetString( ref pParse.zErrMsg, db, sqlite3ErrStr( pParse.rc ) );
}
//assert( pzErrMsg!=0 );
if ( pParse.zErrMsg != null )
{
pzErrMsg = pParse.zErrMsg;
sqlite3_log( pParse.rc, "%s", pzErrMsg );
pParse.zErrMsg = "";
nErr++;
}
if ( pParse.pVdbe != null && pParse.nErr > 0 && pParse.nested == 0 )
{
sqlite3VdbeDelete( ref pParse.pVdbe );
pParse.pVdbe = null;
}
#if !SQLITE_OMIT_SHARED_CACHE
if ( pParse.nested == 0 )
{
sqlite3DbFree( db, ref pParse.aTableLock );
pParse.aTableLock = null;
pParse.nTableLock = 0;
}
#endif
#if !SQLITE_OMIT_VIRTUALTABLE
pParse.apVtabLock = null;//sqlite3_free( pParse.apVtabLock );
#endif
if ( !IN_DECLARE_VTAB(pParse) )
{
/* If the pParse.declareVtab flag is set, do not delete any table
** structure built up in pParse.pNewTable. The calling code (see vtab.c)
** will take responsibility for freeing the Table structure.
*/
sqlite3DeleteTable( db, ref pParse.pNewTable );
}
#if !SQLITE_OMIT_TRIGGER
sqlite3DeleteTrigger( db, ref pParse.pNewTrigger );
#endif
//for ( i = pParse.nzVar - 1; i >= 0; i-- )
// sqlite3DbFree( db, pParse.azVar[i] );
sqlite3DbFree( db, ref pParse.azVar );
sqlite3DbFree( db, ref pParse.aAlias );
while ( pParse.pAinc != null )
{
AutoincInfo p = pParse.pAinc;
pParse.pAinc = p.pNext;
sqlite3DbFree( db, ref p );
}
while ( pParse.pZombieTab != null )
{
Table p = pParse.pZombieTab;
pParse.pZombieTab = p.pNextZombie;
sqlite3DeleteTable( db, ref p );
}
if ( nErr > 0 && pParse.rc == SQLITE_OK )
{
pParse.rc = SQLITE_ERROR;
}
return nErr;
}
}
}
| |
// <copyright file=WorkflowBase.cs
// <copyright>
// Copyright (c) 2016, University of Stuttgart
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Software),
// to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
// <license>MIT License</license>
// <main contributors>
// Markus Funk, Thomas Kosch, Sven Mayer
// </main contributors>
// <co-contributors>
// Paul Brombosch, Mai El-Komy, Juana Heusler,
// Matthias Hoppe, Robert Konrad, Alexander Martin
// </co-contributors>
// <patent information>
// We are aware that this software implements patterns and ideas,
// which might be protected by patents in your country.
// Example patents in Germany are:
// Patent reference number: DE 103 20 557.8
// Patent reference number: DE 10 2013 220 107.9
// Please make sure when using this software not to violate any existing patents in your country.
// </patent information>
// <date> 11/2/2016 12:25:58 PM</date>
using HciLab.Utilities;
using HciLab.Utilities.Mathematics.Geometry2D;
using motionEAPAdmin.Scene;
using System.ComponentModel;
using System.Runtime.Serialization;
using System.Windows.Media.Media3D;
namespace motionEAPAdmin.Backend
{
public abstract class WorkflowBase : DataBaseClass, ISerializable, INotifyPropertyChanged
{
/// <summary>
/// property changed for the databinding
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
private int m_SerVersionWorkflowBase = 3;
protected int m_X = 0; // pixel in color image
protected int m_Y = 0; // pixel in color image
protected int m_Z; // millimeters in real world
protected int m_Width = 1; // pixel in color imaeg
protected int m_Height = 1; // pixel in color image
protected string m_TriggerMessage; // message to be triggered
protected string m_Name;
protected Scene.Scene m_CustomScene = null;
/// <summary>
///
/// </summary>
private Polygon m_Contour = null;
#region No Serializableization
protected GeometryModel3D m_Drawable = null;
private bool m_IsSelected = true;
protected Scene.SceneItem m_SceneItem = null;
#endregion
public WorkflowBase()
: base()
{
}
public WorkflowBase(int pId)
: base(pId)
{
}
public WorkflowBase(SerializationInfo pInfo, StreamingContext pContext)
: base(pInfo, pContext)
{
// for version evaluation while deserializing
int pSerVersion = pInfo.GetInt32("m_SerVersionWorkflowBase");
m_X = pInfo.GetInt32("m_X");
m_Y = pInfo.GetInt32("m_Y");
m_Z = pInfo.GetInt32("m_Z");
m_Width = pInfo.GetInt32("m_Width");
m_Height = pInfo.GetInt32("m_Height");
m_Name = pInfo.GetString("m_Name");
m_TriggerMessage = pInfo.GetString("m_TriggerMessage");
if (pSerVersion > 1)
{
m_CustomScene = (Scene.Scene)pInfo.GetValue("m_CustomScene", typeof(Scene.Scene));
}
if (pSerVersion > 2)
{
m_Contour = (Polygon)pInfo.GetValue("m_Contour", typeof(Polygon));
}
this.trigger += WorkflowManager.Instance.OnTriggered;
}
public new void GetObjectData(SerializationInfo pInfo, StreamingContext pContext)
{
base.GetObjectData(pInfo, pContext);
pInfo.AddValue("m_SerVersionWorkflowBase", m_SerVersionWorkflowBase);
pInfo.AddValue("m_X", m_X);
pInfo.AddValue("m_Y", m_Y);
pInfo.AddValue("m_Z", m_Z);
pInfo.AddValue("m_Width", m_Width);
pInfo.AddValue("m_Height", m_Height);
pInfo.AddValue("m_Name", m_Name);
pInfo.AddValue("m_TriggerMessage", m_TriggerMessage);
pInfo.AddValue("m_CustomScene", m_CustomScene);
pInfo.AddValue("m_Contour", m_Contour);
}
public abstract Scene.SceneItem getDrawable(bool pIsForRecord = false);
public delegate void TriggerHandler(WorkflowBase pSource);
public event TriggerHandler trigger;
public void OnTrigger(WorkflowBase pSource)
{
if (this.trigger != null)
trigger(pSource);
}
protected void NotifyPropertyChanged(string Obj)
{
if (PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(Obj));
}
updateScene();
}
protected void updateScene()
{
if (m_Contour != null)
{
if (m_SceneItem == null || !(m_SceneItem is ScenePolygon))
m_SceneItem = new ScenePolygon(m_Contour, System.Windows.Media.Color.FromRgb(0, 255, 0));
}
else
{
if (m_SceneItem == null || !(m_SceneItem is SceneRect))
m_SceneItem = new SceneRect();
}
m_SceneItem.X = X;
m_SceneItem.Y = Y;
m_SceneItem.Width = Width;
m_SceneItem.Height = Height;
m_SceneItem.Touchy = false;
}
#region Getter / Setter
public int X
{
get
{
return m_X;
}
set
{
m_X = value;
NotifyPropertyChanged("X");
}
}
public int Y
{
get
{
return m_Y;
}
set
{
m_Y = value;
NotifyPropertyChanged("Y");
}
}
public int Z
{
get
{
return m_Z;
}
set
{
m_Z = value;
NotifyPropertyChanged("Z");
}
}
public int Width
{
get
{
return m_Width;
}
set
{
m_Width = value;
NotifyPropertyChanged("Width");
}
}
public int Height
{
get
{
return m_Height;
}
set
{
m_Height = value;
NotifyPropertyChanged("Height");
}
}
public string TriggerMessage
{
get
{
return m_TriggerMessage;
}
set
{
m_TriggerMessage = value;
NotifyPropertyChanged("TriggerMessage");
}
}
public string Name
{
get
{
return m_Name;
}
set
{
m_Name = value;
NotifyPropertyChanged("Name");
}
}
public Scene.Scene CustomScene
{
get { return m_CustomScene; }
set { m_CustomScene = value; }
}
public Polygon Contour
{
get
{
return m_Contour;
}
set
{
m_Contour = value;
NotifyPropertyChanged("Contour");
}
}
#region Getter and setter for CheckedListBox
public bool IsSelected
{
get
{
return m_IsSelected;
}
set
{
m_IsSelected = value;
NotifyPropertyChanged("IsSelected");
}
}
#endregion
#endregion
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.UI.WebControls;
using Adxstudio.Xrm.Cms;
using Adxstudio.Xrm.Data;
using Adxstudio.Xrm.Partner;
using Adxstudio.Xrm.Resources;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Portal.Web;
using Site.Pages;
using Microsoft.Xrm.Sdk;
using System.Web;
namespace Site.Areas.CustomerManagement.Pages
{
public partial class ManageCustomerContacts : PortalPage
{
private DataTable _contacts;
protected string SortDirection
{
get { return ViewState["SortDirection"] as string ?? "ASC"; }
set { ViewState["SortDirection"] = value; }
}
protected string SortExpression
{
get { return ViewState["SortExpression"] as string ?? "Accepted"; }
set { ViewState["SortExpression"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
RedirectToLoginIfAnonymous();
var channelPermission = ServiceContext.GetChannelAccessByContact(Contact);
var channelCreateAccess = (channelPermission != null && channelPermission.GetAttributeValue<bool?>("adx_create").GetValueOrDefault(false));
var channelWriteAccess = (channelPermission != null && channelPermission.GetAttributeValue<bool?>("adx_write").GetValueOrDefault(false));
var channelReadAccess = (channelPermission != null && channelPermission.GetAttributeValue<bool?>("adx_read").GetValueOrDefault(false));
var parentCustomerAccount = Contact.GetAttributeValue<EntityReference>("parentcustomerid") == null ? null : ServiceContext.CreateQuery("account").FirstOrDefault(a => a.GetAttributeValue<Guid>("accountid") == Contact.GetAttributeValue<EntityReference>("parentcustomerid").Id);
var validAcccountClassificationCode = parentCustomerAccount != null && parentCustomerAccount.GetAttributeValue<OptionSetValue>("accountclassificationcode") != null && parentCustomerAccount.GetAttributeValue<OptionSetValue>("accountclassificationcode").Value == (int)Enums.AccountClassificationCode.Partner;
if (channelPermission == null)
{
NoChannelPermissionsRecordError.Visible = true;
ContactsList.Visible = false;
return;
}
if (!channelReadAccess && !channelWriteAccess)
{
ChannelPermissionsError.Visible = true;
}
else
{
if (parentCustomerAccount == null)
{
NoParentAccountError.Visible = true;
}
else
{
ParentAccountClassificationCodeError.Visible = !validAcccountClassificationCode;
}
}
if ((!channelReadAccess && !channelWriteAccess) || parentCustomerAccount == null || !validAcccountClassificationCode)
{
ContactsList.Visible = false;
return;
}
CreateButton.Visible = channelCreateAccess;
if (!IsPostBack)
{
PopulateCustomerFilter();
}
var contacts = new List<Entity>();
if (string.Equals(CustomerFilter.Text, "All", StringComparison.InvariantCulture))
{
var myContacts = ServiceContext.CreateQuery("contact").Where(c => c.GetAttributeValue<EntityReference>("msa_managingpartnerid") == parentCustomerAccount.ToEntityReference());
contacts.AddRange(myContacts);
var accounts = ServiceContext.CreateQuery("account").Where(a => a.GetAttributeValue<EntityReference>("msa_managingpartnerid") == parentCustomerAccount.ToEntityReference()).ToList();
if (accounts.Any())
{
foreach (var account in accounts)
{
var currentContacts =
ServiceContext.CreateQuery("contact")
.Where(
c =>
(c.GetAttributeValue<EntityReference>("msa_managingpartnerid") == null ||
(c.GetAttributeValue<EntityReference>("msa_managingpartnerid") != null &&
!c.GetAttributeValue<EntityReference>("msa_managingpartnerid").Equals(parentCustomerAccount.ToEntityReference()))) &&
c.GetAttributeValue<EntityReference>("parentcustomerid") != null &&
c.GetAttributeValue<EntityReference>("parentcustomerid").Equals(account.ToEntityReference()));
contacts.AddRange(currentContacts);
}
}
}
else if (string.Equals(CustomerFilter.Text, "My", StringComparison.InvariantCulture))
{
var currentContacts =
ServiceContext.CreateQuery("contact")
.Where(
c =>
c.GetAttributeValue<EntityReference>("parentcustomerid") == null &&
(c.GetAttributeValue<EntityReference>("msa_managingpartnerid") != null &&
c.GetAttributeValue<EntityReference>("msa_managingpartnerid").Equals(parentCustomerAccount.ToEntityReference())));
contacts.AddRange(currentContacts);
}
else
{
Guid accountid;
if (Guid.TryParse(CustomerFilter.SelectedValue, out accountid))
{
var currentContacts =
ServiceContext.CreateQuery("contact")
.Where(
c =>
c.GetAttributeValue<EntityReference>("parentcustomerid") != null &&
c.GetAttributeValue<EntityReference>("parentcustomerid").Equals(new EntityReference("account", accountid)));
contacts.AddRange(currentContacts);
}
}
_contacts = EnumerableExtensions.CopyToDataTable(contacts.Select(c => new
{
contactid = c.GetAttributeValue<Guid>("contactid"),
ID = c.GetAttributeValue<string>("fullname"),
CompanyName = c.GetRelatedEntity(ServiceContext, new Relationship("contact_customer_accounts")) == null ? string.Empty : c.GetRelatedEntity(ServiceContext, new Relationship("contact_customer_accounts")).GetAttributeValue<string>("name"),
City = c.GetAttributeValue<string>("address1_city"),
State = c.GetAttributeValue<string>("address1_stateorprovince"),
Phone = c.GetAttributeValue<string>("address1_telephone1"),
Email = c.GetAttributeValue<string>("emailaddress1"),
}));
_contacts.Columns["City"].ColumnName = "City";
_contacts.Columns["State"].ColumnName = "State";
_contacts.Columns["Phone"].ColumnName = "Phone";
_contacts.Columns["Email"].ColumnName = "E-mail Address";
CustomerContactsList.DataKeyNames = new[] { "contactid" };
CustomerContactsList.DataSource = _contacts;
CustomerContactsList.DataBind();
Guid id;
if (CustomerFilter.SelectedItem != null && Guid.TryParse(CustomerFilter.SelectedItem.Value, out id))
{
CreateButton.QueryStringCollection = new QueryStringCollection(string.Empty);
CreateButton.QueryStringCollection.Set("AccountID", id.ToString());
}
}
protected void CustomerContactsList_Sorting(object sender, GridViewSortEventArgs e)
{
SortDirection = e.SortExpression == SortExpression ? (SortDirection == "ASC" ? "DESC" : "ASC") : "ASC";
SortExpression = e.SortExpression;
_contacts.DefaultView.Sort = string.Format("{0} {1}", SortExpression, SortDirection);
CustomerContactsList.DataSource = _contacts;
CustomerContactsList.DataBind();
}
protected void CustomerContactsList_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header || e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].Visible = false;
}
if (e.Row.RowType != DataControlRowType.DataRow)
{
return;
}
var dataKey = CustomerContactsList.DataKeys[e.Row.RowIndex].Value;
e.Row.Cells[1].Text = string.Format(@"<a href=""{0}"">{1}</a>", HttpUtility.HtmlEncode(EditContactUrl(dataKey)), HttpUtility.HtmlEncode(e.Row.Cells[1].Text));
e.Row.Cells[1].Attributes.Add("style", "white-space: nowrap;");
}
protected string EditContactUrl(object id)
{
var page = ServiceContext.GetPageBySiteMarkerName(Website, "Edit Customer Contact");
if (page == null)
{
throw new Exception("Please contact the system administrator. A required site marker titled Edit Customer Contact doesn't exist.");
}
var url = new UrlBuilder(ServiceContext.GetUrl(page));
url.QueryString.Set("ContactID", id.ToString());
return url.PathWithQueryString;
}
private void PopulateCustomerFilter()
{
CustomerFilter.Items.Clear();
var accounts =
ServiceContext.CreateQuery("account")
.Where(
a =>
a.GetAttributeValue<EntityReference>("msa_managingpartnerid") != null &&
a.GetAttributeValue<EntityReference>("msa_managingpartnerid")
.Equals(Contact.GetAttributeValue<EntityReference>("parentcustomerid")))
.OrderBy(a => a.GetAttributeValue<string>("name"));
CustomerFilter.Items.Add(new ListItem("All"));
CustomerFilter.Items.Add(new ListItem("My"));
foreach (var account in accounts)
{
CustomerFilter.Items.Add(new ListItem(account.GetAttributeValue<string>("name"), account.GetAttributeValue<Guid>("accountid").ToString()));
}
}
}
}
| |
// Visual Studio Shared Project
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using EnvDTE;
using Microsoft.VisualStudio.Package.Automation;
using VSLangProj;
namespace Microsoft.VisualStudioTools.Project.Automation
{
/// <summary>
/// Represents an automation friendly version of a language-specific project.
/// </summary>
[ComVisible(true), CLSCompliant(false)]
public class OAVSProject : VSProject
{
#region fields
private ProjectNode project;
private OAVSProjectEvents events;
#endregion
#region ctors
internal OAVSProject(ProjectNode project)
{
this.project = project;
}
#endregion
#region VSProject Members
public virtual ProjectItem AddWebReference(string bstrUrl)
{
throw new NotImplementedException();
}
public virtual BuildManager BuildManager
{
get
{
return new OABuildManager(this.project);
}
}
public virtual void CopyProject(string bstrDestFolder, string bstrDestUNCPath, prjCopyProjectOption copyProjectOption, string bstrUsername, string bstrPassword)
{
throw new NotImplementedException();
}
public virtual ProjectItem CreateWebReferencesFolder()
{
throw new NotImplementedException();
}
public virtual DTE DTE
{
get
{
return (EnvDTE.DTE)this.project.Site.GetService(typeof(EnvDTE.DTE));
}
}
public virtual VSProjectEvents Events
{
get
{
if (events == null)
events = new OAVSProjectEvents(this);
return events;
}
}
public virtual void Exec(prjExecCommand command, int bSuppressUI, object varIn, out object pVarOut)
{
throw new NotImplementedException(); ;
}
public virtual void GenerateKeyPairFiles(string strPublicPrivateFile, string strPublicOnlyFile)
{
throw new NotImplementedException(); ;
}
public virtual string GetUniqueFilename(object pDispatch, string bstrRoot, string bstrDesiredExt)
{
throw new NotImplementedException(); ;
}
public virtual Imports Imports
{
get
{
throw new NotImplementedException();
}
}
public virtual EnvDTE.Project Project
{
get
{
return this.project.GetAutomationObject() as EnvDTE.Project;
}
}
public virtual References References
{
get
{
ReferenceContainerNode references = project.GetReferenceContainer() as ReferenceContainerNode;
if (null == references)
{
return new OAReferences(null, project);
}
return references.Object as References;
}
}
public virtual void Refresh()
{
}
public virtual string TemplatePath
{
get
{
throw new NotImplementedException();
}
}
public virtual ProjectItem WebReferencesFolder
{
get
{
throw new NotImplementedException();
}
}
public virtual bool WorkOffline
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
#endregion
}
/// <summary>
/// Provides access to language-specific project events
/// </summary>
[ComVisible(true), CLSCompliant(false)]
public class OAVSProjectEvents : VSProjectEvents
{
#region fields
private OAVSProject vsProject;
#endregion
#region ctors
public OAVSProjectEvents(OAVSProject vsProject)
{
this.vsProject = vsProject;
}
#endregion
#region VSProjectEvents Members
public virtual BuildManagerEvents BuildManagerEvents
{
get
{
return vsProject.BuildManager as BuildManagerEvents;
}
}
public virtual ImportsEvents ImportsEvents
{
get
{
throw new NotImplementedException();
}
}
public virtual ReferencesEvents ReferencesEvents
{
get
{
return vsProject.References as ReferencesEvents;
}
}
#endregion
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.Cci;
using Microsoft.Cci.MutableCodeModel;
using System.Diagnostics.Contracts;
namespace CSharp2CCI {
/// <summary>
/// A thin wrapper for Roslyn source locations
/// </summary>
public sealed class SourceLocationWrapper : IPrimarySourceLocation, IDocument, IPrimarySourceDocument {
SyntaxTree tree;
Microsoft.CodeAnalysis.Text.TextSpan span;
public SourceLocationWrapper(SyntaxTree tree, Microsoft.CodeAnalysis.Text.TextSpan span) {
this.tree = tree;
this.span = span;
}
#region IPrimarySourceLocation members
public int EndColumn {
get { return this.tree.GetLineSpan(this.span, true).EndLinePosition.Character + 1; }
}
public int EndLine {
get { return this.tree.GetLineSpan(this.span, true).EndLinePosition.Line + 1; }
}
public IPrimarySourceDocument PrimarySourceDocument {
get { return this; }
}
public int StartColumn {
get { return this.tree.GetLineSpan(this.span, true).StartLinePosition.Character + 1; }
}
public int StartLine {
get { return this.tree.GetLineSpan(this.span, true).StartLinePosition.Line + 1; }
}
public bool Contains(ISourceLocation location) {
throw new NotImplementedException();
}
public int CopyTo(int offset, char[] destination, int destinationOffset, int length) {
throw new NotImplementedException();
}
public int EndIndex {
get { return this.span.End; }
}
public int Length {
get { return this.span.Length; }
}
public ISourceDocument SourceDocument {
get { throw new NotImplementedException(); }
}
public string Source {
get { return this.tree.GetText().GetSubText(this.span).ToString(); }
}
public int StartIndex {
get { return this.span.Start; }
}
public IDocument Document {
get { return this; }
}
#endregion
#region IDocument members
// TODO: Need the full location
public string Location {
get { return this.tree.FilePath; }
}
public IName Name {
get { throw new NotImplementedException(); }
}
#endregion
#region IPrimarySourceDocument
// TODO
public Guid DocumentType {
get { return Guid.Empty; }
}
// TODO
public Guid Language {
get { return Guid.Empty; }
}
// TODO
public Guid LanguageVendor {
get { return Guid.Empty; }
}
public IPrimarySourceLocation PrimarySourceLocation {
get { throw new NotImplementedException(); }
}
public IPrimarySourceLocation GetPrimarySourceLocation(int position, int length) {
throw new NotImplementedException();
}
public void ToLineColumn(int position, out int line, out int column) {
throw new NotImplementedException();
}
public ISourceLocation GetCorrespondingSourceLocation(ISourceLocation sourceLocationInPreviousVersionOfDocument) {
throw new NotImplementedException();
}
public ISourceLocation GetSourceLocation(int position, int length) {
throw new NotImplementedException();
}
public string GetText() {
throw new NotImplementedException();
}
public bool IsUpdatedVersionOf(ISourceDocument sourceDocument) {
throw new NotImplementedException();
}
public string SourceLanguage {
get { throw new NotImplementedException(); }
}
public ISourceLocation SourceLocation {
get { throw new NotImplementedException(); }
}
#endregion
}
public sealed class SourceLocationProvider : ISourceLocationProvider {
public IEnumerable<IPrimarySourceLocation> GetPrimarySourceLocationsFor(IEnumerable<ILocation> locations) {
foreach (ILocation location in locations) {
foreach (IPrimarySourceLocation psloc in this.GetPrimarySourceLocationsFor(location))
yield return psloc;
}
}
public IEnumerable<IPrimarySourceLocation> GetPrimarySourceLocationsFor(ILocation location) {
IPrimarySourceLocation/*?*/ psloc = location as IPrimarySourceLocation;
if (psloc != null) {
IIncludedSourceLocation /*?*/ iloc = psloc as IncludedSourceLocation;
if (iloc != null)
yield return new OriginalSourceLocation(iloc);
else
yield return psloc;
} else {
IDerivedSourceLocation/*?*/ dsloc = location as IDerivedSourceLocation;
if (dsloc != null) {
foreach (IPrimarySourceLocation psl in dsloc.PrimarySourceLocations) {
IIncludedSourceLocation /*?*/ iloc = psl as IncludedSourceLocation;
if (iloc != null)
yield return new OriginalSourceLocation(iloc);
else
yield return psl;
}
}
var esloc = location as IExpressionSourceLocation;
if (esloc != null) {
yield return esloc.PrimarySourceLocation;
}
}
}
public IEnumerable<IPrimarySourceLocation> GetPrimarySourceLocationsForDefinitionOf(ILocalDefinition localDefinition) {
LocalDefinition locDef = localDefinition as LocalDefinition;
return Enumerable<IPrimarySourceLocation>.Empty;
}
public string GetSourceNameFor(ILocalDefinition localDefinition, out bool isCompilerGenerated) {
isCompilerGenerated = localDefinition.Name == Dummy.Name;
return localDefinition.Name.Value;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.EventHubs;
using Microsoft.Extensions.Logging;
using Orleans.Configuration;
using Orleans.Providers.Streams.Common;
using Orleans.Runtime;
using Orleans.Streams;
using Orleans.ServiceBus.Providers.Testing;
using Orleans.Hosting;
namespace Orleans.ServiceBus.Providers
{
/// <summary>
/// Event Hub Partition settings
/// </summary>
public class EventHubPartitionSettings
{
/// <summary>
/// Eventhub settings
/// </summary>
public EventHubOptions Hub { get; set; }
public EventHubReceiverOptions ReceiverOptions { get; set; }
/// <summary>
/// Partition name
/// </summary>
public string Partition { get; set; }
}
internal class EventHubAdapterReceiver : IQueueAdapterReceiver, IQueueCache
{
public const int MaxMessagesPerRead = 1000;
private static readonly TimeSpan ReceiveTimeout = TimeSpan.FromSeconds(5);
private readonly EventHubPartitionSettings settings;
private readonly Func<string, IStreamQueueCheckpointer<string>, ILoggerFactory, ITelemetryProducer, IEventHubQueueCache> cacheFactory;
private readonly Func<string, Task<IStreamQueueCheckpointer<string>>> checkpointerFactory;
private readonly ILoggerFactory loggerFactory;
private readonly ILogger logger;
private readonly IQueueAdapterReceiverMonitor monitor;
private readonly ITelemetryProducer telemetryProducer;
private readonly LoadSheddingOptions loadSheddingOptions;
private IEventHubQueueCache cache;
private IEventHubReceiver receiver;
private Func<EventHubPartitionSettings, string, ILogger, ITelemetryProducer, Task<IEventHubReceiver>> eventHubReceiverFactory;
private IStreamQueueCheckpointer<string> checkpointer;
private AggregatedQueueFlowController flowController;
// Receiver life cycle
private int recieverState = ReceiverShutdown;
private const int ReceiverShutdown = 0;
private const int ReceiverRunning = 1;
public int GetMaxAddCount()
{
return this.flowController.GetMaxAddCount();
}
public EventHubAdapterReceiver(EventHubPartitionSettings settings,
Func<string, IStreamQueueCheckpointer<string>, ILoggerFactory, ITelemetryProducer, IEventHubQueueCache> cacheFactory,
Func<string, Task<IStreamQueueCheckpointer<string>>> checkpointerFactory,
ILoggerFactory loggerFactory,
IQueueAdapterReceiverMonitor monitor,
LoadSheddingOptions loadSheddingOptions,
ITelemetryProducer telemetryProducer,
Func<EventHubPartitionSettings, string, ILogger, ITelemetryProducer, Task<IEventHubReceiver>> eventHubReceiverFactory = null)
{
if (settings == null) throw new ArgumentNullException(nameof(settings));
if (cacheFactory == null) throw new ArgumentNullException(nameof(cacheFactory));
if (checkpointerFactory == null) throw new ArgumentNullException(nameof(checkpointerFactory));
if (loggerFactory == null) throw new ArgumentNullException(nameof(loggerFactory));
if (monitor == null) throw new ArgumentNullException(nameof(monitor));
if (loadSheddingOptions == null) throw new ArgumentNullException(nameof(loadSheddingOptions));
if (telemetryProducer == null) throw new ArgumentNullException(nameof(telemetryProducer));
this.settings = settings;
this.cacheFactory = cacheFactory;
this.checkpointerFactory = checkpointerFactory;
this.loggerFactory = loggerFactory;
this.logger = this.loggerFactory.CreateLogger($"{this.GetType().FullName}.{settings.Hub.Path}.{settings.Partition}");
this.monitor = monitor;
this.telemetryProducer = telemetryProducer;
this.loadSheddingOptions = loadSheddingOptions;
this.eventHubReceiverFactory = eventHubReceiverFactory == null ? EventHubAdapterReceiver.CreateReceiver : eventHubReceiverFactory;
}
public Task Initialize(TimeSpan timeout)
{
this.logger.Info("Initializing EventHub partition {0}-{1}.", this.settings.Hub.Path, this.settings.Partition);
// if receiver was already running, do nothing
return ReceiverRunning == Interlocked.Exchange(ref this.recieverState, ReceiverRunning)
? Task.CompletedTask
: Initialize();
}
/// <summary>
/// Initialization of EventHub receiver is performed at adapter reciever initialization, but if it fails,
/// it will be retried when messages are requested
/// </summary>
/// <returns></returns>
private async Task Initialize()
{
var watch = Stopwatch.StartNew();
try
{
this.checkpointer = await this.checkpointerFactory(this.settings.Partition);
if(this.cache != null)
{
this.cache.Dispose();
this.cache = null;
}
this.cache = this.cacheFactory(this.settings.Partition, this.checkpointer, this.loggerFactory, this.telemetryProducer);
this.flowController = new AggregatedQueueFlowController(MaxMessagesPerRead) { this.cache, LoadShedQueueFlowController.CreateAsPercentOfLoadSheddingLimit(this.loadSheddingOptions) };
string offset = await this.checkpointer.Load();
this.receiver = await this.eventHubReceiverFactory(this.settings, offset, this.logger, this.telemetryProducer);
watch.Stop();
this.monitor?.TrackInitialization(true, watch.Elapsed, null);
}
catch (Exception ex)
{
watch.Stop();
this.monitor?.TrackInitialization(false, watch.Elapsed, ex);
throw;
}
}
public async Task<IList<IBatchContainer>> GetQueueMessagesAsync(int maxCount)
{
if (this.recieverState == ReceiverShutdown || maxCount <= 0)
{
return new List<IBatchContainer>();
}
// if receiver initialization failed, retry
if (this.receiver == null)
{
this.logger.Warn(OrleansServiceBusErrorCode.FailedPartitionRead,
"Retrying initialization of EventHub partition {0}-{1}.", this.settings.Hub.Path, this.settings.Partition);
await Initialize();
if (this.receiver == null)
{
// should not get here, should throw instead, but just incase.
return new List<IBatchContainer>();
}
}
var watch = Stopwatch.StartNew();
List<EventData> messages;
try
{
messages = (await this.receiver.ReceiveAsync(maxCount, ReceiveTimeout))?.ToList();
watch.Stop();
this.monitor?.TrackRead(true, watch.Elapsed, null);
}
catch (Exception ex)
{
watch.Stop();
this.monitor?.TrackRead(false, watch.Elapsed, ex);
this.logger.Warn(OrleansServiceBusErrorCode.FailedPartitionRead,
"Failed to read from EventHub partition {0}-{1}. : Exception: {2}.", this.settings.Hub.Path,
this.settings.Partition, ex);
throw;
}
var batches = new List<IBatchContainer>();
if (messages == null || messages.Count == 0)
{
this.monitor?.TrackMessagesReceived(0, null, null);
return batches;
}
// monitor message age
var dequeueTimeUtc = DateTime.UtcNow;
DateTime oldestMessageEnqueueTime = messages[0].SystemProperties.EnqueuedTimeUtc;
DateTime newestMessageEnqueueTime = messages[messages.Count - 1].SystemProperties.EnqueuedTimeUtc;
this.monitor?.TrackMessagesReceived(messages.Count, oldestMessageEnqueueTime, newestMessageEnqueueTime);
List<StreamPosition> messageStreamPositions = this.cache.Add(messages, dequeueTimeUtc);
foreach (var streamPosition in messageStreamPositions)
{
batches.Add(new StreamActivityNotificationBatch(streamPosition.StreamIdentity.Guid,
streamPosition.StreamIdentity.Namespace, streamPosition.SequenceToken));
}
if (!this.checkpointer.CheckpointExists)
{
this.checkpointer.Update(
messages[0].SystemProperties.Offset,
DateTime.UtcNow);
}
return batches;
}
public void AddToCache(IList<IBatchContainer> messages)
{
// do nothing, we add data directly into cache. No need for agent involvement
}
public bool TryPurgeFromCache(out IList<IBatchContainer> purgedItems)
{
purgedItems = null;
//if not under pressure, signal the cache to do a time based purge
//if under pressure, which means consuming speed is less than producing speed, then shouldn't purge, and don't read more message into the cache
if (!this.IsUnderPressure())
this.cache.SignalPurge();
return false;
}
public IQueueCacheCursor GetCacheCursor(IStreamIdentity streamIdentity, StreamSequenceToken token)
{
return new Cursor(this.cache, streamIdentity, token);
}
public bool IsUnderPressure()
{
return this.GetMaxAddCount() <= 0;
}
public Task MessagesDeliveredAsync(IList<IBatchContainer> messages)
{
return Task.CompletedTask;
}
public async Task Shutdown(TimeSpan timeout)
{
var watch = Stopwatch.StartNew();
try
{
// if receiver was already shutdown, do nothing
if (ReceiverShutdown == Interlocked.Exchange(ref this.recieverState, ReceiverShutdown))
{
return;
}
this.logger.Info("Stopping reading from EventHub partition {0}-{1}", this.settings.Hub.Path, this.settings.Partition);
// clear cache and receiver
IEventHubQueueCache localCache = Interlocked.Exchange(ref this.cache, null);
var localReceiver = Interlocked.Exchange(ref this.receiver, null);
// start closing receiver
Task closeTask = Task.CompletedTask;
if (localReceiver != null)
{
closeTask = localReceiver.CloseAsync();
}
// dispose of cache
localCache?.Dispose();
// finish return receiver closing task
await closeTask;
watch.Stop();
this.monitor?.TrackShutdown(true, watch.Elapsed, null);
}
catch (Exception ex)
{
watch.Stop();
this.monitor?.TrackShutdown(false, watch.Elapsed, ex);
throw;
}
}
private static async Task<IEventHubReceiver> CreateReceiver(EventHubPartitionSettings partitionSettings, string offset, ILogger logger, ITelemetryProducer telemetryProducer)
{
bool offsetInclusive = true;
var connectionStringBuilder = new EventHubsConnectionStringBuilder(partitionSettings.Hub.ConnectionString)
{
EntityPath = partitionSettings.Hub.Path
};
EventHubClient client = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());
// if we have a starting offset or if we're not configured to start reading from utc now, read from offset
if (!partitionSettings.ReceiverOptions.StartFromNow ||
offset != EventHubConstants.StartOfStream)
{
logger.Info("Starting to read from EventHub partition {0}-{1} at offset {2}", partitionSettings.Hub.Path, partitionSettings.Partition, offset);
}
else
{
// to start reading from most recent data, we get the latest offset from the partition.
EventHubPartitionRuntimeInformation partitionInfo =
await client.GetPartitionRuntimeInformationAsync(partitionSettings.Partition);
offset = partitionInfo.LastEnqueuedOffset;
offsetInclusive = false;
logger.Info("Starting to read latest messages from EventHub partition {0}-{1} at offset {2}", partitionSettings.Hub.Path, partitionSettings.Partition, offset);
}
PartitionReceiver receiver = client.CreateReceiver(partitionSettings.Hub.ConsumerGroup, partitionSettings.Partition, offset, offsetInclusive);
if (partitionSettings.ReceiverOptions.PrefetchCount.HasValue)
receiver.PrefetchCount = partitionSettings.ReceiverOptions.PrefetchCount.Value;
return new EventHubReceiverProxy(receiver);
}
/// <summary>
/// For test purpose. ConfigureDataGeneratorForStream will configure a data generator for the stream
/// </summary>
/// <param name="streamId"></param>
internal void ConfigureDataGeneratorForStream(IStreamIdentity streamId)
{
(this.receiver as EventHubPartitionGeneratorReceiver)?.ConfigureDataGeneratorForStream(streamId);
}
internal void StopProducingOnStream(IStreamIdentity streamId)
{
(this.receiver as EventHubPartitionGeneratorReceiver)?.StopProducingOnStream(streamId);
}
private class StreamActivityNotificationBatch : IBatchContainer
{
public Guid StreamGuid { get; }
public string StreamNamespace { get; }
public StreamSequenceToken SequenceToken { get; }
public StreamActivityNotificationBatch(Guid streamGuid, string streamNamespace,
StreamSequenceToken sequenceToken)
{
this.StreamGuid = streamGuid;
this.StreamNamespace = streamNamespace;
this.SequenceToken = sequenceToken;
}
public IEnumerable<Tuple<T, StreamSequenceToken>> GetEvents<T>() { throw new NotSupportedException(); }
public bool ImportRequestContext() { throw new NotSupportedException(); }
public bool ShouldDeliver(IStreamIdentity stream, object filterData, StreamFilterPredicate shouldReceiveFunc) { throw new NotSupportedException(); }
}
private class Cursor : IQueueCacheCursor
{
private readonly IEventHubQueueCache cache;
private readonly object cursor;
private IBatchContainer current;
public Cursor(IEventHubQueueCache cache, IStreamIdentity streamIdentity, StreamSequenceToken token)
{
this.cache = cache;
this.cursor = cache.GetCursor(streamIdentity, token);
}
public void Dispose()
{
}
public IBatchContainer GetCurrent(out Exception exception)
{
exception = null;
return this.current;
}
public bool MoveNext()
{
IBatchContainer next;
if (!this.cache.TryGetNextMessage(this.cursor, out next))
{
return false;
}
this.current = next;
return true;
}
public void Refresh(StreamSequenceToken token)
{
}
public void RecordDeliveryFailure()
{
}
}
}
}
| |
namespace dotless.Core.Parser.Tree
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using Exceptions;
using Infrastructure;
using Infrastructure.Nodes;
using Utils;
public class Color : Node, IOperable, IComparable
{
private static readonly Dictionary<int, string> Html4ColorsReverse;
private static readonly Dictionary<string, int> Html4Colors =
new Dictionary<string, int>
{
{ "aliceblue", 0xf0f8ff},
{ "antiquewhite", 0xfaebd7},
{ "aqua", 0x00ffff},
{ "aquamarine", 0x7fffd4},
{ "azure", 0xf0ffff},
{ "beige", 0xf5f5dc},
{ "bisque", 0xffe4c4},
{ "black", 0x000000},
{ "blanchedalmond", 0xffebcd},
{ "blue", 0x0000ff},
{ "blueviolet", 0x8a2be2},
{ "brown", 0xa52a2a},
{ "burlywood", 0xdeb887},
{ "cadetblue", 0x5f9ea0},
{ "chartreuse", 0x7fff00},
{ "chocolate", 0xd2691e},
{ "coral", 0xff7f50},
{ "cornflowerblue", 0x6495ed},
{ "cornsilk", 0xfff8dc},
{ "crimson", 0xdc143c},
{ "cyan", 0x00ffff},
{ "darkblue", 0x00008b},
{ "darkcyan", 0x008b8b},
{ "darkgoldenrod", 0xb8860b},
{ "darkgray", 0xa9a9a9},
{ "darkgrey", 0xa9a9a9},
{ "darkgreen", 0x006400},
{ "darkkhaki", 0xbdb76b},
{ "darkmagenta", 0x8b008b},
{ "darkolivegreen", 0x556b2f},
{ "darkorange", 0xff8c00},
{ "darkorchid", 0x9932cc},
{ "darkred", 0x8b0000},
{ "darksalmon", 0xe9967a},
{ "darkseagreen", 0x8fbc8f},
{ "darkslateblue", 0x483d8b},
{ "darkslategray", 0x2f4f4f},
{ "darkslategrey", 0x2f4f4f},
{ "darkturquoise", 0x00ced1},
{ "darkviolet", 0x9400d3},
{ "deeppink", 0xff1493},
{ "deepskyblue", 0x00bfff},
{ "dimgray", 0x696969},
{ "dimgrey", 0x696969},
{ "dodgerblue", 0x1e90ff},
{ "firebrick", 0xb22222},
{ "floralwhite", 0xfffaf0},
{ "forestgreen", 0x228b22},
{ "fuchsia", 0xff00ff},
{ "gainsboro", 0xdcdcdc},
{ "ghostwhite", 0xf8f8ff},
{ "gold", 0xffd700},
{ "goldenrod", 0xdaa520},
{ "gray", 0x808080},
{ "grey", 0x808080},
{ "green", 0x008000},
{ "greenyellow", 0xadff2f},
{ "honeydew", 0xf0fff0},
{ "hotpink", 0xff69b4},
{ "indianred", 0xcd5c5c},
{ "indigo", 0x4b0082},
{ "ivory", 0xfffff0},
{ "khaki", 0xf0e68c},
{ "lavender", 0xe6e6fa},
{ "lavenderblush", 0xfff0f5},
{ "lawngreen", 0x7cfc00},
{ "lemonchiffon", 0xfffacd},
{ "lightblue", 0xadd8e6},
{ "lightcoral", 0xf08080},
{ "lightcyan", 0xe0ffff},
{ "lightgoldenrodyellow", 0xfafad2},
{ "lightgray", 0xd3d3d3},
{ "lightgrey", 0xd3d3d3},
{ "lightgreen", 0x90ee90},
{ "lightpink", 0xffb6c1},
{ "lightsalmon", 0xffa07a},
{ "lightseagreen", 0x20b2aa},
{ "lightskyblue", 0x87cefa},
{ "lightslategray", 0x778899},
{ "lightslategrey", 0x778899},
{ "lightsteelblue", 0xb0c4de},
{ "lightyellow", 0xffffe0},
{ "lime", 0x00ff00},
{ "limegreen", 0x32cd32},
{ "linen", 0xfaf0e6},
{ "magenta", 0xff00ff},
{ "maroon", 0x800000},
{ "mediumaquamarine", 0x66cdaa},
{ "mediumblue", 0x0000cd},
{ "mediumorchid", 0xba55d3},
{ "mediumpurple", 0x9370d8},
{ "mediumseagreen", 0x3cb371},
{ "mediumslateblue", 0x7b68ee},
{ "mediumspringgreen", 0x00fa9a},
{ "mediumturquoise", 0x48d1cc},
{ "mediumvioletred", 0xc71585},
{ "midnightblue", 0x191970},
{ "mintcream", 0xf5fffa},
{ "mistyrose", 0xffe4e1},
{ "moccasin", 0xffe4b5},
{ "navajowhite", 0xffdead},
{ "navy", 0x000080},
{ "oldlace", 0xfdf5e6},
{ "olive", 0x808000},
{ "olivedrab", 0x6b8e23},
{ "orange", 0xffa500},
{ "orangered", 0xff4500},
{ "orchid", 0xda70d6},
{ "palegoldenrod", 0xeee8aa},
{ "palegreen", 0x98fb98},
{ "paleturquoise", 0xafeeee},
{ "palevioletred", 0xd87093},
{ "papayawhip", 0xffefd5},
{ "peachpuff", 0xffdab9},
{ "peru", 0xcd853f},
{ "pink", 0xffc0cb},
{ "plum", 0xdda0dd},
{ "powderblue", 0xb0e0e6},
{ "purple", 0x800080},
{ "red", 0xff0000},
{ "rosybrown", 0xbc8f8f},
{ "royalblue", 0x4169e1},
{ "saddlebrown", 0x8b4513},
{ "salmon", 0xfa8072},
{ "sandybrown", 0xf4a460},
{ "seagreen", 0x2e8b57},
{ "seashell", 0xfff5ee},
{ "sienna", 0xa0522d},
{ "silver", 0xc0c0c0},
{ "skyblue", 0x87ceeb},
{ "slateblue", 0x6a5acd},
{ "slategray", 0x708090},
{ "slategrey", 0x708090},
{ "snow", 0xfffafa},
{ "springgreen", 0x00ff7f},
{ "steelblue", 0x4682b4},
{ "tan", 0xd2b48c},
{ "teal", 0x008080},
{ "thistle", 0xd8bfd8},
{ "tomato", 0xff6347},
{ "turquoise", 0x40e0d0},
{ "violet", 0xee82ee},
{ "wheat", 0xf5deb3},
{ "white", 0xffffff},
{ "whitesmoke", 0xf5f5f5},
{ "yellow", 0xffff00},
{ "yellowgreen", 0x9acd32 }
};
static Color()
{
Html4ColorsReverse = new Dictionary<int, string>();
foreach (KeyValuePair<string, int> color in Html4Colors)
{
if (Html4ColorsReverse.ContainsKey(color.Value))
{
if (Html4ColorsReverse[color.Value].Length <= color.Key.Length)
{
continue;
}
}
Html4ColorsReverse[color.Value] = color.Key;
}
}
private bool isArgb = false;
public readonly double[] RGB;
public readonly double Alpha;
public Color(double[] rgb) : this(rgb, 1)
{
}
public Color(double[] rgb, double alpha)
{
RGB = rgb;
Alpha = alpha;
}
public Color(IEnumerable<Number> rgb, Number alpha)
{
RGB = rgb
.Select(d => d.Normalize(255d))
.ToArray<double>();
Alpha = alpha.Normalize();
}
public Color(string hex)
{
Alpha = 1;
if (hex.Length == 8)
{
isArgb = true;
RGB = Enumerable.Range(1, 3)
.Select(i => hex.Substring(i * 2, 2))
.Select(s => (double) int.Parse(s, NumberStyles.HexNumber))
.ToArray();
Alpha = (double) int.Parse(hex.Substring(0, 2), NumberStyles.HexNumber) / 255d;
}
else if (hex.Length == 6)
{
RGB = Enumerable.Range(0, 3)
.Select(i => hex.Substring(i*2, 2))
.Select(s => (double) int.Parse(s, NumberStyles.HexNumber))
.ToArray();
}
else
{
RGB = hex.ToCharArray()
.Select(c => (double) int.Parse("" + c + c, NumberStyles.HexNumber))
.ToArray();
}
}
public Color(double red, double green, double blue, double alpha)
{
RGB = new[]
{
NumberExtensions.Normalize(red, 255d),
NumberExtensions.Normalize(green, 255d),
NumberExtensions.Normalize(blue, 255d)
};
Alpha = NumberExtensions.Normalize(alpha);
}
public Color(double red, double green, double blue)
: this(red, green, blue, 1d)
{
}
public Color(int color)
{
RGB = new double[3];
B = color & 0xff;
color >>= 8;
G = color & 0xff;
color >>= 8;
R = color & 0xff;
Alpha = 1;
}
public double R
{
get { return RGB[0]; }
set { RGB[0] = value; }
}
public double G
{
get { return RGB[1]; }
set { RGB[1] = value; }
}
public double B
{
get { return RGB[2]; }
set { RGB[2] = value; }
}
/// <summary>
/// Transforms the linear to SRBG. Formula derivation decscribed <a href="http://en.wikipedia.org/wiki/SRGB#Theory_of_the_transformation">here</a>
/// </summary>
/// <param name="linearChannel">The linear channel, for example R/255</param>
/// <returns>The sRBG value for the given channel</returns>
private double TransformLinearToSrbg(double linearChannel)
{
const double decodingGamma = 2.4;
const double phi = 12.92;
const double alpha = .055;
return (linearChannel <= 0.03928) ? linearChannel / phi : Math.Pow(((linearChannel + alpha) / (1 + alpha)), decodingGamma);
}
/// <summary>
/// Calculates the luma value based on the <a href="http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef">W3 Standard</a>
/// </summary>
/// <value>
/// The luma value for the current color
/// </value>
public double Luma
{
get
{
var linearR = R / 255;
var linearG = G / 255;
var linearB = B / 255;
var red = TransformLinearToSrbg(linearR);
var green = TransformLinearToSrbg(linearG);
var blue = TransformLinearToSrbg(linearB);
return 0.2126 * red + 0.7152 * green + 0.0722 * blue;
}
}
public override void AppendCSS(Env env)
{
var rgb = RGB
.Select(d => (int) Math.Round(d, MidpointRounding.AwayFromZero))
.Select(i => i > 255 ? 255 : (i < 0 ? 0 : i))
.ToArray();
if (Alpha == 0 && rgb[0] == 0 && rgb[1] == 0 && rgb[2] == 0)
{
env.Output.AppendFormat(CultureInfo.InvariantCulture, "transparent");
return;
}
if (isArgb)
{
env.Output.Append(ToArgb());
return;
}
if (Alpha < 1.0)
{
env.Output.AppendFormat(CultureInfo.InvariantCulture, "rgba({0}, {1}, {2}, {3})", rgb[0], rgb[1], rgb[2], Alpha);
return;
}
var keyword = GetKeyword(rgb);
var hexString = '#' + rgb
.Select(i => i.ToString("X2"))
.JoinStrings("")
.ToLowerInvariant();
if (env.Compress && !env.DisableColorCompression)
{
hexString = Regex.Replace(hexString, @"#(.)\1(.)\2(.)\3", "#$1$2$3");
env.Output.Append(string.IsNullOrEmpty(keyword) || hexString.Length < keyword.Length ? hexString : keyword);
return;
}
env.Output.Append(!string.IsNullOrEmpty(keyword) ? keyword : hexString);
}
public Node Operate(Operation op, Node other)
{
var otherColor = other as Color;
if (otherColor == null)
{
var operable = other as IOperable;
if(operable == null)
throw new ParsingException(string.Format("Unable to convert right hand side of {0} to a color", op.Operator), op.Location);
otherColor = operable.ToColor();
}
var result = new double[3];
for (var c = 0; c < 3; c++)
{
result[c] = Operation.Operate(op.Operator, RGB[c], otherColor.RGB[c]);
}
return new Color(result)
.ReducedFrom<Node>(this, other);
}
public Color ToColor()
{
return this;
}
public string GetKeyword(int[] rgb)
{
var color = (rgb[0] << 16) + (rgb[1] << 8) + rgb[2];
string keyword;
if (Html4ColorsReverse.TryGetValue(color, out keyword))
return keyword;
return null;
}
public static Color GetColorFromKeyword(string keyword)
{
int color;
if (keyword == "transparent")
{
return new Color(0, 0, 0, 0);
}
if (Html4Colors.TryGetValue(keyword, out color))
return new Color(color);
return null;
}
/// <summary>
/// Returns in the IE ARGB format e.g ##FF001122 = rgba(0x00, 0x11, 0x22, 1)
/// </summary>
/// <returns></returns>
public string ToArgb()
{
var argb =
new double[] { Alpha * 255 }
.Concat(RGB)
.Select(d => (int)Math.Round(d, MidpointRounding.AwayFromZero))
.Select(i => i > 255 ? 255 : (i < 0 ? 0 : i))
.ToArray();
return '#' + argb
.Select(i => i.ToString("X2"))
.JoinStrings("")
.ToLowerInvariant();
}
public int CompareTo(object obj)
{
var col = obj as Color;
if (col == null)
{
return -1;
}
if (col.R == R && col.G == G && col.B == B && col.Alpha == Alpha)
{
return 0;
}
return (((256 * 3) - (col.R + col.G + col.B)) * col.Alpha) < (((256 * 3) - (R + G + B)) * Alpha) ? 1 : -1;
}
public static explicit operator System.Drawing.Color(Color color)
{
if (color == null)
throw new ArgumentNullException("color");
return System.Drawing.Color.FromArgb((int) Math.Round(color.Alpha * 255d), (int) color.R, (int) color.G, (int) color.B);
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Flavor;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudioTools;
using IServiceProvider = System.IServiceProvider;
namespace Microsoft.PythonTools.Uwp.Project {
[Guid("27BB1268-135A-4409-914F-7AA64AD8195D")]
partial class PythonUwpProject :
FlavoredProjectBase,
IOleCommandTarget,
IVsProjectFlavorCfgProvider,
IVsProject,
IVsFilterAddProjectItemDlg {
private PythonUwpPackage _package;
internal IVsProject _innerProject;
internal IVsProject3 _innerProject3;
private IVsProjectFlavorCfgProvider _innerVsProjectFlavorCfgProvider;
private static Guid PythonProjectGuid = new Guid(PythonConstants.ProjectFactoryGuid);
private IOleCommandTarget _menuService;
public PythonUwpProject() {
}
internal PythonUwpPackage Package {
get { return _package; }
set {
Debug.Assert(_package == null);
if (_package != null) {
throw new InvalidOperationException("PythonUwpProject.Package must only be set once");
}
_package = value;
}
}
#region IVsAggregatableProject
/// <summary>
/// Do the initialization here (such as loading flavor specific
/// information from the project)
/// </summary>
protected override void InitializeForOuter(string fileName, string location, string name, uint flags, ref Guid guidProject, out bool cancel) {
base.InitializeForOuter(fileName, location, name, flags, ref guidProject, out cancel);
}
#endregion
protected override int QueryStatusCommand(uint itemid, ref Guid pguidCmdGroup, uint cCmds, VisualStudio.OLE.Interop.OLECMD[] prgCmds, IntPtr pCmdText) {
if (pguidCmdGroup == GuidList.guidOfficeSharePointCmdSet) {
for (int i = 0; i < prgCmds.Length; i++) {
// Report it as supported so that it's not routed any
// further, but disable it and make it invisible.
prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_INVISIBLE);
}
return VSConstants.S_OK;
}
return base.QueryStatusCommand(itemid, ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
}
protected override void SetInnerProject(IntPtr innerIUnknown) {
var inner = Marshal.GetObjectForIUnknown(innerIUnknown);
// The reason why we keep a reference to those is that doing a QI after being
// aggregated would do the AddRef on the outer object.
_innerVsProjectFlavorCfgProvider = inner as IVsProjectFlavorCfgProvider;
_innerProject = inner as IVsProject;
_innerProject3 = inner as IVsProject3;
_innerVsHierarchy = inner as IVsHierarchy;
// Ensure we have a service provider as this is required for menu items to work
if (this.serviceProvider == null) {
this.serviceProvider = (IServiceProvider)Package;
}
// Now let the base implementation set the inner object
base.SetInnerProject(innerIUnknown);
// Get access to the menu service used by FlavoredProjectBase. We
// need to forward IOleCommandTarget functions to this object, since
// we override the FlavoredProjectBase implementation with no way to
// call it directory.
// (This must run after we called base.SetInnerProject)
_menuService = (IOleCommandTarget)((IServiceProvider)this).GetService(typeof(IMenuCommandService));
if (_menuService == null) {
throw new InvalidOperationException("Cannot initialize Uwp project");
}
}
protected override int GetProperty(uint itemId, int propId, out object property) {
switch ((__VSHPROPID2)propId) {
case __VSHPROPID2.VSHPROPID_CfgPropertyPagesCLSIDList:
{
var res = base.GetProperty(itemId, propId, out property);
if (ErrorHandler.Succeeded(res)) {
var guids = GetGuidsFromList(property as string);
guids.RemoveAll(g => CfgSpecificPropertyPagesToRemove.Contains(g));
guids.AddRange(CfgSpecificPropertyPagesToAdd);
property = MakeListFromGuids(guids);
}
return res;
}
case __VSHPROPID2.VSHPROPID_PropertyPagesCLSIDList:
{
var res = base.GetProperty(itemId, propId, out property);
if (ErrorHandler.Succeeded(res)) {
var guids = GetGuidsFromList(property as string);
guids.RemoveAll(g => PropertyPagesToRemove.Contains(g));
guids.AddRange(PropertyPagesToAdd);
property = MakeListFromGuids(guids);
}
return res;
}
}
switch ((__VSHPROPID6)propId) {
case __VSHPROPID6.VSHPROPID_Subcaption:
{
var bps = this._innerProject as IVsBuildPropertyStorage;
string descriptor = null;
if (bps != null) {
var res = bps.GetPropertyValue("TargetOsAndVersion", null, (uint)_PersistStorageType.PST_PROJECT_FILE, out descriptor);
property = descriptor;
return res;
}
break;
}
}
return base.GetProperty(itemId, propId, out property);
}
private static Guid[] PropertyPagesToAdd = new Guid[0];
private static Guid[] CfgSpecificPropertyPagesToAdd = new Guid[] {
new Guid(GuidList.guidUwpPropertyPageString)
};
private static HashSet<Guid> PropertyPagesToRemove = new HashSet<Guid> {
new Guid("{8C0201FE-8ECA-403C-92A3-1BC55F031979}"), // typeof(DeployPropertyPageComClass)
new Guid("{ED3B544C-26D8-4348-877B-A1F7BD505ED9}"), // typeof(DatabaseDeployPropertyPageComClass)
new Guid("{909D16B3-C8E8-43D1-A2B8-26EA0D4B6B57}"), // Microsoft.VisualStudio.Web.Application.WebPropertyPage
new Guid("{379354F2-BBB3-4BA9-AA71-FBE7B0E5EA94}"), // Microsoft.VisualStudio.Web.Application.SilverlightLinksPage
new Guid("{A553AD0B-2F9E-4BCE-95B3-9A1F7074BC27}"), // Package/Publish Web
new Guid("{9AB2347D-948D-4CD2-8DBE-F15F0EF78ED3}"), // Package/Publish SQL
new Guid(PythonConstants.DebugPropertyPageGuid),
new Guid(PythonConstants.GeneralPropertyPageGuid),
new Guid(PythonConstants.PublishPropertyPageGuid)
};
internal static HashSet<Guid> CfgSpecificPropertyPagesToRemove = new HashSet<Guid>(new Guid[] { Guid.Empty });
private static List<Guid> GetGuidsFromList(string guidList) {
if (string.IsNullOrEmpty(guidList)) {
return new List<Guid>();
}
Guid value;
return guidList.Split(';')
.Select(str => Guid.TryParse(str, out value) ? (Guid?)value : null)
.Where(g => g.HasValue)
.Select(g => g.Value)
.ToList();
}
private static string MakeListFromGuids(IEnumerable<Guid> guidList) {
return string.Join(";", guidList.Select(g => g.ToString("B")));
}
internal string RemovePropertyPagesFromList(string propertyPagesList, string[] pagesToRemove) {
if (pagesToRemove == null || !pagesToRemove.Any()) {
return propertyPagesList;
}
var guidsToRemove = new HashSet<Guid>(
pagesToRemove.Select(str => { Guid guid; return Guid.TryParse(str, out guid) ? guid : Guid.Empty; })
);
guidsToRemove.Add(Guid.Empty);
return string.Join(
";",
propertyPagesList.Split(';')
.Where(str => !string.IsNullOrEmpty(str))
.Select(str => { Guid guid; return Guid.TryParse(str, out guid) ? guid : Guid.Empty; })
.Except(guidsToRemove)
.Select(guid => guid.ToString("B"))
);
}
int IOleCommandTarget.Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) {
return _menuService.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
}
int IOleCommandTarget.QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) {
return _menuService.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
}
#region IVsProjectFlavorCfgProvider Members
public int CreateProjectFlavorCfg(IVsCfg pBaseProjectCfg, out IVsProjectFlavorCfg ppFlavorCfg) {
// We're flavored with a Windows Store Application project and our normal
// project... But we don't want the web application project to
// influence our config as that alters our debug launch story. We
// control that w/ the web project which is actually just letting
// the base Python project handle it. So we keep the base Python
// project config here.
IVsProjectFlavorCfg uwpCfg;
ErrorHandler.ThrowOnFailure(
_innerVsProjectFlavorCfgProvider.CreateProjectFlavorCfg(
pBaseProjectCfg,
out uwpCfg
)
);
ppFlavorCfg = new PythonUwpProjectConfig(pBaseProjectCfg, uwpCfg);
return VSConstants.S_OK;
}
#endregion
#region IVsProject Members
int IVsProject.AddItem(uint itemidLoc, VSADDITEMOPERATION dwAddItemOperation, string pszItemName, uint cFilesToOpen, string[] rgpszFilesToOpen, IntPtr hwndDlgOwner, VSADDRESULT[] pResult) {
return _innerProject.AddItem(itemidLoc, dwAddItemOperation, pszItemName, cFilesToOpen, rgpszFilesToOpen, hwndDlgOwner, pResult);
}
int IVsProject.GenerateUniqueItemName(uint itemidLoc, string pszExt, string pszSuggestedRoot, out string pbstrItemName) {
return _innerProject.GenerateUniqueItemName(itemidLoc, pszExt, pszSuggestedRoot, out pbstrItemName);
}
int IVsProject.GetItemContext(uint itemid, out VisualStudio.OLE.Interop.IServiceProvider ppSP) {
return _innerProject.GetItemContext(itemid, out ppSP);
}
int IVsProject.GetMkDocument(uint itemid, out string pbstrMkDocument) {
return _innerProject.GetMkDocument(itemid, out pbstrMkDocument);
}
int IVsProject.IsDocumentInProject(string pszMkDocument, out int pfFound, VSDOCUMENTPRIORITY[] pdwPriority, out uint pitemid) {
return _innerProject.IsDocumentInProject(pszMkDocument, out pfFound, pdwPriority, out pitemid);
}
int IVsProject.OpenItem(uint itemid, ref Guid rguidLogicalView, IntPtr punkDocDataExisting, out IVsWindowFrame ppWindowFrame) {
return _innerProject.OpenItem(itemid, rguidLogicalView, punkDocDataExisting, out ppWindowFrame);
}
#endregion
#region IVsFilterAddProjectItemDlg Members
int IVsFilterAddProjectItemDlg.FilterListItemByLocalizedName(ref Guid rguidProjectItemTemplates, string pszLocalizedName, out int pfFilter) {
pfFilter = 0;
return VSConstants.S_OK;
}
int IVsFilterAddProjectItemDlg.FilterListItemByTemplateFile(ref Guid rguidProjectItemTemplates, string pszTemplateFile, out int pfFilter) {
pfFilter = 0;
return VSConstants.S_OK;
}
int IVsFilterAddProjectItemDlg.FilterTreeItemByLocalizedName(ref Guid rguidProjectItemTemplates, string pszLocalizedName, out int pfFilter) {
pfFilter = 0;
return VSConstants.S_OK;
}
int IVsFilterAddProjectItemDlg.FilterTreeItemByTemplateDir(ref Guid rguidProjectItemTemplates, string pszTemplateDir, out int pfFilter) {
// https://pytools.codeplex.com/workitem/1313
// ASP.NET will filter some things out, including .css files, which we don't want it to do.
// So we shut that down by not forwarding this to any inner projects, which is fine, because
// Python projects don't implement this interface either.
pfFilter = 0;
return VSConstants.S_OK;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Bond.Comm
{
using System;
using System.Diagnostics;
/// <summary>
/// Interface representing a message of an unknown payload type.
/// </summary>
/// <remarks>
/// A message can contain either a payload or an error, represented by
/// <see cref="Bond.Comm.Error"/>.
/// </remarks>
public interface IMessage
{
/// <summary>
/// Gets the payload as a <see cref="IBonded"/> value.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown when the message contains an error and not a payload.
/// </exception>
IBonded RawPayload { get; }
/// <summary>
/// Gets the error, if any.
/// </summary>
/// <remarks>
/// If the message has a payload and no error, <c>null</c> is returned.
/// </remarks>
IBonded<Error> Error { get; }
/// <summary>
/// Gets a value indicating whether the message contains an error.
/// </summary>
/// <remarks>
/// If a message does not contain an error, it contains a payload.
/// </remarks>
bool IsError { get; }
/// <summary>
/// Converts this message to an <see cref="IMessage{T}">IMessage<U></see>.
/// </summary>
/// <typeparam name="U">The new type of the message payload.</typeparam>
/// <returns>
/// An instance of <see cref="IMessage{T}">IMessage<U></see>. If the conversion fails,
/// <c>null</c> is returned.
/// </returns>
IMessage<U> Convert<U>();
}
/// <summary>
/// Interface representing a message of specific payload type.
/// </summary>
/// <typeparam name="T">The type of the message payload.</typeparam>
/// <remarks>
/// A message can contain either a payload or an error, represented by
/// <see cref="Bond.Comm.Error"/>.
/// </remarks>
public interface IMessage<out T> : IMessage
{
/// <summary>
/// Gets the payload as a <see cref="IBonded{T}">IBonded<T></see>
/// value.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown when the message contains an error and not a payload.
/// </exception>
IBonded<T> Payload { get; }
}
/// <summary>
/// A message of an unknown payload type.
/// </summary>
public class Message : IMessage
{
private IBonded payload;
private IBonded<Error> error;
/// <summary>
/// Initializes a Message with the given payload.
/// </summary>
/// <param name="payload">The payload for the message.</param>
public Message(IBonded payload)
{
if (payload == null)
{
throw new ArgumentNullException(nameof(payload));
}
this.payload = payload;
error = null;
}
// To create an error Message, use Message.FromError<TPayload>() or Message.FromError().
//
// This ctor is internal so that a non-error Message<Error> can be created. If this were
// public, then new Message<Error>(SomeError) would resolve to this ctor, creating an error
// message, instead of to the generic ctor. We need new Message<Error>(SomeError) to resolve
// to the generic ctor to create a non-error Message.
internal Message(IBonded<Error> error)
{
if (error == null)
{
throw new ArgumentNullException(nameof(error));
}
payload = null;
this.error = error;
}
/// <summary>
/// Creates a message from the given payload.
/// </summary>
/// <param name="payload">The payload for the message.</param>
/// <returns>A payload message of unknown payload type.</returns>
public static IMessage FromPayload(IBonded payload)
{
if (payload == null)
{
throw new ArgumentNullException(nameof(payload));
}
return new Message(payload);
}
/// <summary>
/// Creates a message from the given payload.
/// </summary>
/// <typeparam name="TPayload">
/// The type of the message payload.
/// </typeparam>
/// <param name="payload">The payload for the message.</param>
/// <returns>A payload message of the given payload type.</returns>
public static IMessage<TPayload> FromPayload<TPayload>(TPayload payload)
{
if (payload == null)
{
throw new ArgumentNullException(nameof(payload));
}
return FromPayload(MakeMostDerivedIBonded(payload));
}
/// <summary>
/// Creates a message from the given payload.
/// </summary>
/// <typeparam name="TPayload">
/// The type of the message payload.
/// </typeparam>
/// <param name="payload">The payload for the message.</param>
/// <returns>A payload message of the given payload type.</returns>
public static IMessage<TPayload> FromPayload<TPayload>(IBonded<TPayload> payload)
{
if (payload == null)
{
throw new ArgumentNullException(nameof(payload));
}
return new Message<TPayload>(payload);
}
/// <summary>
/// Creates an error message from the given Error.
/// </summary>
/// <typeparam name="TPayload">
/// The type of the message payload
/// </typeparam>
/// <param name="err">The Error for the message.</param>
/// <returns>An error message of the given payload type.</returns>
public static IMessage<TPayload> FromError<TPayload>(Error err)
{
if (err == null)
{
throw new ArgumentNullException(nameof(err));
}
return FromError<TPayload>(MakeMostDerivedIBonded(err));
}
/// <summary>
/// Creates an error message from the given Error.
/// </summary>
/// <typeparam name="TPayload">
/// The type of the message payload.
/// </typeparam>
/// <param name="err">The Error for the message.</param>
/// <returns>An error message of the given payload type.</returns>
public static IMessage<TPayload> FromError<TPayload>(IBonded<Error> err)
{
if (err == null)
{
throw new ArgumentNullException(nameof(err));
}
return new Message<TPayload>(err);
}
/// <summary>
/// Creates an error message from the given error.
/// </summary>
/// <param name="err">The Error for the message.</param>
/// <returns>An error message of unknown payload type.</returns>
public static IMessage FromError(Error err)
{
if (err == null)
{
throw new ArgumentNullException(nameof(err));
}
return FromError(MakeMostDerivedIBonded(err));
}
/// <summary>
/// Creates an error message from the given Error.
/// </summary>
/// <param name="err">The Error for the message.</param>
/// <returns>An error message of unknown payload type.</returns>
public static IMessage FromError(IBonded<Error> err)
{
if (err == null)
{
throw new ArgumentNullException(nameof(err));
}
return new Message(err);
}
internal static IBonded<TActual> MakeMostDerivedIBonded<TActual>(TActual payload)
{
if (payload == null)
{
throw new ArgumentNullException(nameof(payload));
}
Type ibondedType = typeof (Bonded<>).MakeGenericType(payload.GetType());
return (IBonded<TActual>) Activator.CreateInstance(ibondedType, payload);
}
public IBonded RawPayload
{
get
{
if (IsError)
{
throw new InvalidOperationException("The Payload of this message cannot be accessed, as this message contains an error.");
}
Debug.Assert(payload != null);
return payload;
}
}
public IBonded<Error> Error
{
get
{
Debug.Assert((payload == null) ^ (error == null));
return error;
}
}
public bool IsError
{
get
{
Debug.Assert((payload == null) ^ (error == null));
return error != null;
}
}
public IMessage<U> Convert<U>()
{
if (IsError)
{
return FromError<U>(error);
}
else
{
return FromPayload(payload.Convert<U>());
}
}
}
/// <summary>
/// A message of known type.
/// </summary>
/// <typeparam name="TPayload">The type of the message payload.</typeparam>
public class Message<TPayload> : Message, IMessage<TPayload>
{
/// <summary>
/// Creates a payload message from the given payload.
/// </summary>
/// <param name="payload">The message payload.</param>
public Message(TPayload payload) : base(Message.MakeMostDerivedIBonded(payload)) { }
/// <summary>
/// Creates a payload message from the given payload.
/// </summary>
/// <param name="payload">The message payload.</param>
public Message(IBonded<TPayload> payload) : base(payload)
{
}
internal Message(IBonded<Error> error) : base(error)
{
}
public IBonded<TPayload> Payload
{
get
{
return RawPayload.Convert<TPayload>();
}
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TestExtensions.cs" company="">
//
// </copyright>
// <summary>
// The test extensions.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace UX.Testing.Core.Extensions
{
using System;
using System.Collections;
using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>The test extensions.</summary>
[DebuggerStepThrough]
public static class TestExtensions
{
#region Public Methods and Operators
/// <summary>Asserts that two strings are equal, without regard to case. </summary>
/// <param name="expected">The expected string.</param>
/// <param name="actual">The actual string.</param>
public static void AreEqualIgnoringCase(string expected, string actual)
{
AreEqualIgnoringCase(expected, actual, "Expected <{0}> but actual was <{1}>.", expected, actual);
}
/// <summary>Asserts that two strings are equal, without regard to case. </summary>
/// <param name="expected">The expected string.</param>
/// <param name="actual">The actual string.</param>
/// <param name="message">A message to display. This message can be seen in the unit test results.</param>
/// <param name="parameters">An array of parameters to use when formatting <paramref name="message"/>.</param>
public static void AreEqualIgnoringCase(string expected, string actual, string message, params object[] parameters)
{
Assert.IsTrue(string.Compare(expected, actual, StringComparison.CurrentCultureIgnoreCase) == 0, message, parameters);
}
/// <summary>The cast to.</summary>
/// <param name="source">The source.</param>
/// <typeparam name="T"></typeparam>
/// <returns>The <see cref="T"/>.</returns>
public static T CastTo<T>(this object source)
{
return (T)source;
}
/// <summary>Assert that an array, list or other collection is empty.</summary>
/// <param name="collection">The value to be tested.</param>
public static void IsEmpty(ICollection collection)
{
IsEmpty(collection, "Expected a collection containing <0> items but actual was <{0}> items.", 0, collection.Count);
}
/// <summary>Assert that an array, list or other collection is empty.</summary>
/// <param name="collection">The value to be tested.</param>
/// <param name="message">A message to display. This message can be seen in the unit test results.</param>
public static void IsEmpty(ICollection collection, string message)
{
IsEmpty(collection, message, null);
}
/// <summary>Assert that an array, list or other collection is empty.</summary>
/// <param name="collection">The value to be tested.</param>
/// <param name="message">A message to display. This message can be seen in the unit test results.</param>
/// <param name="parameters">An array of parameters to use when formatting <paramref name="message"/>.</param>
public static void IsEmpty(ICollection collection, string message, params object[] parameters)
{
Assert.IsTrue(collection.Count == 0, message, parameters);
}
/// <summary>Asserts that a string is empty.</summary>
/// <param name="value">The value to be tested.</param>
public static void IsEmpty(string value)
{
IsEmpty(value, "Expected <{0}> but actual was <{1}>.", string.Empty, value);
}
/// <summary>Asserts that a string is empty.</summary>
/// <param name="value">The value to be tested.</param>
/// <param name="message">A message to display. This message can be seen in the unit test results.</param>
/// <param name="parameters">An array of parameters to use when formatting <paramref name="message"/>.</param>
public static void IsEmpty(string value, string message, params object[] parameters)
{
Assert.IsTrue(value.Length == 0, message, parameters);
}
/// <summary>Assert that an array, list or other collection is not empty.</summary>
/// <param name="collection">The value to be tested.</param>
public static void IsNotEmpty(ICollection collection)
{
IsNotEmpty(collection, "Expected a collection containing <0> items but actual was <{0}> items.", collection.Count, 0);
}
/// <summary>Assert that an array, list or other collection is not empty.</summary>
/// <param name="collection">The value to be tested.</param>
/// <param name="message">A message to display. This message can be seen in the unit test results.</param>
/// <param name="parameters">An array of parameters to use when formatting <paramref name="message"/>.</param>
public static void IsNotEmpty(ICollection collection, string message, params object[] parameters)
{
Assert.IsFalse(collection.Count == 0, message, parameters);
}
/// <summary>Asserts that a string is not empty.</summary>
/// <param name="value">The value to be tested.</param>
public static void IsNotEmpty(string value)
{
IsNotEmpty(value, "Expected <{0}> but actual was <{1}>.", value, string.Empty);
}
/// <summary>Asserts that a string is not empty.</summary>
/// <param name="value">The value to be tested.</param>
/// <param name="message">A message to display. This message can be seen in the unit test results.</param>
/// <param name="parameters">An array of parameters to use when formatting <paramref name="message"/>.</param>
public static void IsNotEmpty(string value, string message, params object[] parameters)
{
Assert.IsFalse(value.Length == 0, message, parameters);
}
/// <summary>The should be.</summary>
/// <param name="actual">The actual.</param>
/// <typeparam name="T"></typeparam>
public static void ShouldBe<T>(this object actual)
{
Assert.IsInstanceOfType(actual, typeof(T));
}
/// <summary>The should be.</summary>
/// <param name="actual">The actual.</param>
/// <param name="message"></param>
/// <param name="parameters"></param>
/// <typeparam name="T"></typeparam>
public static void ShouldBe<T>(this object actual, string message, params object[] parameters)
{
Assert.IsInstanceOfType(actual, typeof(T), message, parameters);
}
/// <summary>The should be false verifies that the specified condition is false.</summary>
/// <param name="source">The source.</param>
public static void ShouldBeFalse(this bool source)
{
Assert.IsFalse(source);
}
/// <summary>The should be false.</summary>
/// <param name="source">The source.</param>
/// <param name="message">The message.</param>
/// <param name="parameters">The parameters.</param>
public static void ShouldBeFalse(this bool source, string message, params object[] parameters)
{
Assert.IsFalse(source, message, parameters);
}
/// <summary>The should be null.</summary>
/// <param name="actual">The actual.</param>
public static void ShouldBeNull(this object actual)
{
Assert.IsNull(actual);
}
/// <summary>The should be null.</summary>
/// <param name="actual">The actual.</param>
/// <param name="message">The message.</param>
/// <param name="parameters">The parameters.</param>
public static void ShouldBeNull(this object actual, string message, params object[] parameters)
{
Assert.IsNull(actual, message, parameters);
}
/// <summary>Compares the two strings (case-insensitive).</summary>
/// <param name="actual"></param>
/// <param name="expected"></param>
public static void ShouldBeSameStringAs(this string actual, string expected)
{
if (!string.Equals(actual, expected, StringComparison.InvariantCultureIgnoreCase))
{
var message = string.Format("Expected {0} but was {1}", expected, actual);
throw new AssertFailedException(message);
}
}
/// <summary>The should be same string as.</summary>
/// <param name="actual">The actual.</param>
/// <param name="expected">The expected.</param>
/// <param name="message">The message.</param>
/// <param name="parameters">The parameters.</param>
/// <exception cref="Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException"></exception>
public static void ShouldBeSameStringAs(this string actual, string expected, string message, params object[] parameters)
{
if (!string.Equals(actual, expected, StringComparison.InvariantCultureIgnoreCase))
{
var msg = string.Format(message, parameters);
throw new AssertFailedException(msg);
}
}
/// <summary>The should be the same as verifies that two specified objects refer to the same object.</summary>
/// <param name="actual">The actual.</param>
/// <param name="expected">The expected.</param>
public static void ShouldBeTheSameAs(this object actual, object expected)
{
Assert.AreSame(expected, actual);
}
/// <summary>The should be the same as.</summary>
/// <param name="actual">The actual.</param>
/// <param name="expected">The expected.</param>
/// <param name="message">The message.</param>
/// <param name="parameters">The parameters.</param>
public static void ShouldBeTheSameAs(this object actual, object expected, string message, params object[] parameters)
{
Assert.AreSame(expected, actual, message, parameters);
}
/// <summary>The should be true.</summary>
/// <param name="source">The source.</param>
public static void ShouldBeTrue(this bool source)
{
Assert.IsTrue(source);
}
/// <summary>The should be true.</summary>
/// <param name="source">The source.</param>
/// <param name="message">The message.</param>
/// <param name="parameters">The parameters.</param>
public static void ShouldBeTrue(this bool source, string message, params object[] parameters)
{
Assert.IsTrue(source, message, parameters);
}
/// <summary>The should equal.</summary>
/// <param name="actual">The actual.</param>
/// <param name="expected">The expected.</param>
/// <typeparam name="T"></typeparam>
/// <returns>The <see cref="T"/>.</returns>
public static T ShouldEqual<T>(this T actual, object expected)
{
Assert.AreEqual(expected, actual);
return actual;
}
/// <summary>Asserts that two objects are equal.</summary>
/// <param name="actual"></param>
/// <param name="expected"></param>
/// <param name="message"></param>
/// <param name="parameters"></param>
/// <exception cref="AssertionException"></exception>
public static void ShouldEqual(this object actual, object expected, string message, params object[] parameters)
{
Assert.AreEqual(expected, actual, message, parameters);
}
/// <summary>The should not be null.</summary>
/// <param name="obj">The obj.</param>
/// <typeparam name="T"></typeparam>
/// <returns>The <see cref="T"/>.</returns>
public static T ShouldNotBeNull<T>(this T obj)
{
Assert.IsNotNull(obj);
return obj;
}
/// <summary>The should not be null.</summary>
/// <param name="obj">The obj.</param>
/// <param name="message">The message.</param>
/// <param name="parameters"></param>
/// <typeparam name="T"></typeparam>
/// <returns>The <see cref="T"/>.</returns>
public static T ShouldNotBeNull<T>(this T obj, string message, params object[] parameters)
{
Assert.IsNotNull(obj, message, parameters);
return obj;
}
/// <summary>The should be not be the same as verifies that two specified objects refer to different objects.</summary>
/// <param name="actual">The actual.</param>
/// <param name="expected">The expected.</param>
public static void ShouldNotBeTheSameAs(this object actual, object expected)
{
Assert.AreNotSame(expected, actual);
}
/// <summary>The should not be the same as.</summary>
/// <param name="actual">The actual.</param>
/// <param name="expected">The expected.</param>
/// <param name="message">The message.</param>
/// <param name="parameters">The parameters.</param>
public static void ShouldNotBeTheSameAs(this object actual, object expected, string message, params object[] parameters)
{
Assert.AreNotSame(expected, actual, message, parameters);
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using SLNetworkComm;
using libsecondlife;
namespace SLeek
{
public partial class InventoryConsole : UserControl
{
private SleekInstance instance;
private SLNetCom netcom;
private SecondLife client;
private Dictionary<LLUUID, TreeNode> treeLookup = new Dictionary<LLUUID, TreeNode>();
private InventoryTreeSorter treeSorter = new InventoryTreeSorter();
private InventoryClipboard clip;
private InventoryItemConsole currentProperties;
private InventoryManager.FolderUpdatedCallback folderUpdate;
private InventoryManager.ItemReceivedCallback itemReceived;
private InventoryManager.ObjectOfferedCallback objectOffer;
public InventoryConsole(SleekInstance instance)
{
InitializeComponent();
this.instance = instance;
netcom = this.instance.Netcom;
client = this.instance.Client;
clip = new InventoryClipboard(client);
ApplyConfig(this.instance.Config.CurrentConfig);
this.instance.Config.ConfigApplied += new EventHandler<ConfigAppliedEventArgs>(Config_ConfigApplied);
this.Disposed += new EventHandler(InventoryConsole_Disposed);
InitializeImageList();
InitializeTree();
GetRoot();
}
private void InitializeImageList()
{
ilsInventory.Images.Add("ArrowForward", Properties.Resources.arrow_forward_16);
ilsInventory.Images.Add("ClosedFolder", Properties.Resources.folder_closed_16);
ilsInventory.Images.Add("OpenFolder", Properties.Resources.folder_open_16);
ilsInventory.Images.Add("Gear", Properties.Resources.applications_16);
ilsInventory.Images.Add("Notecard", Properties.Resources.documents_16);
ilsInventory.Images.Add("Script", Properties.Resources.lsl_scripts_16);
}
private void InitializeTree()
{
foreach (ITreeSortMethod method in treeSorter.GetSortMethods())
{
ToolStripMenuItem item = (ToolStripMenuItem)tbtnSort.DropDown.Items.Add(method.Name);
item.ToolTipText = method.Description;
item.Name = method.Name;
item.Click += new EventHandler(SortMethodClick);
}
((ToolStripMenuItem)tbtnSort.DropDown.Items[0]).PerformClick();
treInventory.TreeViewNodeSorter = treeSorter;
folderUpdate = new InventoryManager.FolderUpdatedCallback(Inventory_OnFolderUpdated);
itemReceived = new InventoryManager.ItemReceivedCallback(Inventory_OnItemReceived);
objectOffer = new InventoryManager.ObjectOfferedCallback(Inventory_OnObjectOffered);
client.Inventory.OnFolderUpdated += folderUpdate;
client.Inventory.OnItemReceived += itemReceived;
client.Inventory.OnObjectOffered += objectOffer;
}
//Seperate thread
private void Inventory_OnItemReceived(InventoryItem item)
{
BeginInvoke(
new InventoryManager.ItemReceivedCallback(ReceivedInventoryItem),
new object[] { item });
}
//UI thread
private void ReceivedInventoryItem(InventoryItem item)
{
ProcessIncomingObject(item);
}
//Separate thread
private bool Inventory_OnObjectOffered(LLUUID fromAgentID, string fromAgentName, uint parentEstateID, LLUUID regionID, LLVector3 position, DateTime timestamp, AssetType type, LLUUID objectID, bool fromTask)
{
BeginInvoke(
new InventoryManager.ObjectOfferedCallback(ReceivedInventoryOffer),
new object[] { fromAgentID, fromAgentName, parentEstateID, regionID, position, timestamp, type, objectID, fromTask });
return true;
}
//UI thread
private bool ReceivedInventoryOffer(LLUUID fromAgentID, string fromAgentName, uint parentEstateID, LLUUID regionID, LLVector3 position, DateTime timestamp, AssetType type, LLUUID objectID, bool fromTask)
{
if (!client.Inventory.Store.Contains(objectID)) return true;
InventoryBase invObj = client.Inventory.Store[objectID];
ProcessIncomingObject(invObj);
return true;
}
//Seperate thread
private void Inventory_OnFolderUpdated(LLUUID folderID)
{
BeginInvoke(
new InventoryManager.FolderUpdatedCallback(FolderDownloadFinished),
new object[] { folderID });
}
//UI thread
private void FolderDownloadFinished(LLUUID folderID)
{
InventoryBase invObj = client.Inventory.Store[folderID];
ProcessIncomingObject(invObj);
}
private void GetRoot()
{
InventoryFolder rootFolder = client.Inventory.Store.RootFolder;
TreeNode rootNode = treInventory.Nodes.Add(rootFolder.UUID.ToString(), "My Inventory");
rootNode.Tag = rootFolder;
rootNode.ImageKey = "ClosedFolder";
treeLookup.Add(rootFolder.UUID, rootNode);
//Triggers treInventory's AfterExpand event, thus triggering the root content request
rootNode.Nodes.Add("Requesting folder contents...");
rootNode.Expand();
}
private void Config_ConfigApplied(object sender, ConfigAppliedEventArgs e)
{
ApplyConfig(e.AppliedConfig);
}
private void ApplyConfig(Config config)
{
if (config.InterfaceStyle == 0)
tstInventory.RenderMode = ToolStripRenderMode.System;
else if (config.InterfaceStyle == 1)
tstInventory.RenderMode = ToolStripRenderMode.ManagerRenderMode;
}
private void InventoryConsole_Disposed(object sender, EventArgs e)
{
CleanUp();
}
public void CleanUp()
{
ClearCurrentProperties();
client.Inventory.OnFolderUpdated -= folderUpdate;
client.Inventory.OnObjectOffered -= objectOffer;
}
private void SortMethodClick(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(treeSorter.CurrentSortName))
((ToolStripMenuItem)tbtnSort.DropDown.Items[treeSorter.CurrentSortName]).Checked = false;
ToolStripMenuItem item = (ToolStripMenuItem)sender;
treeSorter.CurrentSortName = item.Text;
treInventory.BeginUpdate();
treInventory.Sort();
treInventory.EndUpdate();
item.Checked = true;
}
private void ProcessIncomingObject(InventoryBase io)
{
if (io is InventoryFolder)
{
InventoryFolder folder = (InventoryFolder)io;
TreeNode node = treeLookup[folder.UUID];
treInventory.BeginUpdate();
node.Nodes.Clear();
List<InventoryBase> folderContents = client.Inventory.Store.GetContents(folder);
if (folderContents.Count > 0)
{
ProcessInventoryItems(folderContents, node);
treInventory.Sort();
if (!node.IsVisible)
{
node.LastNode.EnsureVisible();
node.EnsureVisible();
}
}
treInventory.EndUpdate();
}
else if (io is InventoryItem)
{
InventoryItem item = (InventoryItem)io;
TreeNode node = treeLookup[item.ParentUUID];
treInventory.BeginUpdate();
TreeNode itemNode = AddTreeItem(item, node);
treInventory.Sort();
if (!itemNode.IsVisible)
{
if (node.IsExpanded)
{
node.LastNode.EnsureVisible();
itemNode.EnsureVisible();
}
}
treInventory.EndUpdate();
}
}
private TreeNode AddTreeFolder(InventoryFolder folder, TreeNode node)
{
if (treeLookup.ContainsKey(folder.UUID))
return treeLookup[folder.UUID];
TreeNode folderNode = node.Nodes.Add(folder.UUID.ToString(), folder.Name);
folderNode.Tag = folder;
folderNode.ImageKey = "ClosedFolder";
treeLookup.Add(folder.UUID, folderNode);
return folderNode;
}
private TreeNode AddTreeItem(InventoryItem item, TreeNode node)
{
if (treeLookup.ContainsKey(item.UUID))
return treeLookup[item.UUID];
TreeNode itemNode = node.Nodes.Add(item.UUID.ToString(), item.Name);
itemNode.Tag = item;
switch (item.InventoryType)
{
case InventoryType.Wearable:
itemNode.ImageKey = "Gear"; //TODO: use "clothing" key instead
break;
case InventoryType.Notecard:
itemNode.ImageKey = "Notecard";
break;
case InventoryType.LSL:
itemNode.ImageKey = "Script";
break;
case InventoryType.Texture:
itemNode.ImageKey = "Gear"; //TODO: use "image" key instead
break;
default:
itemNode.ImageKey = "Gear";
break;
}
treeLookup.Add(item.UUID, itemNode);
return itemNode;
}
//Recursive! :o
private void ProcessInventoryItems(List<InventoryBase> list, TreeNode node)
{
if (list == null) return;
foreach (InventoryBase item in list)
{
if (item is InventoryFolder)
{
InventoryFolder folder = (InventoryFolder)item;
TreeNode folderNode = AddTreeFolder(folder, node);
List<InventoryBase> contents = client.Inventory.Store.GetContents(folder);
if (contents.Count > 0)
ProcessInventoryItems(contents, folderNode);
else
folderNode.Nodes.Add("Requesting folder contents...");
}
else if (item is InventoryItem)
{
AddTreeItem((InventoryItem)item, node);
}
}
}
private void AddNewFolder(string folderName, TreeNode node)
{
if (node == null) return;
InventoryFolder folder = null;
TreeNode folderNode = null;
if (node.Tag is InventoryFolder)
{
folder = (InventoryFolder)node.Tag;
folderNode = node;
}
else if (node.Tag is InventoryItem)
{
folder = (InventoryFolder)node.Parent.Tag;
folderNode = node.Parent;
}
treInventory.BeginUpdate();
LLUUID newFolderID = client.Inventory.CreateFolder(folder.UUID, folderName, AssetType.Folder);
InventoryFolder newFolder = (InventoryFolder)client.Inventory.Store[newFolderID];
TreeNode newNode = AddTreeFolder(newFolder, folderNode);
treInventory.Sort();
treInventory.EndUpdate();
}
private void AddNewNotecard(string notecardName, string notecardDescription, string notecardContent, TreeNode node)
{
if (node == null) return;
InventoryFolder folder = null;
TreeNode folderNode = null;
if (node.Tag is InventoryFolder)
{
folder = (InventoryFolder)node.Tag;
folderNode = node;
}
else if (node.Tag is InventoryItem)
{
folder = (InventoryFolder)node.Parent.Tag;
folderNode = node.Parent;
}
InventoryManager.ItemCreatedCallback itemCreated =
new InventoryManager.ItemCreatedCallback(delegate(bool success, InventoryItem item)
{
if (!success) return;
treInventory.BeginUpdate();
AddTreeItem(item, folderNode);
treInventory.Sort();
treInventory.EndUpdate();
});
client.Inventory.RequestCreateItem(
folder.UUID, notecardName, notecardDescription,
AssetType.Notecard, InventoryType.Notecard, PermissionMask.All,
itemCreated);
}
private void AddNewScript(string name, string description, string content, TreeNode node)
{
if (node == null) return;
InventoryFolder folder = null;
TreeNode folderNode = null;
if (node.Tag is InventoryFolder)
{
folder = (InventoryFolder)node.Tag;
folderNode = node;
}
else if (node.Tag is InventoryItem)
{
folder = (InventoryFolder)node.Parent.Tag;
folderNode = node.Parent;
}
InventoryManager.ItemCreatedCallback itemCreated =
new InventoryManager.ItemCreatedCallback(delegate(bool success, InventoryItem item)
{
if (!success) return;
treInventory.BeginUpdate();
AddTreeItem(item, folderNode);
treInventory.Sort();
treInventory.EndUpdate();
});
client.Inventory.RequestCreateItem(
folder.UUID, name, description,
AssetType.LSLText, InventoryType.LSL, PermissionMask.All,
itemCreated);
}
private void DeleteItem(TreeNode node)
{
if (node == null) return;
InventoryBase io = (InventoryBase)node.Tag;
if (io is InventoryFolder)
{
InventoryFolder folder = (InventoryFolder)io;
treeLookup.Remove(folder.UUID);
client.Inventory.RemoveFolder(folder.UUID);
folder = null;
}
else if (io is InventoryItem)
{
InventoryItem item = (InventoryItem)io;
treeLookup.Remove(item.UUID);
client.Inventory.RemoveItem(item.UUID);
item = null;
}
io = null;
node.Remove();
node = null;
}
private void treInventory_AfterExpand(object sender, TreeViewEventArgs e)
{
if (e.Node.Nodes[0].Tag == null)
{
InventoryFolder folder = (InventoryFolder)e.Node.Tag;
client.Inventory.RequestFolderContents(folder.UUID, client.Self.AgentID, true, true, InventorySortOrder.ByName);
}
e.Node.ImageKey = "OpenFolder";
}
private void treInventory_AfterCollapse(object sender, TreeViewEventArgs e)
{
e.Node.ImageKey = "ClosedFolder";
}
private void tmnuNewFolder_Click(object sender, EventArgs e)
{
string newFolderName = "New Folder";
if (treInventory.SelectedNode == null)
AddNewFolder(newFolderName, treInventory.Nodes[0]);
else
AddNewFolder(newFolderName, treInventory.SelectedNode);
}
private void ClearCurrentProperties()
{
if (currentProperties == null) return;
currentProperties.CleanUp();
currentProperties.Dispose();
currentProperties = null;
}
private void RefreshPropertiesPane()
{
if (treInventory.SelectedNode == null) return;
InventoryBase io = (InventoryBase)treInventory.SelectedNode.Tag;
if (io is InventoryItem)
{
InventoryItemConsole console = new InventoryItemConsole(instance, (InventoryItem)io);
console.Dock = DockStyle.Fill;
splitContainer1.Panel2.Controls.Add(console);
ClearCurrentProperties();
currentProperties = console;
}
else
{
ClearCurrentProperties();
}
}
private void treInventory_AfterSelect(object sender, TreeViewEventArgs e)
{
tbtnNew.Enabled = tbtnOrganize.Enabled = (treInventory.SelectedNode != null);
RefreshPropertiesPane();
}
private void tmnuDelete_Click(object sender, EventArgs e)
{
DeleteItem(treInventory.SelectedNode);
}
private void tmnuRename_Click(object sender, EventArgs e)
{
treInventory.SelectedNode.BeginEdit();
}
private void treInventory_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
{
if (e.CancelEdit) return;
e.CancelEdit = true; //temporary until we can actually rename stuff
/*
if (e.Node.Tag is InventoryFolder)
((InventoryFolder)e.Node.Tag).Name = e.Label;
else if (e.Node.Tag is InventoryItem)
((InventoryItem)e.Node.Tag).Name = e.Label;
e.Node.Text = e.Label;
*/
}
private void tmnuNewNotecard_Click(object sender, EventArgs e)
{
string newNotecardName = "New Notecard";
string newNotecardDescription = string.Empty;
string newNotecardContent = string.Empty;
if (treInventory.SelectedNode == null)
AddNewNotecard(
newNotecardName,
newNotecardDescription,
newNotecardContent,
treInventory.Nodes[0]);
else
AddNewNotecard(
newNotecardName,
newNotecardDescription,
newNotecardContent,
treInventory.SelectedNode);
}
private void tmnuCut_Click(object sender, EventArgs e)
{
clip.SetClipboardNode(treInventory.SelectedNode, true);
tmnuPaste.Enabled = true;
}
private void tmnuPaste_Click(object sender, EventArgs e)
{
clip.PasteTo(treInventory.SelectedNode);
tmnuPaste.Enabled = false;
}
private void tmnuNewScript_Click(object sender, EventArgs e)
{
string newScriptName = "New Script";
string newScriptDescription = string.Empty;
string newScriptContent = string.Empty;
if (treInventory.SelectedNode == null)
AddNewScript(
newScriptName,
newScriptDescription,
newScriptContent,
treInventory.Nodes[0]);
else
AddNewScript(
newScriptName,
newScriptDescription,
newScriptContent,
treInventory.SelectedNode);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using Validation;
namespace System.Collections.Immutable
{
public partial struct ImmutableArray<T>
{
/// <summary>
/// A writable array accessor that can be converted into an <see cref="ImmutableArray{T}"/>
/// instance without allocating memory.
/// </summary>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ImmutableArrayBuilderDebuggerProxy<>))]
public sealed class Builder : IList<T>, IReadOnlyList<T>
{
/// <summary>
/// The backing array for the builder.
/// </summary>
private RefAsValueType<T>[] elements;
/// <summary>
/// The number of initialized elements in the array.
/// </summary>
private int count;
/// <summary>
/// Initializes a new instance of the <see cref="Builder"/> class.
/// </summary>
/// <param name="capacity">The initial capacity of the internal array.</param>
internal Builder(int capacity)
{
Requires.Range(capacity >= 0, "capacity");
this.elements = new RefAsValueType<T>[capacity];
this.Count = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="Builder"/> class.
/// </summary>
internal Builder()
: this(8)
{
}
/// <summary>
/// Gets or sets the length of the array.
/// </summary>
/// <remarks>
/// If the value is decreased, the array contents are truncated.
/// If the value is increased, the added elements are initialized to <c>default(T)</c>.
/// </remarks>
public int Count
{
get
{
return this.count;
}
set
{
Requires.Range(value >= 0, "value");
if (value < this.count)
{
// truncation mode
// Clear the elements of the elements that are effectively removed.
var e = this.elements;
// PERF: Array.Clear works well for big arrays,
// but may have too much overhead with small ones (which is the common case here)
if (this.count - value > 64)
{
Array.Clear(this.elements, value, this.count - value);
}
else
{
for (int i = value; i < this.Count; i++)
{
this.elements[i].Value = default(T);
}
}
}
else if (value > this.count)
{
// expansion
this.EnsureCapacity(value);
}
this.count = value;
}
}
/// <summary>
/// Gets or sets the element at the specified index.
/// </summary>
/// <param name="index">The index.</param>
/// <returns></returns>
/// <exception cref="System.IndexOutOfRangeException">
/// </exception>
public T this[int index]
{
get
{
if (index >= this.Count)
{
throw new IndexOutOfRangeException();
}
return this.elements[index].Value;
}
set
{
if (index >= this.Count)
{
throw new IndexOutOfRangeException();
}
this.elements[index].Value = value;
}
}
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only.
/// </summary>
/// <returns>true if the <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only; otherwise, false.
/// </returns>
bool ICollection<T>.IsReadOnly
{
get { return false; }
}
/// <summary>
/// Returns an immutable copy of the current contents of this collection.
/// </summary>
/// <returns>An immutable array.</returns>
public ImmutableArray<T> ToImmutable()
{
if (this.Count == 0)
{
return Empty;
}
return new ImmutableArray<T>(this.ToArray());
}
/// <summary>
/// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1" />.
/// </summary>
public void Clear()
{
this.Count = 0;
}
/// <summary>
/// Inserts an item to the <see cref="T:System.Collections.Generic.IList`1" /> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which <paramref name="item" /> should be inserted.</param>
/// <param name="item">The object to insert into the <see cref="T:System.Collections.Generic.IList`1" />.</param>
public void Insert(int index, T item)
{
Requires.Range(index >= 0 && index <= this.Count, "index");
this.EnsureCapacity(this.Count + 1);
if (index < this.Count)
{
Array.Copy(this.elements, index, this.elements, index + 1, this.Count - index);
}
this.count++;
this.elements[index].Value = item;
}
/// <summary>
/// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1" />.
/// </summary>
/// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1" />.</param>
public void Add(T item)
{
this.EnsureCapacity(this.Count + 1);
this.elements[this.count++].Value = item;
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange(IEnumerable<T> items)
{
Requires.NotNull(items, "items");
int count;
if (items.TryGetCount(out count))
{
this.EnsureCapacity(this.Count + count);
}
foreach (var item in items)
{
this.Add(item);
}
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange(params T[] items)
{
Requires.NotNull(items, "items");
var offset = this.Count;
this.Count += items.Length;
var nodes = this.elements;
for (int i = 0; i < items.Length; i++)
{
nodes[offset + i].Value = items[i];
}
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange<TDerived>(TDerived[] items) where TDerived : T
{
Requires.NotNull(items, "items");
var offset = this.Count;
this.Count += items.Length;
var nodes = this.elements;
for (int i = 0; i < items.Length; i++)
{
nodes[offset + i].Value = items[i];
}
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
/// <param name="length">The number of elements from the source array to add.</param>
public void AddRange(T[] items, int length)
{
Requires.NotNull(items, "items");
Requires.Range(length >= 0, "length");
var offset = this.Count;
this.Count += length;
var nodes = this.elements;
for (int i = 0; i < length; i++)
{
nodes[offset + i].Value = items[i];
}
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange(ImmutableArray<T> items)
{
this.AddRange(items, items.Length);
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
/// <param name="length">The number of elements from the source array to add.</param>
public void AddRange(ImmutableArray<T> items, int length)
{
Requires.Range(length >= 0, "length");
if (items.array != null)
{
this.AddRange(items.array, length);
}
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange<TDerived>(ImmutableArray<TDerived> items) where TDerived : T
{
if (items.array != null)
{
this.AddRange(items.array);
}
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange(Builder items)
{
Requires.NotNull(items, "items");
this.AddRange(items.elements, items.Count);
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange<TDerived>(ImmutableArray<TDerived>.Builder items) where TDerived : T
{
Requires.NotNull(items, "items");
this.AddRange(items.elements, items.Count);
}
/// <summary>
/// Removes the specified element.
/// </summary>
/// <param name="element">The element.</param>
/// <returns>A value indicating whether the specified element was found and removed from the collection.</returns>
public bool Remove(T element)
{
int index = this.IndexOf(element);
if (index >= 0)
{
this.RemoveAt(index);
return true;
}
return false;
}
/// <summary>
/// Removes the <see cref="T:System.Collections.Generic.IList`1" /> item at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the item to remove.</param>
public void RemoveAt(int index)
{
Requires.Range(index >= 0 && index < this.Count, "index");
if (index < this.Count - 1)
{
Array.Copy(this.elements, index + 1, this.elements, index, this.Count - index - 1);
}
this.Count--;
}
/// <summary>
/// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1" /> contains a specific value.
/// </summary>
/// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1" />.</param>
/// <returns>
/// true if <paramref name="item" /> is found in the <see cref="T:System.Collections.Generic.ICollection`1" />; otherwise, false.
/// </returns>
public bool Contains(T item)
{
return this.IndexOf(item) >= 0;
}
/// <summary>
/// Creates a new array with the current contents of this Builder.
/// </summary>
public T[] ToArray()
{
var tmp = new T[this.Count];
var elements = this.elements;
for (int i = 0; i < tmp.Length; i++)
{
tmp[i] = elements[i].Value;
}
return tmp;
}
/// <summary>
/// Copies the current contents to the specified array.
/// </summary>
/// <param name="array">The array to copy to.</param>
/// <param name="index">The starting index of the target array.</param>
public void CopyTo(T[] array, int index)
{
Requires.NotNull(array, "array");
Requires.Range(index >= 0 && index + this.Count <= array.Length, "start");
foreach (var item in this)
{
array[index++] = item;
}
}
/// <summary>
/// Resizes the array to accommodate the specified capacity requirement.
/// </summary>
/// <param name="capacity">The required capacity.</param>
public void EnsureCapacity(int capacity)
{
if (this.elements.Length < capacity)
{
int newCapacity = Math.Max(this.elements.Length * 2, capacity);
Array.Resize(ref this.elements, newCapacity);
}
}
/// <summary>
/// Determines the index of a specific item in the <see cref="T:System.Collections.Generic.IList`1" />.
/// </summary>
/// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.IList`1" />.</param>
/// <returns>
/// The index of <paramref name="item" /> if found in the list; otherwise, -1.
/// </returns>
[Pure]
public int IndexOf(T item)
{
return this.IndexOf(item, 0, this.count, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int IndexOf(T item, int startIndex)
{
return this.IndexOf(item, startIndex, this.Count - startIndex, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <param name="count">The number of elements to search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int IndexOf(T item, int startIndex, int count)
{
return this.IndexOf(item, startIndex, count, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <param name="count">The number of elements to search.</param>
/// <param name="equalityComparer">The equality comparer to use in the search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int IndexOf(T item, int startIndex, int count, IEqualityComparer<T> equalityComparer)
{
Requires.NotNull(equalityComparer, "equalityComparer");
if (count == 0 && startIndex == 0)
{
return -1;
}
Requires.Range(startIndex >= 0 && startIndex < this.Count, "startIndex");
Requires.Range(count >= 0 && startIndex + count <= this.Count, "count");
if (equalityComparer == EqualityComparer<T>.Default)
{
return Array.IndexOf(this.elements, new RefAsValueType<T>(item), startIndex, count);
}
else
{
for (int i = startIndex; i < startIndex + count; i++)
{
if (equalityComparer.Equals(this.elements[i].Value, item))
{
return i;
}
}
return -1;
}
}
/// <summary>
/// Searches the array for the specified item in reverse.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int LastIndexOf(T item)
{
if (this.Count == 0)
{
return -1;
}
return this.LastIndexOf(item, this.Count - 1, this.Count, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item in reverse.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int LastIndexOf(T item, int startIndex)
{
if (this.Count == 0 && startIndex == 0)
{
return -1;
}
Requires.Range(startIndex >= 0 && startIndex < this.Count, "startIndex");
return this.LastIndexOf(item, startIndex, startIndex + 1, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item in reverse.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <param name="count">The number of elements to search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int LastIndexOf(T item, int startIndex, int count)
{
return this.LastIndexOf(item, startIndex, count, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item in reverse.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <param name="count">The number of elements to search.</param>
/// <param name="equalityComparer">The equality comparer to use in the search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int LastIndexOf(T item, int startIndex, int count, IEqualityComparer<T> equalityComparer)
{
Requires.NotNull(equalityComparer, "equalityComparer");
if (count == 0 && startIndex == 0)
{
return -1;
}
Requires.Range(startIndex >= 0 && startIndex < this.Count, "startIndex");
Requires.Range(count >= 0 && startIndex - count + 1 >= 0, "count");
if (equalityComparer == EqualityComparer<T>.Default)
{
return Array.LastIndexOf(this.elements, new RefAsValueType<T>(item), startIndex, count);
}
else
{
for (int i = startIndex; i >= startIndex - count + 1; i--)
{
if (equalityComparer.Equals(item, this.elements[i].Value))
{
return i;
}
}
return -1;
}
}
/// <summary>
/// Reverses the order of elements in the collection.
/// </summary>
public void ReverseContents()
{
int end = this.Count - 1;
for (int i = 0, j = end; i < j; i++, j--)
{
var tmp = this.elements[i].Value;
this.elements[i] = this.elements[j];
this.elements[j].Value = tmp;
}
}
/// <summary>
/// Sorts the array.
/// </summary>
public void Sort()
{
if (Count > 1)
{
Array.Sort(this.elements, 0, this.Count, Comparer.Default);
}
}
/// <summary>
/// Sorts the array.
/// </summary>
/// <param name="comparer">The comparer to use in sorting. If <c>null</c>, the default comparer is used.</param>
public void Sort(IComparer<T> comparer)
{
if (Count > 1)
{
Array.Sort(this.elements, 0, this.Count, Comparer.Create(comparer));
}
}
/// <summary>
/// Sorts the array.
/// </summary>
/// <param name="index">The index of the first element to consider in the sort.</param>
/// <param name="count">The number of elements to include in the sort.</param>
/// <param name="comparer">The comparer to use in sorting. If <c>null</c>, the default comparer is used.</param>
public void Sort(int index, int count, IComparer<T> comparer)
{
// Don't rely on Array.Sort's argument validation since our internal array may exceed
// the bounds of the publically addressable region.
Requires.Range(index >= 0, "index");
Requires.Range(count >= 0 && index + count <= this.Count, "count");
if (count > 1)
{
Array.Sort(this.elements, index, count, Comparer.Create(comparer));
}
}
/// <summary>
/// Returns an enumerator for the contents of the array.
/// </summary>
/// <returns>An enumerator.</returns>
public IEnumerator<T> GetEnumerator()
{
for (int i = 0; i < this.Count; i++)
{
yield return this[i];
}
}
/// <summary>
/// Returns an enumerator for the contents of the array.
/// </summary>
/// <returns>An enumerator.</returns>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// Returns an enumerator for the contents of the array.
/// </summary>
/// <returns>An enumerator.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// Adds items to this collection.
/// </summary>
/// <typeparam name="TDerived">The type of source elements.</typeparam>
/// <param name="items">The source array.</param>
/// <param name="length">The number of elements to add to this array.</param>
private void AddRange<TDerived>(RefAsValueType<TDerived>[] items, int length) where TDerived : T
{
this.EnsureCapacity(this.Count + length);
var offset = this.Count;
this.Count += length;
var nodes = this.elements;
for (int i = 0; i < length; i++)
{
nodes[offset + i].Value = items[i].Value;
}
}
private sealed class Comparer : IComparer<RefAsValueType<T>>
{
private readonly IComparer<T> comparer;
public static readonly Comparer Default = new Comparer(Comparer<T>.Default);
public static Comparer Create(IComparer<T> comparer)
{
if (comparer == null || comparer == Comparer<T>.Default)
{
return Default;
}
return new Comparer(comparer);
}
private Comparer(IComparer<T> comparer)
{
Requires.NotNull(comparer, "comparer"); // use Comparer.Default instead of passing null
this.comparer = comparer;
}
public int Compare(RefAsValueType<T> x, RefAsValueType<T> y)
{
return this.comparer.Compare(x.Value, y.Value);
}
}
}
}
/// <summary>
/// A simple view of the immutable collection that the debugger can show to the developer.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class ImmutableArrayBuilderDebuggerProxy<T>
{
/// <summary>
/// The collection to be enumerated.
/// </summary>
private readonly ImmutableArray<T>.Builder builder;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableArrayBuilderDebuggerProxy<T>"/> class.
/// </summary>
/// <param name="builder">The collection to display in the debugger</param>
public ImmutableArrayBuilderDebuggerProxy(ImmutableArray<T>.Builder builder)
{
this.builder = builder;
}
/// <summary>
/// Gets a simple debugger-viewable collection.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public T[] A
{
get
{
return this.builder.ToArray();
}
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using IronPython.Runtime.Operations;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
#if FEATURE_NUMERICS
using System.Numerics;
#else
using Microsoft.Scripting.Math;
#endif
namespace IronPython.Runtime {
/// <summary>
/// StringFormatter provides Python's % style string formatting services.
/// </summary>
internal class StringFormatter {
const int UnspecifiedPrecision = -1; // Use the default precision
private readonly CodeContext/*!*/ _context;
private object _data;
private int _dataIndex;
private string _str;
private int _index;
private char _curCh;
// The options for formatting the current formatting specifier in the format string
internal FormatSettings _opts;
// Should ddd.0 be displayed as "ddd" or "ddd.0". "'%g' % ddd.0" needs "ddd", but str(ddd.0) needs "ddd.0"
internal bool _TrailingZeroAfterWholeFloat = false;
private StringBuilder _buf;
// This is a ThreadStatic since so that formatting operations on one thread do not interfere with other threads
[ThreadStatic]
private static NumberFormatInfo NumberFormatInfoForThreadLower;
[ThreadStatic]
private static NumberFormatInfo NumberFormatInfoForThreadUpper;
internal static NumberFormatInfo nfil {
get {
if (NumberFormatInfoForThreadLower == null) {
NumberFormatInfo numberFormatInfo = ((CultureInfo)CultureInfo.InvariantCulture.Clone()).NumberFormat;
// The CLI formats as "Infinity", but CPython formats differently
numberFormatInfo.PositiveInfinitySymbol = "inf";
numberFormatInfo.NegativeInfinitySymbol = "-inf";
numberFormatInfo.NaNSymbol = "nan";
NumberFormatInfoForThreadLower = numberFormatInfo;
}
return NumberFormatInfoForThreadLower;
}
}
internal static NumberFormatInfo nfiu {
get {
if (NumberFormatInfoForThreadUpper == null) {
NumberFormatInfo numberFormatInfo = ((CultureInfo)CultureInfo.InvariantCulture.Clone()).NumberFormat;
// The CLI formats as "Infinity", but CPython formats differently
numberFormatInfo.PositiveInfinitySymbol = "INF";
numberFormatInfo.NegativeInfinitySymbol = "-INF";
numberFormatInfo.NaNSymbol = "NAN";
NumberFormatInfoForThreadUpper = numberFormatInfo;
}
return NumberFormatInfoForThreadUpper;
}
}
private NumberFormatInfo _nfi;
#region Constructors
public StringFormatter(CodeContext/*!*/ context, string str, object data) {
_str = str;
_data = data;
_context = context;
_nfi = nfil;
}
#endregion
#region Public API Surface
public string Format() {
_index = 0;
_buf = new StringBuilder(_str.Length * 2);
int modIndex;
while ((modIndex = _str.IndexOf('%', _index)) != -1) {
_buf.Append(_str, _index, modIndex - _index);
_index = modIndex + 1;
DoFormatCode();
}
_buf.Append(_str, _index, _str.Length - _index);
CheckDataUsed();
return _buf.ToString();
}
#endregion
#region Private APIs
private void DoFormatCode() {
// we already pulled the first %
if (_index == _str.Length)
throw PythonOps.ValueError("incomplete format, expected format character at index {0}", _index);
// Index is placed right after the %.
Debug.Assert(_str[_index - 1] == '%');
_curCh = _str[_index++];
if (_curCh == '%') {
// Escaped '%' character using "%%". Just print it and we are done
_buf.Append('%');
return;
}
string key = ReadMappingKey();
_opts = new FormatSettings();
ReadConversionFlags();
ReadMinimumFieldWidth();
ReadPrecision();
ReadLengthModifier();
// use the key (or lack thereof) to get the value
object value;
if (key == null) {
value = GetData(_dataIndex++);
} else {
value = GetKey(key);
}
_opts.Value = value;
WriteConversion();
}
/// <summary>
/// Read a possible mapping key for %(key)s.
/// </summary>
/// <returns>The key name enclosed between the '%(key)s',
/// or null if there are no paranthesis such as '%s'.</returns>
private string ReadMappingKey() {
// Caller has set _curCh to the character past the %, and
// _index to 2 characters past the original '%'.
Debug.Assert(_curCh == _str[_index - 1]);
Debug.Assert(_str[_index - 2] == '%');
if (_curCh != '(') {
// No parenthesized key.
return null;
}
// CPython supports nested parenthesis (See "S3.6.2:String Formatting Operations").
// Keywords inbetween %(...)s can contain parenthesis.
//
// For example, here are the keys returned for various format strings:
// %(key)s - return 'key'
// %((key))s - return '(key)'
// %()s - return ''
// %((((key))))s - return '(((key)))'
// %((%)s)s - return '(%)s'
// %((%s))s - return (%s)
// %(a(b)c)s - return a(b)c
// %((a)s)s - return (a)s
// %(((a)s))s - return ((a)s)
// Use a counter rule.
int nested = 1; // already passed the 1st '('
int start = _index; // character index after 1st opening '('
int end = start;
while (end < _str.Length) {
if (_str[end] == '(') {
nested++;
} else if (_str[end] == ')') {
nested--;
}
if (nested == 0) {
// Found final matching closing parent
string key = _str.Substring(_index, end - start);
// Update fields
_index = end + 1;
if (_index == _str.Length) {
// This error could happen with a format string like '%((key))'
throw PythonOps.ValueError("incomplete format");
}
_curCh = _str[_index++];
return key;
}
end++;
}
// Error: missing closing ')'.
// This could happen with '%((key)s'
throw PythonOps.ValueError("incomplete format key");
}
private void ReadConversionFlags() {
bool fFoundConversion;
do {
fFoundConversion = true;
switch (_curCh) {
case '#': _opts.AltForm = true; break;
case '-': _opts.LeftAdj = true; _opts.ZeroPad = false; break;
case '0': if (!_opts.LeftAdj) _opts.ZeroPad = true; break;
case '+': _opts.SignChar = true; _opts.Space = false; break;
case ' ': if (!_opts.SignChar) _opts.Space = true; break;
default: fFoundConversion = false; break;
}
if (fFoundConversion) _curCh = _str[_index++];
} while (fFoundConversion);
}
private int ReadNumberOrStar() {
return ReadNumberOrStar(0);
}
private int ReadNumberOrStar(int noValSpecified) {
int res = noValSpecified;
if (_curCh == '*') {
if (!(_data is PythonTuple)) { throw PythonOps.TypeError("* requires a tuple for values"); }
_curCh = _str[_index++];
res = PythonContext.GetContext(_context).ConvertToInt32(GetData(_dataIndex++));
} else {
if (Char.IsDigit(_curCh)) {
res = 0;
while (Char.IsDigit(_curCh) && _index < this._str.Length) {
res = res * 10 + ((int)(_curCh - '0'));
_curCh = _str[_index++];
}
}
}
return res;
}
private void ReadMinimumFieldWidth() {
int fieldWidth = ReadNumberOrStar();;
if (fieldWidth < 0) {
_opts.FieldWidth = fieldWidth * -1;
_opts.LeftAdj = true;
} else {
_opts.FieldWidth = fieldWidth;
}
if (_opts.FieldWidth == Int32.MaxValue) {
throw PythonOps.MemoryError("not enough memory for field width");
}
}
private void ReadPrecision() {
if (_curCh == '.') {
_curCh = _str[_index++];
// possibility: "8.f", "8.0f", or "8.2f"
_opts.Precision = ReadNumberOrStar();
if (_opts.Precision > 116) throw PythonOps.OverflowError("formatted integer is too long (precision too large?)");
} else {
_opts.Precision = UnspecifiedPrecision;
}
}
private void ReadLengthModifier() {
switch (_curCh) {
// ignored, not necessary for Python
case 'h':
case 'l':
case 'L':
_curCh = _str[_index++];
break;
}
}
private void WriteConversion() {
// conversion type (required)
switch (_curCh) {
// signed integer decimal
case 'd':
case 'i': AppendInt(); return;
// unsigned octal
case 'o': AppendOctal(); return;
// unsigned decimal
case 'u': AppendInt(); return;
// unsigned hexadecimal
case 'x': AppendHex(_curCh); return;
case 'X': AppendHex(_curCh); return;
// floating point exponential format
case 'e':
// floating point decimal
case 'f':
// Same as "e" if exponent is less than -4 or more than precision, "f" otherwise.
case 'g': AppendFloat(_curCh); return;
// same as 3 above but uppercase
case 'E':
case 'F':
case 'G': _nfi = nfiu; AppendFloat(_curCh); _nfi = nfil; return;
// single character (int or single char str)
case 'c': AppendChar(); return;
// string (repr() version)
case 'r': AppendRepr(); return;
// string (str() version)
case 's': AppendString(); return;
default:
if (_curCh > 0xff)
throw PythonOps.ValueError("unsupported format character '{0}' (0x{1:X}) at index {2}", '?', (int)_curCh, _index - 1);
else
throw PythonOps.ValueError("unsupported format character '{0}' (0x{1:X}) at index {2}", _curCh, (int)_curCh, _index - 1);
}
}
private object GetData(int index) {
PythonTuple dt = _data as PythonTuple;
if (dt != null) {
if (index < dt.__len__()) {
return dt[index];
}
} else {
if (index == 0) {
return _data;
}
}
throw PythonOps.TypeError("not enough arguments for format string");
}
private object GetKey(string key) {
IDictionary<object, object> map = _data as IDictionary<object, object>;
if (map == null) {
PythonDictionary dict = _data as PythonDictionary;
if (dict == null) {
if (PythonOps.IsMappingType(DefaultContext.Default, _data) == ScriptingRuntimeHelpers.True) {
return PythonOps.GetIndex(_context, _data, key);
}
throw PythonOps.TypeError("format requires a mapping");
}
object res;
if (dict.TryGetValue(key, out res)) return res;
} else {
object res;
if (map.TryGetValue(key, out res)) {
return res;
}
}
throw PythonOps.KeyError(key);
}
private object GetIntegerValue(out bool fPos) {
object val;
int intVal;
if (PythonContext.GetContext(_context).TryConvertToInt32(_opts.Value, out intVal)) {
val = intVal;
fPos = intVal >= 0;
} else {
BigInteger bigInt;
if (Converter.TryConvertToBigInteger(_opts.Value, out bigInt)) {
val = bigInt;
fPos = bigInt >= BigInteger.Zero;
} else {
throw PythonOps.TypeError("int argument required");
}
}
return val;
}
private void AppendChar() {
char val = Converter.ExplicitConvertToChar(_opts.Value);
if (_opts.FieldWidth > 1) {
if (!_opts.LeftAdj) {
_buf.Append(' ', _opts.FieldWidth - 1);
}
_buf.Append(val);
if (_opts.LeftAdj) {
_buf.Append(' ', _opts.FieldWidth - 1);
}
} else {
_buf.Append(val);
}
}
private void CheckDataUsed() {
if (PythonOps.IsMappingType(DefaultContext.Default, _data) == ScriptingRuntimeHelpers.False) {
if ((!(_data is PythonTuple) && _dataIndex != 1) ||
(_data is PythonTuple && _dataIndex != ((PythonTuple)_data).__len__())) {
throw PythonOps.TypeError("not all arguments converted during string formatting");
}
}
}
private void AppendInt() {
bool fPos;
object val = GetIntegerValue(out fPos);
if (_opts.LeftAdj) {
AppendLeftAdj(val, fPos, 'D');
} else if (_opts.Precision > 0) {
// in this case the precision means
// the minimum number of characters
_opts.FieldWidth = (_opts.Space || _opts.SignChar) ?
_opts.Precision + 1 : _opts.Precision;
AppendZeroPad(val, fPos, 'D');
} else if (_opts.ZeroPad) {
AppendZeroPad(val, fPos, 'D');
} else {
AppendNumeric(val, fPos, 'D');
}
}
private static readonly char[] zero = new char[] { '0' };
// Return the new type char to use
// opts.Precision will be set to the number of digits to display after the decimal point
private char AdjustForG(char type, double v) {
if (type != 'G' && type != 'g')
return type;
if (Double.IsNaN(v) || Double.IsInfinity(v))
return type;
double absV = Math.Abs(v);
if (_opts.Precision == 0) {
_opts.Precision = 1;
}
if ((v != 0.0) && // 0.0 should not be displayed as scientific notation
absV < 1e-4 || // Values less than 0.0001 will need scientific notation
absV >= Math.Pow(10, _opts.Precision)) { // Values bigger than 1e<precision> will need scientific notation
// One digit is displayed before the decimal point. Hence, we need one fewer than the precision after the decimal point
int fractionDigitsRequired = (_opts.Precision - 1);
string expForm = absV.ToString("E" + fractionDigitsRequired, CultureInfo.InvariantCulture);
string mantissa = expForm.Substring(0, expForm.IndexOf('E')).TrimEnd(zero);
if (mantissa.Length == 1) {
_opts.Precision = 0;
} else {
// We do -2 to ignore the digit before the decimal point and the decimal point itself
Debug.Assert(mantissa[1] == '.');
_opts.Precision = mantissa.Length - 2;
}
type = (type == 'G') ? 'E' : 'e';
} else {
// "0.000ddddd" is allowed when the precision is 5. The 3 leading zeros are not counted
int numberDecimalDigits = _opts.Precision;
if (absV < 1e-3) numberDecimalDigits += 3;
else if (absV < 1e-2) numberDecimalDigits += 2;
else if (absV < 1e-1) numberDecimalDigits += 1;
string fixedPointForm = absV.ToString("F" + numberDecimalDigits, CultureInfo.InvariantCulture).TrimEnd(zero);
bool convertType = true;
if (numberDecimalDigits > 15) {
// System.Double(0.33333333333333331).ToString("F17") == "0.33333333333333300"
string fixedPointFormG = absV.ToString("G" + numberDecimalDigits, CultureInfo.InvariantCulture).TrimEnd(zero);
if (fixedPointFormG.Length > fixedPointForm.Length) {
fixedPointForm = fixedPointFormG;
convertType = false;
}
}
string fraction = fixedPointForm.Substring(fixedPointForm.IndexOf('.') + 1);
if (absV < 1.0) {
_opts.Precision = fraction.Length;
} else {
int digitsBeforeDecimalPoint = 1 + (int)Math.Log10(absV);
_opts.Precision = Math.Min(_opts.Precision - digitsBeforeDecimalPoint, fraction.Length);
}
if (convertType) {
type = (type == 'G') ? 'F' : 'f';
}
}
return type;
}
private void AppendFloat(char type) {
double v;
if (!Converter.TryConvertToDouble(_opts.Value, out v))
throw PythonOps.TypeError("float argument required");
// scientific exponential format
Debug.Assert(type == 'E' || type == 'e' ||
// floating point decimal
type == 'F' || type == 'f' ||
// Same as "e" if exponent is less than -4 or more than precision, "f" otherwise.
type == 'G' || type == 'g');
bool forceDot = false;
// update our precision first...
if (_opts.Precision != UnspecifiedPrecision) {
if (_opts.Precision == 0 && _opts.AltForm) forceDot = true;
if (_opts.Precision > 50)
_opts.Precision = 50;
} else {
// alternate form (#) specified, set precision to zero...
if (_opts.AltForm) {
_opts.Precision = 0;
forceDot = true;
} else _opts.Precision = 6;
}
type = AdjustForG(type, v);
_nfi.NumberDecimalDigits = _opts.Precision;
// then append
if (_opts.LeftAdj) {
AppendLeftAdj(v, DoubleOps.Sign(v) >= 0, type);
} else if (_opts.ZeroPad) {
AppendZeroPadFloat(v, type);
} else {
AppendNumeric(v, DoubleOps.Sign(v) >= 0, type);
}
if (DoubleOps.Sign(v) < 0 && v > -1 && _buf[0] != '-') {
FixupFloatMinus();
}
if (forceDot) {
FixupAltFormDot(v);
}
}
private void FixupAltFormDot(double v) {
if (!double.IsInfinity(v) && !double.IsNaN(v)) {
_buf.Append('.');
}
if (_opts.FieldWidth != 0) {
// try and remove the extra character we're adding.
for (int i = 0; i < _buf.Length; i++) {
if (_buf[i] == ' ' || _buf[i] == '0') {
_buf.Remove(i, 1);
break;
} else if (_buf[i] != '-' && _buf[i] != '+') {
break;
}
}
}
}
private void FixupFloatMinus() {
// Python always appends a - even if precision is 0 and the value would appear to be zero.
bool fNeedMinus = true;
for (int i = 0; i < _buf.Length; i++) {
if (_buf[i] != '.' && _buf[i] != '0' && _buf[i] != ' ') {
fNeedMinus = false;
break;
}
}
if (fNeedMinus) {
if (_opts.FieldWidth != 0) {
// trim us back down to the correct field width...
if (_buf[_buf.Length - 1] == ' ') {
_buf.Insert(0, "-");
_buf.Remove(_buf.Length - 1, 1);
} else {
int index = 0;
while (_buf[index] == ' ') index++;
if (index > 0) index--;
_buf[index] = '-';
}
} else {
_buf.Insert(0, "-");
}
}
}
private void AppendZeroPad(object val, bool fPos, char format) {
if (fPos && (_opts.SignChar || _opts.Space)) {
// produce [' '|'+']0000digits
// first get 0 padded number to field width
string res = String.Format(_nfi, "{0:" + format + _opts.FieldWidth.ToString() + "}", val);
char signOrSpace = _opts.SignChar ? '+' : ' ';
// then if we ended up with a leading zero replace it, otherwise
// append the space / + to the front.
if (res[0] == '0' && res.Length > 1) {
res = signOrSpace + res.Substring(1);
} else {
res = signOrSpace + res;
}
_buf.Append(res);
} else {
string res = String.Format(_nfi, "{0:" + format + _opts.FieldWidth.ToString() + "}", val);
// Difference:
// System.String.Format("{0:D3}", -1) '-001'
// "%03d" % -1 '-01'
if (res[0] == '-') {
// negative
_buf.Append("-");
if (res[1] != '0') {
_buf.Append(res.Substring(1));
} else {
_buf.Append(res.Substring(2));
}
} else {
// positive
_buf.Append(res);
}
}
}
private void AppendZeroPadFloat(double val, char format) {
if (val >= 0) {
StringBuilder res = new StringBuilder(val.ToString(format.ToString(), _nfi));
if (res.Length < _opts.FieldWidth) {
res.Insert(0, new string('0', _opts.FieldWidth - res.Length));
}
if (_opts.SignChar || _opts.Space) {
char signOrSpace = _opts.SignChar ? '+' : ' ';
// then if we ended up with a leading zero replace it, otherwise
// append the space / + to the front.
if (res[0] == '0' && res[1] != '.') {
res[0] = signOrSpace;
} else {
res.Insert(0, signOrSpace.ToString());
}
}
_buf.Append(res);
} else {
StringBuilder res = new StringBuilder(val.ToString(format.ToString(), _nfi));
if (res.Length < _opts.FieldWidth) {
res.Insert(1, new string('0', _opts.FieldWidth - res.Length));
}
_buf.Append(res);
}
}
private void AppendNumeric(object val, bool fPos, char format) {
if (format == 'e' || format == 'E') {
AppendNumericExp(val, fPos, format);
} else {
// f, F, g, D
AppendNumericDecimal(val, fPos, format);
}
}
private void AppendNumericExp(object val, bool fPos, char format) {
Debug.Assert(_opts.Precision != UnspecifiedPrecision);
var forceMinus = false;
double doubleVal = (double)val;
if (IsNegativeZero(doubleVal)) {
forceMinus = true;
}
if (fPos && (_opts.SignChar || _opts.Space)) {
string strval = (_opts.SignChar ? "+" : " ") + String.Format(_nfi, "{0:" + format + _opts.Precision + "}", val);
strval = adjustExponent(strval);
if (strval.Length < _opts.FieldWidth) {
_buf.Append(' ', _opts.FieldWidth - strval.Length);
}
if (forceMinus) {
_buf.Append('-');
}
_buf.Append(strval);
} else if (_opts.Precision < 100) {
//CLR formatting has a maximum precision of 100.
string num = String.Format(_nfi, "{0," + _opts.FieldWidth + ":" + format + _opts.Precision + "}", val);
num = adjustExponent(num);
if (num.Length < _opts.FieldWidth) {
_buf.Append(' ', _opts.FieldWidth - num.Length);
}
if (forceMinus)
_buf.Append('-');
_buf.Append(num);
} else {
AppendNumericCommon(val, format);
}
}
private void AppendNumericDecimal(object val, bool fPos, char format) {
if (fPos && (_opts.SignChar || _opts.Space)) {
string strval = (_opts.SignChar ? "+" : " ") + String.Format(_nfi, "{0:" + format + "}", val);
if (strval.Length < _opts.FieldWidth) {
_buf.Append(' ', _opts.FieldWidth - strval.Length);
}
_buf.Append(strval);
} else if (_opts.Precision == UnspecifiedPrecision) {
_buf.AppendFormat(_nfi, "{0," + _opts.FieldWidth + ":" + format + "}", val);
} else if (_opts.Precision < 100) {
//CLR formatting has a maximum precision of 100.
_buf.Append(String.Format(_nfi, "{0," + _opts.FieldWidth + ":" + format + _opts.Precision + "}", val));
} else {
AppendNumericCommon(val, format);
}
// If AdjustForG() sets opts.Precision == 0, it means that no significant digits should be displayed after
// the decimal point. ie. 123.4 should be displayed as "123", not "123.4". However, we might still need a
// decorative ".0". ie. to display "123.0"
if (_TrailingZeroAfterWholeFloat && (format == 'f' || format == 'F') && _opts.Precision == 0)
_buf.Append(".0");
}
private void AppendNumericCommon(object val, char format) {
StringBuilder res = new StringBuilder();
res.AppendFormat("{0:" + format + "}", val);
if (res.Length < _opts.Precision) {
res.Insert(0, new String('0', _opts.Precision - res.Length));
}
if (res.Length < _opts.FieldWidth) {
res.Insert(0, new String(' ', _opts.FieldWidth - res.Length));
}
_buf.Append(res.ToString());
}
// A strange string formatting bug requires that we use Standard Numeric Format and
// not Custom Numeric Format. Standard Numeric Format produces always a 3 digit exponent
// which needs to be taken care off.
// Example: 9.3126672485384569e+23, precision=16
// format string "e16" ==> "9.3126672485384569e+023", but we want "e+23", not "e+023"
// format string "0.0000000000000000e+00" ==> "9.3126672485384600e+23", which is a precision error
// so, we have to format with "e16" and strip the zero manually
private string adjustExponent(string val) {
if (val[val.Length - 3] == '0') {
return val.Substring(0, val.Length - 3) + val.Substring(val.Length - 2, 2);
} else {
return val;
}
}
private void AppendLeftAdj(object val, bool fPos, char type) {
var format = (type == 'e' || type == 'E') ?
"{0:" + type + _opts.Precision + "}" :
"{0:" + type + "}";
var str = adjustExponent(String.Format(_nfi, format, val));
if (fPos) {
if (_opts.SignChar) str = '+' + str;
else if (_opts.Space) str = ' ' + str;
}
_buf.Append(str);
if (str.Length < _opts.FieldWidth) _buf.Append(' ', _opts.FieldWidth - str.Length);
}
private static bool NeedsAltForm(char format, char last) {
if (format == 'X' || format == 'x') return true;
if (last == '0') return false;
return true;
}
private static string GetAltFormPrefixForRadix(char format, int radix) {
switch (radix) {
case 8: return "0";
case 16: return format + "0";
}
return "";
}
/// <summary>
/// AppendBase appends an integer at the specified radix doing all the
/// special forms for Python. We have a copy and paste version of this
/// for BigInteger below that should be kept in sync.
/// </summary>
private void AppendBase(char format, int radix) {
bool fPos;
object intVal = GetIntegerValue(out fPos);
if (intVal is BigInteger) {
AppendBaseBigInt((BigInteger)intVal, format, radix);
return;
}
int origVal = (int)intVal;
int val = origVal;
if (val < 0) {
val *= -1;
// if negative number, the leading space has no impact
_opts.Space = false;
}
// we build up the number backwards inside a string builder,
// and after we've finished building this up we append the
// string to our output buffer backwards.
// convert value to string
StringBuilder str = new StringBuilder();
if (val == 0) str.Append('0');
while (val != 0) {
int digit = val % radix;
if (digit < 10) str.Append((char)((digit) + '0'));
else if (Char.IsLower(format)) str.Append((char)((digit - 10) + 'a'));
else str.Append((char)((digit - 10) + 'A'));
val /= radix;
}
// pad out for additional precision
if (str.Length < _opts.Precision) {
int len = _opts.Precision - str.Length;
str.Append('0', len);
}
// pad result to minimum field width
if (_opts.FieldWidth != 0) {
int signLen = (origVal < 0 || _opts.SignChar) ? 1 : 0;
int spaceLen = _opts.Space ? 1 : 0;
int len = _opts.FieldWidth - (str.Length + signLen + spaceLen);
if (len > 0) {
// we account for the size of the alternate form, if we'll end up adding it.
if (_opts.AltForm && NeedsAltForm(format, (!_opts.LeftAdj && _opts.ZeroPad) ? '0' : str[str.Length - 1])) {
len -= GetAltFormPrefixForRadix(format, radix).Length;
}
if (len > 0) {
// and finally append the right form
if (_opts.LeftAdj) {
str.Insert(0, " ", len);
} else {
if (_opts.ZeroPad) {
str.Append('0', len);
} else {
_buf.Append(' ', len);
}
}
}
}
}
// append the alternate form
if (_opts.AltForm && NeedsAltForm(format, str[str.Length - 1]))
str.Append(GetAltFormPrefixForRadix(format, radix));
// add any sign if necessary
if (origVal < 0) {
_buf.Append('-');
} else if (_opts.SignChar) {
_buf.Append('+');
} else if (_opts.Space) {
_buf.Append(' ');
}
// append the final value
for (int i = str.Length - 1; i >= 0; i--) {
_buf.Append(str[i]);
}
}
/// <summary>
/// BigInteger version of AppendBase. Should be kept in sync w/ AppendBase
/// </summary>
private void AppendBaseBigInt(BigInteger origVal, char format, int radix) {
BigInteger val = origVal;
if (val < 0) val *= -1;
// convert value to octal
StringBuilder str = new StringBuilder();
// use .NETs faster conversion if we can
if (radix == 16) {
AppendNumberReversed(str, Char.IsLower(format) ? val.ToString("x") : val.ToString("X"));
} else if (radix == 10) {
AppendNumberReversed(str, val.ToString());
} else {
if (val == 0) str.Append('0');
while (val != 0) {
int digit = (int)(val % radix);
if (digit < 10) str.Append((char)((digit) + '0'));
else if (Char.IsLower(format)) str.Append((char)((digit - 10) + 'a'));
else str.Append((char)((digit - 10) + 'A'));
val /= radix;
}
}
// pad out for additional precision
if (str.Length < _opts.Precision) {
int len = _opts.Precision - str.Length;
str.Append('0', len);
}
// pad result to minimum field width
if (_opts.FieldWidth != 0) {
int signLen = (origVal < 0 || _opts.SignChar) ? 1 : 0;
int len = _opts.FieldWidth - (str.Length + signLen);
if (len > 0) {
// we account for the size of the alternate form, if we'll end up adding it.
if (_opts.AltForm && NeedsAltForm(format, (!_opts.LeftAdj && _opts.ZeroPad) ? '0' : str[str.Length - 1])) {
len -= GetAltFormPrefixForRadix(format, radix).Length;
}
if (len > 0) {
// and finally append the right form
if (_opts.LeftAdj) {
str.Insert(0, " ", len);
} else {
if (_opts.ZeroPad) {
str.Append('0', len);
} else {
_buf.Append(' ', len);
}
}
}
}
}
// append the alternate form
if (_opts.AltForm && NeedsAltForm(format, str[str.Length - 1]))
str.Append(GetAltFormPrefixForRadix(format, radix));
// add any sign if necessary
if (origVal < 0) {
_buf.Append('-');
} else if (_opts.SignChar) {
_buf.Append('+');
} else if (_opts.Space) {
_buf.Append(' ');
}
// append the final value
for (int i = str.Length - 1; i >= 0; i--) {
_buf.Append(str[i]);
}
}
private static void AppendNumberReversed(StringBuilder str, string res) {
int start = 0;
while (start < (res.Length - 1) && res[start] == '0') {
start++;
}
for (int i = res.Length - 1; i >= start; i--) {
str.Append(res[i]);
}
}
private void AppendHex(char format) {
AppendBase(format, 16);
}
private void AppendOctal() {
AppendBase('o', 8);
}
private void AppendString() {
AppendString(PythonOps.ToString(_context, _opts.Value));
}
private void AppendRepr() {
AppendString(PythonOps.Repr(_context, _opts.Value));
}
private void AppendString(string s) {
if (_opts.Precision != UnspecifiedPrecision && s.Length > _opts.Precision) s = s.Substring(0, _opts.Precision);
if (!_opts.LeftAdj && _opts.FieldWidth > s.Length) {
_buf.Append(' ', _opts.FieldWidth - s.Length);
}
_buf.Append(s);
if (_opts.LeftAdj && _opts.FieldWidth > s.Length) {
_buf.Append(' ', _opts.FieldWidth - s.Length);
}
}
private static readonly long NegativeZeroBits = BitConverter.DoubleToInt64Bits(-0.0);
internal static bool IsNegativeZero(double x) {
// -0.0 == 0.0 is True, so detecting -0.0 uses memory representation
return BitConverter.DoubleToInt64Bits(x) == NegativeZeroBits;
}
#endregion
#region Private data structures
// The conversion specifier format is as follows:
// % (mappingKey) conversionFlags fieldWidth . precision lengthModifier conversionType
// where:
// mappingKey - value to be formatted
// conversionFlags - # 0 - + <space>
// lengthModifier - h, l, and L. Ignored by Python
// conversionType - d i o u x X e E f F g G c r s %
// Ex:
// %(varName)#4o - Display "varName" as octal and prepend with leading 0 if necessary, for a total of atleast 4 characters
[Flags]
internal enum FormatOptions {
ZeroPad = 0x01, // Use zero-padding to fit FieldWidth
LeftAdj = 0x02, // Use left-adjustment to fit FieldWidth. Overrides ZeroPad
AltForm = 0x04, // Add a leading 0 if necessary for octal, or add a leading 0x or 0X for hex
Space = 0x08, // Leave a white-space
SignChar = 0x10 // Force usage of a sign char even if the value is positive
}
internal struct FormatSettings {
#region FormatOptions property accessors
public bool ZeroPad {
get {
return ((Options & FormatOptions.ZeroPad) != 0);
}
set {
if (value) {
Options |= FormatOptions.ZeroPad;
} else {
Options &= (~FormatOptions.ZeroPad);
}
}
}
public bool LeftAdj {
get {
return ((Options & FormatOptions.LeftAdj) != 0);
}
set {
if (value) {
Options |= FormatOptions.LeftAdj;
} else {
Options &= (~FormatOptions.LeftAdj);
}
}
}
public bool AltForm {
get {
return ((Options & FormatOptions.AltForm) != 0);
}
set {
if (value) {
Options |= FormatOptions.AltForm;
} else {
Options &= (~FormatOptions.AltForm);
}
}
}
public bool Space {
get {
return ((Options & FormatOptions.Space) != 0);
}
set {
if (value) {
Options |= FormatOptions.Space;
} else {
Options &= (~FormatOptions.Space);
}
}
}
public bool SignChar {
get {
return ((Options & FormatOptions.SignChar) != 0);
}
set {
if (value) {
Options |= FormatOptions.SignChar;
} else {
Options &= (~FormatOptions.SignChar);
}
}
}
#endregion
internal FormatOptions Options;
// Minimum number of characters that the entire formatted string should occupy.
// Smaller results will be left-padded with white-space or zeros depending on Options
internal int FieldWidth;
// Number of significant digits to display, before and after the decimal point.
// For floats, it gets adjusted to the number of digits to display after the decimal point since
// that is the value required by StringBuilder.AppendFormat.
// For clarity, we should break this up into the two values - the precision specified by the
// format string, and the value to be passed in to StringBuilder.AppendFormat
internal int Precision;
internal object Value;
}
#endregion
}
}
| |
// ---------------------------------------------------------------------------
// <copyright file="JsonWriter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ---------------------------------------------------------------------------
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
/// <summary>
/// JSON text writer
/// </summary>
internal class JsonWriter : TextWriter
{
private const string Indentation = " ";
#region Member variables
private Stream outStream;
private bool shouldCloseStream;
private bool prettyPrint;
private bool writingStringValue = false;
private byte[] smallBuffer = new byte[20];
private char[] charBuffer = new char[4];
private Queue<char> surrogateCharBuffer = new Queue<char>(4);
private Stack<char> closures = new Stack<char>();
private Stack<bool> closureHasMembers = new Stack<bool>();
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="JsonWriter"/> class.
/// </summary>
/// <param name="outStream">The out stream.</param>
/// <param name="prettyPrint">if set to <c>true</c> [pretty print].</param>
public JsonWriter(Stream outStream, bool prettyPrint)
{
this.outStream = outStream;
this.prettyPrint = prettyPrint;
this.shouldCloseStream = false;
}
#endregion
#region Dispose methods
/// <summary>
/// Releases the unmanaged resources used by the <see cref="T:System.IO.TextWriter"/> and optionally releases the managed resources.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
protected override void Dispose(bool disposing)
{
if (this.shouldCloseStream)
{
this.outStream.Flush();
this.outStream.Dispose();
}
base.Dispose(disposing);
}
#endregion
#region Public methods
/// <summary>
/// Writes a character to the text stream.
/// </summary>
/// <param name="value">The character to write to the text stream.</param>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="T:System.IO.TextWriter"/> is closed.
/// </exception>
/// <exception cref="T:System.IO.IOException">
/// An I/O error occurs.
/// </exception>
public override void Write(char value)
{
if (this.writingStringValue)
{
// Handle Surrogates and Supplementary Characters
// Refer to: http://msdn.microsoft.com/en-us/library/windows/desktop/dd374069(v=vs.85).aspx
if (char.IsHighSurrogate(value))
{
this.surrogateCharBuffer.Enqueue(value);
if (this.surrogateCharBuffer.Count == 4)
{
Debug.Assert(false, "The number of surrogate characters for a single real character should be less than 4.");
// Still write characters out
this.WriteSurrogateChar();
}
}
else if (char.IsLowSurrogate(value))
{
this.surrogateCharBuffer.Enqueue(value);
this.WriteSurrogateChar();
}
else
{
// Non surrogate characters
if (this.surrogateCharBuffer.Count > 0)
{
Debug.Assert(false, "A low surrogate character is expected.");
this.WriteSurrogateChar();
}
if (value == '\r')
{
this.WriteInternal(@"\r");
}
else if (value == '\n')
{
this.WriteInternal(@"\n");
}
else if (value == '\t')
{
this.WriteInternal(@"\t");
}
else
{
this.WritePrintableChar(value);
}
}
}
else
{
this.WritePrintableChar(value);
}
}
/// <summary>
/// Pushes object closure.
/// </summary>
public void PushObjectClosure()
{
this.AddingValue();
this.closures.Push('}');
this.closureHasMembers.Push(false);
this.WriteInternal('{');
this.WriteIndentation();
}
/// <summary>
/// Pushes array closure.
/// </summary>
public void PushArrayClosure()
{
this.AddingValue();
this.closures.Push(']');
this.closureHasMembers.Push(false);
this.WriteInternal('[');
this.WriteIndentation();
}
/// <summary>
/// Pops closure.
/// </summary>
public void PopClosure()
{
var popChar = this.closures.Pop();
this.closureHasMembers.Pop();
this.WriteIndentation();
this.WriteInternal(popChar);
}
/// <summary>
/// Writes quote.
/// </summary>
public void WriteQuote()
{
this.WriteInternal('"');
}
/// <summary>
/// Writes key.
/// </summary>
/// <param name="key">The key.</param>
public void WriteKey(string key)
{
if (this.closureHasMembers.Peek())
{
this.WriteInternal(',');
this.WriteIndentation();
}
this.WriteQuote();
this.Write(key);
this.WriteQuote();
if (this.prettyPrint)
{
this.Write(" : ");
}
else
{
this.WriteInternal(':');
}
}
/// <summary>
/// Writes value.
/// </summary>
/// <param name="value">The value.</param>
public void WriteValue(string value)
{
this.AddingValue();
this.WriteQuote();
this.writingStringValue = true;
this.Write(value);
this.writingStringValue = false;
this.WriteQuote();
}
/// <summary>
/// Writes bool value.
/// </summary>
/// <param name="value">if set to <c>true</c> [value].</param>
public void WriteValue(bool value)
{
this.AddingValue();
this.Write(value.ToString().ToLowerInvariant());
}
/// <summary>
/// Writes long value.
/// </summary>
/// <param name="value">The value.</param>
public void WriteValue(long value)
{
this.AddingValue();
this.Write(value);
}
/// <summary>
/// Writes int value.
/// </summary>
/// <param name="value">The value.</param>
public void WriteValue(int value)
{
this.AddingValue();
this.Write(value);
}
/// <summary>
/// Writes an enum value.
/// </summary>
/// <param name="value">The value.</param>
public void WriteValue(Enum value)
{
this.WriteValue(EwsUtilities.SerializeEnum(value));
}
/// <summary>
/// Writes DateTime value.
/// </summary>
/// <param name="value">The value.</param>
public void WriteValue(DateTime value)
{
this.WriteValue(EwsUtilities.DateTimeToXSDateTime(value));
}
/// <summary>
/// Writes float value.
/// </summary>
/// <param name="value">The value.</param>
public void WriteValue(float value)
{
this.AddingValue();
this.Write(value);
}
/// <summary>
/// Writes double value.
/// </summary>
/// <param name="value">The value.</param>
public void WriteValue(double value)
{
this.AddingValue();
this.Write(value);
}
/// <summary>
/// Writes null value.
/// </summary>
public void WriteNullValue()
{
this.AddingValue();
this.Write("null");
}
#endregion
#region Private methods
/// <summary>
/// Write printable char.
/// </summary>
/// <param name="value">The value.</param>
private void WritePrintableChar(char value)
{
if (value == '"' || value == '\\')
{
this.WriteInternal('\\');
}
this.WriteInternal(value);
}
/// <summary>
/// Internal writer.
/// </summary>
/// <param name="value">The value.</param>
private void WriteInternal(char value)
{
this.charBuffer[0] = value;
int bytesLength = this.Encoding.GetBytes(
this.charBuffer,
0,
1,
this.smallBuffer,
0);
this.outStream.Write(smallBuffer, 0, bytesLength);
}
/// <summary>
/// Internal writer.
/// </summary>
/// <param name="value">The value.</param>
private void WriteInternal(string value)
{
value.CopyTo(0, this.charBuffer, 0, value.Length);
int bytesLength = this.Encoding.GetBytes(
this.charBuffer,
0,
value.Length,
this.smallBuffer,
0);
this.outStream.Write(smallBuffer, 0, bytesLength);
}
/// <summary>
/// Surrogate character writer.
/// </summary>
private void WriteSurrogateChar()
{
this.surrogateCharBuffer.CopyTo(this.charBuffer, 0);
int bytesLength = this.Encoding.GetBytes(
this.charBuffer,
0,
this.surrogateCharBuffer.Count,
this.smallBuffer,
0);
this.outStream.Write(smallBuffer, 0, bytesLength);
this.surrogateCharBuffer.Clear();
}
/// <summary>
/// Writes indentation.
/// </summary>
private void WriteIndentation()
{
if (this.prettyPrint)
{
this.WriteInternal('\r');
this.WriteInternal('\n');
for (int i = this.closures.Count - 1; i >= 0; i--)
{
this.Write(JsonWriter.Indentation);
}
}
}
/// <summary>
/// Adding a value.
/// </summary>
private void AddingValue()
{
if (this.closures.Count > 0)
{
if (this.closures.Peek() == ']' &&
this.closureHasMembers.Peek())
{
this.WriteInternal(',');
this.WriteIndentation();
}
if (!this.closureHasMembers.Peek())
{
this.closureHasMembers.Pop();
this.closureHasMembers.Push(true);
}
}
}
#endregion
#region Public properties
/// <summary>
/// When overridden in a derived class, returns the <see cref="T:System.Text.Encoding"/> in which the output is written.
/// </summary>
/// <value></value>
/// <returns>
/// The Encoding in which the output is written.
/// </returns>
public override Encoding Encoding
{
get { return Encoding.UTF8; }
}
/// <summary>
/// Gets or sets a value indicating whether input stream should be closed when reader is closed.
/// </summary>
public bool ShouldCloseStream
{
get
{
return this.shouldCloseStream;
}
set
{
this.shouldCloseStream = value;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
using WebApplication.Models;
using WebApplication.Models.AccountViewModels;
using WebApplication.Services;
namespace WebApplication.Controllers
{
[Authorize]
public class AccountController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
private readonly ILogger _logger;
public AccountController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ISmsSender smsSender,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
_logger = loggerFactory.CreateLogger<AccountController>();
}
//
// GET: /Account/Login
[HttpGet]
[AllowAnonymous]
public IActionResult Login(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation(1, "User logged in.");
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning(2, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/Register
[HttpGet]
[AllowAnonymous]
public IActionResult Register(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.UserName, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
//var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
//var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
//await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
// $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User created a new account with password.");
return RedirectToLocal(returnUrl);
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LogOff()
{
await _signInManager.SignOutAsync();
_logger.LogInformation(4, "User logged out.");
return RedirectToAction(nameof(HomeController.Index), "Home");
}
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public IActionResult ExternalLogin(string provider, string returnUrl = null)
{
// Request a redirect to the external login provider.
var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return Challenge(properties, provider);
}
//
// GET: /Account/ExternalLoginCallback
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
if (remoteError != null)
{
ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}");
return View(nameof(Login));
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return RedirectToAction(nameof(Login));
}
// Sign in the user with this external login provider if the user already has a login.
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
if (result.Succeeded)
{
_logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider);
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl });
}
if (result.IsLockedOut)
{
return View("Lockout");
}
else
{
// If the user does not have an account, then ask the user to create an account.
ViewData["ReturnUrl"] = returnUrl;
ViewData["LoginProvider"] = info.LoginProvider;
var email = info.Principal.FindFirstValue(ClaimTypes.Email);
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email });
}
}
//
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null)
{
if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user);
if (result.Succeeded)
{
result = await _userManager.AddLoginAsync(user, info);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
return RedirectToLocal(returnUrl);
}
}
AddErrors(result);
}
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
// GET: /Account/ConfirmEmail
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return View("Error");
}
var result = await _userManager.ConfirmEmailAsync(user, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
//
// GET: /Account/ForgotPassword
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPassword()
{
return View();
}
//
// POST: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await _userManager.FindByNameAsync(model.Email);
if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
//var code = await _userManager.GeneratePasswordResetTokenAsync(user);
//var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
//await _emailSender.SendEmailAsync(model.Email, "Reset Password",
// $"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>");
//return View("ForgotPasswordConfirmation");
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ForgotPasswordConfirmation
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPasswordConfirmation()
{
return View();
}
//
// GET: /Account/ResetPassword
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPassword(string code = null)
{
return code == null ? View("Error") : View();
}
//
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _userManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account");
}
var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account");
}
AddErrors(result);
return View();
}
//
// GET: /Account/ResetPasswordConfirmation
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPasswordConfirmation()
{
return View();
}
//
// GET: /Account/SendCode
[HttpGet]
[AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false)
{
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/SendCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SendCode(SendCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View();
}
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
// Generate the token and send it
var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider);
if (string.IsNullOrWhiteSpace(code))
{
return View("Error");
}
var message = "Your security code is: " + code;
if (model.SelectedProvider == "Email")
{
await _emailSender.SendEmailAsync(await _userManager.GetEmailAsync(user), "Security Code", message);
}
else if (model.SelectedProvider == "Phone")
{
await _smsSender.SendSmsAsync(await _userManager.GetPhoneNumberAsync(user), message);
}
return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
//
// GET: /Account/VerifyCode
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null)
{
// Require that the user has already logged in via username/password or external login
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/VerifyCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyCode(VerifyCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// The following code protects for brute force attacks against the two factor codes.
// If a user enters incorrect codes for a specified amount of time then the user account
// will be locked out for a specified amount of time.
var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser);
if (result.Succeeded)
{
return RedirectToLocal(model.ReturnUrl);
}
if (result.IsLockedOut)
{
_logger.LogWarning(7, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid code.");
return View(model);
}
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
private Task<ApplicationUser> GetCurrentUserAsync()
{
return _userManager.GetUserAsync(HttpContext.User);
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction(nameof(HomeController.Index), "Home");
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Diagnostics;
namespace Microsoft.SqlServer.Server
{
// Utilities for manipulating smi-related metadata.
//
// Since this class is built on top of SMI, SMI should not have a dependency on this class
//
// These are all based off of knowing the clr type of the value
// as an ExtendedClrTypeCode enum for rapid access.
internal class MetaDataUtilsSmi
{
internal const SqlDbType InvalidSqlDbType = (SqlDbType)(-1);
internal const long InvalidMaxLength = -2;
// Standard type inference map to get SqlDbType when all you know is the value's type (typecode)
// This map's index is off by one (add one to typecode locate correct entry) in order
// to support ExtendedSqlDbType.Invalid
// This array is meant to be accessed from InferSqlDbTypeFromTypeCode.
private static readonly SqlDbType[] s_extendedTypeCodeToSqlDbTypeMap = {
InvalidSqlDbType, // Invalid extended type code
SqlDbType.Bit, // System.Boolean
SqlDbType.TinyInt, // System.Byte
SqlDbType.NVarChar, // System.Char
SqlDbType.DateTime, // System.DateTime
InvalidSqlDbType, // System.DBNull doesn't have an inferable SqlDbType
SqlDbType.Decimal, // System.Decimal
SqlDbType.Float, // System.Double
InvalidSqlDbType, // null reference doesn't have an inferable SqlDbType
SqlDbType.SmallInt, // System.Int16
SqlDbType.Int, // System.Int32
SqlDbType.BigInt, // System.Int64
InvalidSqlDbType, // System.SByte doesn't have an inferable SqlDbType
SqlDbType.Real, // System.Single
SqlDbType.NVarChar, // System.String
InvalidSqlDbType, // System.UInt16 doesn't have an inferable SqlDbType
InvalidSqlDbType, // System.UInt32 doesn't have an inferable SqlDbType
InvalidSqlDbType, // System.UInt64 doesn't have an inferable SqlDbType
InvalidSqlDbType, // System.Object doesn't have an inferable SqlDbType
SqlDbType.VarBinary, // System.ByteArray
SqlDbType.NVarChar, // System.CharArray
SqlDbType.UniqueIdentifier, // System.Guid
SqlDbType.VarBinary, // System.Data.SqlTypes.SqlBinary
SqlDbType.Bit, // System.Data.SqlTypes.SqlBoolean
SqlDbType.TinyInt, // System.Data.SqlTypes.SqlByte
SqlDbType.DateTime, // System.Data.SqlTypes.SqlDateTime
SqlDbType.Float, // System.Data.SqlTypes.SqlDouble
SqlDbType.UniqueIdentifier, // System.Data.SqlTypes.SqlGuid
SqlDbType.SmallInt, // System.Data.SqlTypes.SqlInt16
SqlDbType.Int, // System.Data.SqlTypes.SqlInt32
SqlDbType.BigInt, // System.Data.SqlTypes.SqlInt64
SqlDbType.Money, // System.Data.SqlTypes.SqlMoney
SqlDbType.Decimal, // System.Data.SqlTypes.SqlDecimal
SqlDbType.Real, // System.Data.SqlTypes.SqlSingle
SqlDbType.NVarChar, // System.Data.SqlTypes.SqlString
SqlDbType.NVarChar, // System.Data.SqlTypes.SqlChars
SqlDbType.VarBinary, // System.Data.SqlTypes.SqlBytes
SqlDbType.Xml, // System.Data.SqlTypes.SqlXml
SqlDbType.Structured, // System.Collections.IEnumerable, used for TVPs it must return IDataRecord
SqlDbType.Structured, // System.Collections.Generic.IEnumerable<Microsoft.SqlServer.Server.SqlDataRecord>
SqlDbType.Time, // System.TimeSpan
SqlDbType.DateTimeOffset, // System.DateTimeOffset
};
// Dictionary to map from clr type object to ExtendedClrTypeCodeMap enum.
// This dictionary should only be accessed from DetermineExtendedTypeCode and class ctor for setup.
private static readonly Dictionary<Type, ExtendedClrTypeCode> s_typeToExtendedTypeCodeMap = CreateTypeToExtendedTypeCodeMap();
private static Dictionary<Type, ExtendedClrTypeCode> CreateTypeToExtendedTypeCodeMap()
{
int Count = 42;
// Keep this initialization list in the same order as ExtendedClrTypeCode for ease in validating!
var dictionary = new Dictionary<Type, ExtendedClrTypeCode>(Count)
{
{ typeof(bool), ExtendedClrTypeCode.Boolean },
{ typeof(byte), ExtendedClrTypeCode.Byte },
{ typeof(char), ExtendedClrTypeCode.Char },
{ typeof(DateTime), ExtendedClrTypeCode.DateTime },
{ typeof(DBNull), ExtendedClrTypeCode.DBNull },
{ typeof(decimal), ExtendedClrTypeCode.Decimal },
{ typeof(double), ExtendedClrTypeCode.Double },
// lookup code will handle special-case null-ref, omitting the addition of ExtendedTypeCode.Empty
{ typeof(short), ExtendedClrTypeCode.Int16 },
{ typeof(int), ExtendedClrTypeCode.Int32 },
{ typeof(long), ExtendedClrTypeCode.Int64 },
{ typeof(sbyte), ExtendedClrTypeCode.SByte },
{ typeof(float), ExtendedClrTypeCode.Single },
{ typeof(string), ExtendedClrTypeCode.String },
{ typeof(ushort), ExtendedClrTypeCode.UInt16 },
{ typeof(uint), ExtendedClrTypeCode.UInt32 },
{ typeof(ulong), ExtendedClrTypeCode.UInt64 },
{ typeof(object), ExtendedClrTypeCode.Object },
{ typeof(byte[]), ExtendedClrTypeCode.ByteArray },
{ typeof(char[]), ExtendedClrTypeCode.CharArray },
{ typeof(Guid), ExtendedClrTypeCode.Guid },
{ typeof(SqlBinary), ExtendedClrTypeCode.SqlBinary },
{ typeof(SqlBoolean), ExtendedClrTypeCode.SqlBoolean },
{ typeof(SqlByte), ExtendedClrTypeCode.SqlByte },
{ typeof(SqlDateTime), ExtendedClrTypeCode.SqlDateTime },
{ typeof(SqlDouble), ExtendedClrTypeCode.SqlDouble },
{ typeof(SqlGuid), ExtendedClrTypeCode.SqlGuid },
{ typeof(SqlInt16), ExtendedClrTypeCode.SqlInt16 },
{ typeof(SqlInt32), ExtendedClrTypeCode.SqlInt32 },
{ typeof(SqlInt64), ExtendedClrTypeCode.SqlInt64 },
{ typeof(SqlMoney), ExtendedClrTypeCode.SqlMoney },
{ typeof(SqlDecimal), ExtendedClrTypeCode.SqlDecimal },
{ typeof(SqlSingle), ExtendedClrTypeCode.SqlSingle },
{ typeof(SqlString), ExtendedClrTypeCode.SqlString },
{ typeof(SqlChars), ExtendedClrTypeCode.SqlChars },
{ typeof(SqlBytes), ExtendedClrTypeCode.SqlBytes },
{ typeof(SqlXml), ExtendedClrTypeCode.SqlXml },
{ typeof(DbDataReader), ExtendedClrTypeCode.DbDataReader },
{ typeof(IEnumerable<SqlDataRecord>), ExtendedClrTypeCode.IEnumerableOfSqlDataRecord },
{ typeof(TimeSpan), ExtendedClrTypeCode.TimeSpan },
{ typeof(DateTimeOffset), ExtendedClrTypeCode.DateTimeOffset },
};
Debug.Assert(dictionary.Count == Count);
return dictionary;
}
internal static bool IsCharOrXmlType(SqlDbType type)
{
return IsUnicodeType(type) ||
IsAnsiType(type) ||
type == SqlDbType.Xml;
}
internal static bool IsUnicodeType(SqlDbType type)
{
return type == SqlDbType.NChar ||
type == SqlDbType.NVarChar ||
type == SqlDbType.NText;
}
internal static bool IsAnsiType(SqlDbType type)
{
return type == SqlDbType.Char ||
type == SqlDbType.VarChar ||
type == SqlDbType.Text;
}
internal static bool IsBinaryType(SqlDbType type)
{
return type == SqlDbType.Binary ||
type == SqlDbType.VarBinary ||
type == SqlDbType.Image;
}
// Does this type use PLP format values?
internal static bool IsPlpFormat(SmiMetaData metaData)
{
return metaData.MaxLength == SmiMetaData.UnlimitedMaxLengthIndicator ||
metaData.SqlDbType == SqlDbType.Image ||
metaData.SqlDbType == SqlDbType.NText ||
metaData.SqlDbType == SqlDbType.Text ||
metaData.SqlDbType == SqlDbType.Udt;
}
// If we know we're only going to use this object to assign to a specific SqlDbType back end object,
// we can save some processing time by only checking for the few valid types that can be assigned to the dbType.
// This assumes a switch statement over SqlDbType is faster than getting the ClrTypeCode and iterating over a
// series of if statements, or using a hash table.
// NOTE: the form of these checks is taking advantage of a feature of the JIT compiler that is supposed to
// optimize checks of the form '(xxx.GetType() == typeof( YYY ))'. The JIT team claimed at one point that
// this doesn't even instantiate a Type instance, thus was the fastest method for individual comparisons.
// Given that there's a known SqlDbType, thus a minimal number of comparisons, it's likely this is faster
// than the other approaches considered (both GetType().GetTypeCode() switch and hash table using Type keys
// must instantiate a Type object. The typecode switch also degenerates into a large if-then-else for
// all but the primitive clr types.
internal static ExtendedClrTypeCode DetermineExtendedTypeCodeForUseWithSqlDbType(
SqlDbType dbType,
bool isMultiValued,
object value
)
{
ExtendedClrTypeCode extendedCode = ExtendedClrTypeCode.Invalid;
// fast-track null, which is valid for all types
if (null == value)
{
extendedCode = ExtendedClrTypeCode.Empty;
}
else if (DBNull.Value == value)
{
extendedCode = ExtendedClrTypeCode.DBNull;
}
else
{
switch (dbType)
{
case SqlDbType.BigInt:
if (value.GetType() == typeof(Int64))
extendedCode = ExtendedClrTypeCode.Int64;
else if (value.GetType() == typeof(SqlInt64))
extendedCode = ExtendedClrTypeCode.SqlInt64;
break;
case SqlDbType.Binary:
case SqlDbType.VarBinary:
case SqlDbType.Image:
case SqlDbType.Timestamp:
if (value.GetType() == typeof(byte[]))
extendedCode = ExtendedClrTypeCode.ByteArray;
else if (value.GetType() == typeof(SqlBinary))
extendedCode = ExtendedClrTypeCode.SqlBinary;
else if (value.GetType() == typeof(SqlBytes))
extendedCode = ExtendedClrTypeCode.SqlBytes;
else if (value.GetType() == typeof(StreamDataFeed))
extendedCode = ExtendedClrTypeCode.Stream;
break;
case SqlDbType.Bit:
if (value.GetType() == typeof(bool))
extendedCode = ExtendedClrTypeCode.Boolean;
else if (value.GetType() == typeof(SqlBoolean))
extendedCode = ExtendedClrTypeCode.SqlBoolean;
break;
case SqlDbType.Char:
case SqlDbType.NChar:
case SqlDbType.NText:
case SqlDbType.NVarChar:
case SqlDbType.Text:
case SqlDbType.VarChar:
if (value.GetType() == typeof(string))
extendedCode = ExtendedClrTypeCode.String;
if (value.GetType() == typeof(TextDataFeed))
extendedCode = ExtendedClrTypeCode.TextReader;
else if (value.GetType() == typeof(SqlString))
extendedCode = ExtendedClrTypeCode.SqlString;
else if (value.GetType() == typeof(char[]))
extendedCode = ExtendedClrTypeCode.CharArray;
else if (value.GetType() == typeof(SqlChars))
extendedCode = ExtendedClrTypeCode.SqlChars;
else if (value.GetType() == typeof(char))
extendedCode = ExtendedClrTypeCode.Char;
break;
case SqlDbType.Date:
case SqlDbType.DateTime2:
case SqlDbType.DateTime:
case SqlDbType.SmallDateTime:
if (value.GetType() == typeof(DateTime))
extendedCode = ExtendedClrTypeCode.DateTime;
else if (value.GetType() == typeof(SqlDateTime))
extendedCode = ExtendedClrTypeCode.SqlDateTime;
break;
case SqlDbType.Decimal:
if (value.GetType() == typeof(Decimal))
extendedCode = ExtendedClrTypeCode.Decimal;
else if (value.GetType() == typeof(SqlDecimal))
extendedCode = ExtendedClrTypeCode.SqlDecimal;
break;
case SqlDbType.Real:
if (value.GetType() == typeof(Single))
extendedCode = ExtendedClrTypeCode.Single;
else if (value.GetType() == typeof(SqlSingle))
extendedCode = ExtendedClrTypeCode.SqlSingle;
break;
case SqlDbType.Int:
if (value.GetType() == typeof(Int32))
extendedCode = ExtendedClrTypeCode.Int32;
else if (value.GetType() == typeof(SqlInt32))
extendedCode = ExtendedClrTypeCode.SqlInt32;
break;
case SqlDbType.Money:
case SqlDbType.SmallMoney:
if (value.GetType() == typeof(SqlMoney))
extendedCode = ExtendedClrTypeCode.SqlMoney;
else if (value.GetType() == typeof(Decimal))
extendedCode = ExtendedClrTypeCode.Decimal;
break;
case SqlDbType.Float:
if (value.GetType() == typeof(SqlDouble))
extendedCode = ExtendedClrTypeCode.SqlDouble;
else if (value.GetType() == typeof(Double))
extendedCode = ExtendedClrTypeCode.Double;
break;
case SqlDbType.UniqueIdentifier:
if (value.GetType() == typeof(SqlGuid))
extendedCode = ExtendedClrTypeCode.SqlGuid;
else if (value.GetType() == typeof(Guid))
extendedCode = ExtendedClrTypeCode.Guid;
break;
case SqlDbType.SmallInt:
if (value.GetType() == typeof(Int16))
extendedCode = ExtendedClrTypeCode.Int16;
else if (value.GetType() == typeof(SqlInt16))
extendedCode = ExtendedClrTypeCode.SqlInt16;
break;
case SqlDbType.TinyInt:
if (value.GetType() == typeof(Byte))
extendedCode = ExtendedClrTypeCode.Byte;
else if (value.GetType() == typeof(SqlByte))
extendedCode = ExtendedClrTypeCode.SqlByte;
break;
case SqlDbType.Variant:
// SqlDbType doesn't help us here, call general-purpose function
extendedCode = DetermineExtendedTypeCode(value);
// Some types aren't allowed for Variants but are for the general-purpose function.
// Match behavior of other types and return invalid in these cases.
if (ExtendedClrTypeCode.SqlXml == extendedCode)
{
extendedCode = ExtendedClrTypeCode.Invalid;
}
break;
case SqlDbType.Udt:
throw ADP.DbTypeNotSupported(SqlDbType.Udt.ToString());
case SqlDbType.Time:
if (value.GetType() == typeof(TimeSpan))
extendedCode = ExtendedClrTypeCode.TimeSpan;
break;
case SqlDbType.DateTimeOffset:
if (value.GetType() == typeof(DateTimeOffset))
extendedCode = ExtendedClrTypeCode.DateTimeOffset;
break;
case SqlDbType.Xml:
if (value.GetType() == typeof(SqlXml))
extendedCode = ExtendedClrTypeCode.SqlXml;
if (value.GetType() == typeof(XmlDataFeed))
extendedCode = ExtendedClrTypeCode.XmlReader;
else if (value.GetType() == typeof(System.String))
extendedCode = ExtendedClrTypeCode.String;
break;
case SqlDbType.Structured:
if (isMultiValued)
{
if (value is IEnumerable<SqlDataRecord>)
{
extendedCode = ExtendedClrTypeCode.IEnumerableOfSqlDataRecord;
}
else if (value is DbDataReader)
{
extendedCode = ExtendedClrTypeCode.DbDataReader;
}
}
break;
default:
// Leave as invalid
break;
}
}
return extendedCode;
}
// Method to map from Type to ExtendedTypeCode
static internal ExtendedClrTypeCode DetermineExtendedTypeCodeFromType(Type clrType)
{
ExtendedClrTypeCode resultCode;
return s_typeToExtendedTypeCodeMap.TryGetValue(clrType, out resultCode) ?
resultCode :
ExtendedClrTypeCode.Invalid;
}
// Returns the ExtendedClrTypeCode that describes the given value
static internal ExtendedClrTypeCode DetermineExtendedTypeCode(object value)
{
return value != null ?
DetermineExtendedTypeCodeFromType(value.GetType()) :
ExtendedClrTypeCode.Empty;
}
// returns a sqldbtype for the given type code
static internal SqlDbType InferSqlDbTypeFromTypeCode(ExtendedClrTypeCode typeCode)
{
Debug.Assert(typeCode >= ExtendedClrTypeCode.Invalid && typeCode <= ExtendedClrTypeCode.Last, "Someone added a typecode without adding support here!");
return s_extendedTypeCodeToSqlDbTypeMap[(int)typeCode + 1];
}
// Infer SqlDbType from Type in the general case. Katmai-only (or later) features that need to
// infer types should use InferSqlDbTypeFromType_Katmai.
static internal SqlDbType InferSqlDbTypeFromType(Type type)
{
ExtendedClrTypeCode typeCode = DetermineExtendedTypeCodeFromType(type);
SqlDbType returnType;
if (ExtendedClrTypeCode.Invalid == typeCode)
{
returnType = InvalidSqlDbType; // Return invalid type so caller can generate specific error
}
else
{
returnType = InferSqlDbTypeFromTypeCode(typeCode);
}
return returnType;
}
// Inference rules changed for Katmai-or-later-only cases. Only features that are guaranteed to be
// running against Katmai and don't have backward compat issues should call this code path.
// example: TVP's are a new Katmai feature (no back compat issues) so can infer DATETIME2
// when mapping System.DateTime from DateTable or DbDataReader. DATETIME2 is better because
// of greater range that can handle all DateTime values.
static internal SqlDbType InferSqlDbTypeFromType_Katmai(Type type)
{
SqlDbType returnType = InferSqlDbTypeFromType(type);
if (SqlDbType.DateTime == returnType)
{
returnType = SqlDbType.DateTime2;
}
return returnType;
}
static internal SqlMetaData SmiExtendedMetaDataToSqlMetaData(SmiExtendedMetaData source)
{
if (SqlDbType.Xml == source.SqlDbType)
{
return new SqlMetaData(source.Name,
source.SqlDbType,
source.MaxLength,
source.Precision,
source.Scale,
source.LocaleId,
source.CompareOptions,
source.TypeSpecificNamePart1,
source.TypeSpecificNamePart2,
source.TypeSpecificNamePart3,
true
);
}
return new SqlMetaData(source.Name,
source.SqlDbType,
source.MaxLength,
source.Precision,
source.Scale,
source.LocaleId,
source.CompareOptions,
null);
}
// Convert SqlMetaData instance to an SmiExtendedMetaData instance.
internal static SmiExtendedMetaData SqlMetaDataToSmiExtendedMetaData(SqlMetaData source)
{
// now map everything across to the extended metadata object
string typeSpecificNamePart1 = null;
string typeSpecificNamePart2 = null;
string typeSpecificNamePart3 = null;
if (SqlDbType.Xml == source.SqlDbType)
{
typeSpecificNamePart1 = source.XmlSchemaCollectionDatabase;
typeSpecificNamePart2 = source.XmlSchemaCollectionOwningSchema;
typeSpecificNamePart3 = source.XmlSchemaCollectionName;
}
else if (SqlDbType.Udt == source.SqlDbType)
{
throw ADP.DbTypeNotSupported(SqlDbType.Udt.ToString());
}
return new SmiExtendedMetaData(source.SqlDbType,
source.MaxLength,
source.Precision,
source.Scale,
source.LocaleId,
source.CompareOptions,
source.Name,
typeSpecificNamePart1,
typeSpecificNamePart2,
typeSpecificNamePart3);
}
// compare SmiMetaData to SqlMetaData and determine if they are compatible.
static internal bool IsCompatible(SmiMetaData firstMd, SqlMetaData secondMd)
{
return firstMd.SqlDbType == secondMd.SqlDbType &&
firstMd.MaxLength == secondMd.MaxLength &&
firstMd.Precision == secondMd.Precision &&
firstMd.Scale == secondMd.Scale &&
firstMd.CompareOptions == secondMd.CompareOptions &&
firstMd.LocaleId == secondMd.LocaleId &&
firstMd.SqlDbType != SqlDbType.Structured && // SqlMetaData doesn't support Structured types
!firstMd.IsMultiValued; // SqlMetaData doesn't have a "multivalued" option
}
// This is a modified version of SmiMetaDataFromSchemaTableRow above
// Since CoreCLR doesn't have GetSchema, we need to infer the MetaData from the CLR Type alone
static internal SmiExtendedMetaData SmiMetaDataFromType(string colName, Type colType)
{
// Determine correct SqlDbType.
SqlDbType colDbType = InferSqlDbTypeFromType_Katmai(colType);
if (InvalidSqlDbType == colDbType)
{
// Unknown through standard mapping, use VarBinary for columns that are Object typed, otherwise we error out.
if (typeof(object) == colType)
{
colDbType = SqlDbType.VarBinary;
}
else
{
throw SQL.UnsupportedColumnTypeForSqlProvider(colName, colType.ToString());
}
}
// Determine metadata modifier values per type (maxlength, precision, scale, etc)
long maxLength = 0;
byte precision = 0;
byte scale = 0;
switch (colDbType)
{
case SqlDbType.BigInt:
case SqlDbType.Bit:
case SqlDbType.DateTime:
case SqlDbType.Float:
case SqlDbType.Image:
case SqlDbType.Int:
case SqlDbType.Money:
case SqlDbType.NText:
case SqlDbType.Real:
case SqlDbType.UniqueIdentifier:
case SqlDbType.SmallDateTime:
case SqlDbType.SmallInt:
case SqlDbType.SmallMoney:
case SqlDbType.Text:
case SqlDbType.Timestamp:
case SqlDbType.TinyInt:
case SqlDbType.Variant:
case SqlDbType.Xml:
case SqlDbType.Date:
// These types require no metadata modifiers
break;
case SqlDbType.Binary:
case SqlDbType.VarBinary:
// source isn't specifying a size, so assume the Maximum
if (SqlDbType.Binary == colDbType)
{
maxLength = SmiMetaData.MaxBinaryLength;
}
else
{
maxLength = SmiMetaData.UnlimitedMaxLengthIndicator;
}
break;
case SqlDbType.Char:
case SqlDbType.VarChar:
// source isn't specifying a size, so assume the Maximum
if (SqlDbType.Char == colDbType)
{
maxLength = SmiMetaData.MaxANSICharacters;
}
else
{
maxLength = SmiMetaData.UnlimitedMaxLengthIndicator;
}
break;
case SqlDbType.NChar:
case SqlDbType.NVarChar:
// source isn't specifying a size, so assume the Maximum
if (SqlDbType.NChar == colDbType)
{
maxLength = SmiMetaData.MaxUnicodeCharacters;
}
else
{
maxLength = SmiMetaData.UnlimitedMaxLengthIndicator;
}
break;
case SqlDbType.Decimal:
// Decimal requires precision and scale
precision = SmiMetaData.DefaultDecimal.Precision;
scale = SmiMetaData.DefaultDecimal.Scale;
break;
case SqlDbType.Time:
case SqlDbType.DateTime2:
case SqlDbType.DateTimeOffset:
// requires scale
scale = SmiMetaData.DefaultTime.Scale;
break;
case SqlDbType.Udt:
case SqlDbType.Structured:
default:
// These types are not supported from SchemaTable
throw SQL.UnsupportedColumnTypeForSqlProvider(colName, colType.ToString());
}
return new SmiExtendedMetaData(
colDbType,
maxLength,
precision,
scale,
Locale.GetCurrentCultureLcid(),
SmiMetaData.GetDefaultForType(colDbType).CompareOptions,
false, // no support for multi-valued columns in a TVP yet
null, // no support for structured columns yet
null,
colName,
null,
null,
null);
}
}
}
| |
/********************************************************************************************
Copyright (c) Microsoft Corporation
All rights reserved.
Microsoft Public License:
This license governs use of the accompanying software. If you use the software, you
accept this license. If you do not accept the license, do not use the software.
1. Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" have the
same meaning here as under U.S. copyright law.
A "contribution" is the original software, or any additions or changes to the software.
A "contributor" is any person that distributes its contribution under this license.
"Licensed patents" are a contributor's patent claims that read directly on its contribution.
2. Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the license conditions
and limitations in section 3, each contributor grants you a non-exclusive, worldwide,
royalty-free copyright license to reproduce its contribution, prepare derivative works of
its contribution, and distribute its contribution or any derivative works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license conditions
and limitations in section 3, each contributor grants you a non-exclusive, worldwide,
royalty-free license under its licensed patents to make, have made, use, sell, offer for
sale, import, and/or otherwise dispose of its contribution in the software or derivative
works of the contribution in the software.
3. Conditions and Limitations
(A) No Trademark License- This license does not grant you rights to use any contributors'
name, logo, or trademarks.
(B) If you bring a patent claim against any contributor over patents that you claim are
infringed by the software, your patent license from such contributor to the software ends
automatically.
(C) If you distribute any portion of the software, you must retain all copyright, patent,
trademark, and attribution notices that are present in the software.
(D) If you distribute any portion of the software in source code form, you may do so only
under this license by including a complete copy of this license with your distribution.
If you distribute any portion of the software in compiled or object code form, you may only
do so under a license that complies with this license.
(E) The software is licensed "as-is." You bear the risk of using it. The contributors give
no express warranties, guarantees or conditions. You may have additional consumer rights
under your local laws which this license cannot change. To the extent permitted under your
local laws, the contributors exclude the implied warranties of merchantability, fitness for
a particular purpose and non-infringement.
********************************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants;
using VsCommands = Microsoft.VisualStudio.VSConstants.VSStd97CmdID;
using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID;
namespace Microsoft.VisualStudio.Project
{
[CLSCompliant(false)]
[ComVisible(true)]
public class FolderNode : HierarchyNode
{
#region ctors
/// <summary>
/// Constructor for the FolderNode
/// </summary>
/// <param name="root">Root node of the hierarchy</param>
/// <param name="relativePath">relative path from root i.e.: "NewFolder1\\NewFolder2\\NewFolder3</param>
/// <param name="element">Associated project element</param>
public FolderNode(ProjectNode root, string relativePath, ProjectElement element)
: base(root, element)
{
if (relativePath == null)
{
throw new ArgumentNullException("relativePath");
}
this.VirtualNodeName = relativePath.TrimEnd('\\');
}
#endregion
#region overridden properties
public override int SortPriority
{
get { return DefaultSortOrderNode.FolderNode; }
}
/// <summary>
/// This relates to the SCC glyph
/// </summary>
public override VsStateIcon StateIconIndex
{
get
{
// The SCC manager does not support being asked for the state icon of a folder (result of the operation is undefined)
return VsStateIcon.STATEICON_NOSTATEICON;
}
}
#endregion
#region overridden methods
protected override NodeProperties CreatePropertiesObject()
{
return new FolderNodeProperties(this);
}
protected internal override void DeleteFromStorage(string path)
{
this.DeleteFolder(path);
}
/// <summary>
/// Get the automation object for the FolderNode
/// </summary>
/// <returns>An instance of the Automation.OAFolderNode type if succeeded</returns>
public override object GetAutomationObject()
{
if(this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
return null;
}
return new Automation.OAFolderItem(this.ProjectMgr.GetAutomationObject() as Automation.OAProject, this);
}
public override object GetIconHandle(bool open)
{
return this.ProjectMgr.ImageHandler.GetIconHandle(open ? (int)ProjectNode.ImageName.OpenFolder : (int)ProjectNode.ImageName.Folder);
}
/// <summary>
/// Rename Folder
/// </summary>
/// <param name="label">new Name of Folder</param>
/// <returns>VSConstants.S_OK, if succeeded</returns>
public override int SetEditLabel(string label)
{
if(String.Compare(Path.GetFileName(this.Url.TrimEnd('\\')), label, StringComparison.Ordinal) == 0)
{
// Label matches current Name
return VSConstants.S_OK;
}
string newPath = Path.Combine(new DirectoryInfo(this.Url).Parent.FullName, label);
// Verify that No Directory/file already exists with the new name among current children
for(HierarchyNode n = Parent.FirstChild; n != null; n = n.NextSibling)
{
if(n != this && String.Compare(n.Caption, label, StringComparison.OrdinalIgnoreCase) == 0)
{
return ShowFileOrFolderAlreadExistsErrorMessage(newPath);
}
}
// Verify that No Directory/file already exists with the new name on disk
if(Directory.Exists(newPath) || File.Exists(newPath))
{
return ShowFileOrFolderAlreadExistsErrorMessage(newPath);
}
try
{
RenameFolder(label);
//Refresh the properties in the properties window
IVsUIShell shell = this.ProjectMgr.GetService(typeof(SVsUIShell)) as IVsUIShell;
Debug.Assert(shell != null, "Could not get the ui shell from the project");
ErrorHandler.ThrowOnFailure(shell.RefreshPropertyBrowser(0));
// Notify the listeners that the name of this folder is changed. This will
// also force a refresh of the SolutionExplorer's node.
this.OnPropertyChanged(this, (int)__VSHPROPID.VSHPROPID_Caption, 0);
}
catch(Exception e)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.RenameFolder, CultureInfo.CurrentUICulture), e.Message));
}
return VSConstants.S_OK;
}
public override int MenuCommandId
{
get { return VsMenus.IDM_VS_CTXT_FOLDERNODE; }
}
public override Guid ItemTypeGuid
{
get
{
return VSConstants.GUID_ItemType_PhysicalFolder;
}
}
public override string Url
{
get
{
return Path.Combine(Path.GetDirectoryName(this.ProjectMgr.Url), this.VirtualNodeName) + "\\";
}
}
public override string Caption
{
get
{
// it might have a backslash at the end...
// and it might consist of Grandparent\parent\this\
string caption = this.VirtualNodeName;
string[] parts;
parts = caption.Split(Path.DirectorySeparatorChar);
caption = parts[parts.GetUpperBound(0)];
return caption;
}
}
public override string GetMkDocument()
{
Debug.Assert(this.Url != null, "No url sepcified for this node");
return this.Url;
}
/// <summary>
/// Enumerate the files associated with this node.
/// A folder node is not a file and as such no file to enumerate.
/// </summary>
/// <param name="files">The list of files to be placed under source control.</param>
/// <param name="flags">The flags that are associated to the files.</param>
protected internal override void GetSccFiles(System.Collections.Generic.IList<string> files, System.Collections.Generic.IList<tagVsSccFilesFlags> flags)
{
return;
}
/// <summary>
/// This method should be overridden to provide the list of special files and associated flags for source control.
/// </summary>
/// <param name="sccFile">One of the file associated to the node.</param>
/// <param name="files">The list of files to be placed under source control.</param>
/// <param name="flags">The flags that are associated to the files.</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Scc")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "scc")]
protected internal override void GetSccSpecialFiles(string sccFile, IList<string> files, IList<tagVsSccFilesFlags> flags)
{
if(this.ExcludeNodeFromScc)
{
return;
}
if(files == null)
{
throw new ArgumentNullException("files");
}
if(flags == null)
{
throw new ArgumentNullException("flags");
}
if(string.IsNullOrEmpty(sccFile))
{
throw new ArgumentException(SR.GetString(SR.InvalidParameter, CultureInfo.CurrentUICulture), "sccFile");
}
// Get the file node for the file passed in.
FileNode node = this.FindChild(sccFile) as FileNode;
// Dependents do not participate directly in scc.
if(node != null && !(node is DependentFileNode))
{
node.GetSccSpecialFiles(sccFile, files, flags);
}
}
/// <summary>
/// Recursevily walks the folder nodes and redraws the state icons
/// </summary>
protected internal override void UpdateSccStateIcons()
{
for(HierarchyNode child = this.FirstChild; child != null; child = child.NextSibling)
{
child.UpdateSccStateIcons();
}
}
protected override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result)
{
if(cmdGroup == VsMenus.guidStandardCommandSet97)
{
switch((VsCommands)cmd)
{
case VsCommands.Copy:
case VsCommands.Paste:
case VsCommands.Cut:
case VsCommands.Rename:
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
case VsCommands.NewFolder:
case VsCommands.AddNewItem:
case VsCommands.AddExistingItem:
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
}
else if(cmdGroup == VsMenus.guidStandardCommandSet2K)
{
if((VsCommands2K)cmd == VsCommands2K.EXCLUDEFROMPROJECT)
{
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
}
else
{
return (int)OleConstants.OLECMDERR_E_UNKNOWNGROUP;
}
return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result);
}
protected override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation)
{
if(deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_DeleteFromStorage)
{
return this.ProjectMgr.CanProjectDeleteItems;
}
return false;
}
#endregion
#region virtual methods
/// <summary>
/// Override if your node is not a file system folder so that
/// it does nothing or it deletes it from your storage location.
/// </summary>
/// <param name="path">Path to the folder to delete</param>
public virtual void DeleteFolder(string path)
{
if(Directory.Exists(path))
Directory.Delete(path, true);
}
/// <summary>
/// creates the physical directory for a folder node
/// Override if your node does not use file system folder
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "e")]
public virtual void CreateDirectory()
{
try
{
if(Directory.Exists(this.Url) == false)
{
Directory.CreateDirectory(this.Url);
}
}
//TODO - this should not digest all exceptions.
catch(System.Exception e)
{
CCITracing.Trace(e);
throw;
}
}
/// <summary>
/// Creates a folder nodes physical directory
/// Override if your node does not use file system folder
/// </summary>
/// <param name="newName"></param>
/// <returns></returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "e")]
public virtual void CreateDirectory(string newName)
{
if(String.IsNullOrEmpty(newName))
{
throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "newName");
}
try
{
// on a new dir && enter, we get called with the same name (so do nothing if name is the same
char[] dummy = new char[1];
dummy[0] = Path.DirectorySeparatorChar;
string oldDir = this.Url;
oldDir = oldDir.TrimEnd(dummy);
string strNewDir = Path.Combine(Path.GetDirectoryName(oldDir), newName);
if(String.Compare(strNewDir, oldDir, StringComparison.OrdinalIgnoreCase) != 0)
{
if(Directory.Exists(strNewDir))
{
throw new InvalidOperationException(SR.GetString(SR.DirectoryExistError, CultureInfo.CurrentUICulture));
}
Directory.CreateDirectory(strNewDir);
}
}
//TODO - this should not digest all exceptions.
catch(System.Exception e)
{
CCITracing.Trace(e);
throw;
}
}
/// <summary>
/// Rename the physical directory for a folder node
/// Override if your node does not use file system folder
/// </summary>
/// <returns></returns>
public virtual void RenameDirectory(string newPath)
{
if(Directory.Exists(this.Url))
{
if(Directory.Exists(newPath))
{
ShowFileOrFolderAlreadExistsErrorMessage(newPath);
}
Directory.Move(this.Url, newPath);
}
}
#endregion
#region helper methods
private void RenameFolder(string newName)
{
// Do the rename (note that we only do the physical rename if the leaf name changed)
string newPath = Path.Combine(this.Parent.VirtualNodeName, newName);
if(String.Compare(Path.GetFileName(VirtualNodeName), newName, StringComparison.Ordinal) != 0)
{
this.RenameDirectory(Path.Combine(this.ProjectMgr.ProjectFolder, newPath));
}
this.VirtualNodeName = newPath;
this.ItemNode.Rename(VirtualNodeName);
// Let all children know of the new path
for(HierarchyNode child = this.FirstChild; child != null; child = child.NextSibling)
{
FolderNode node = child as FolderNode;
if(node == null)
{
child.SetEditLabel(child.Caption);
}
else
{
node.RenameFolder(node.Caption);
}
}
// Some of the previous operation may have changed the selection so set it back to us
IVsUIHierarchyWindow uiWindow = UIHierarchyUtilities.GetUIHierarchyWindow(this.ProjectMgr.Site, SolutionExplorer);
// This happens in the context of renaming a folder.
// Since we are already in solution explorer, it is extremely unlikely that we get a null return.
// If we do, the consequences are minimal: the parent node will be selected instead of the
// renamed node.
if (uiWindow != null)
{
ErrorHandler.ThrowOnFailure(uiWindow.ExpandItem(this.ProjectMgr.InteropSafeIVsUIHierarchy, this.ID, EXPANDFLAGS.EXPF_SelectItem));
}
}
/// <summary>
/// Show error message if not in automation mode, otherwise throw exception
/// </summary>
/// <param name="newPath">path of file or folder already existing on disk</param>
/// <returns>S_OK</returns>
private int ShowFileOrFolderAlreadExistsErrorMessage(string newPath)
{
//A file or folder with the name '{0}' already exists on disk at this location. Please choose another name.
//If this file or folder does not appear in the Solution Explorer, then it is not currently part of your project. To view files which exist on disk, but are not in the project, select Show All Files from the Project menu.
string errorMessage = (String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.FileOrFolderAlreadyExists, CultureInfo.CurrentUICulture), newPath));
if(!Utilities.IsInAutomationFunction(this.ProjectMgr.Site))
{
string title = null;
OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL;
OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK;
OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
VsShellUtilities.ShowMessageBox(this.ProjectMgr.Site, title, errorMessage, icon, buttons, defaultButton);
return VSConstants.S_OK;
}
else
{
throw new InvalidOperationException(errorMessage);
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Construction;
using Xunit;
namespace Microsoft.Build.UnitTests.OM.Definition
{
/// <summary>
/// Tests for protecting imported files while editing
/// </summary>
public class ProtectImports_Tests : IDisposable
{
#region Constants
/// <summary>
/// Imported metadata name
/// </summary>
private const string ImportedMetadataName = "ImportedMetadataName";
/// <summary>
/// Imported metadata value
/// </summary>
private const string ImportedMetadataValue = "ImportedMetadataValue";
/// <summary>
/// Item name to use
/// </summary>
private const string ItemName = "ItemName";
/// <summary>
/// Item type to use
/// </summary>
private const string ItemType = "ItemType";
/// <summary>
/// New value
/// </summary>
private const string NewValue = "NewValue";
/// <summary>
/// It's non-overridable just in the sense that the tests aren't providing new values to it; nothing else implied
/// </summary>
private const string NonOverridableMetadataName = "NonOverridableMetadataName";
/// <summary>
/// Overridable metadata name
/// </summary>
private const string OverridableMetadataName = "OverridableMetadataName";
/// <summary>
/// Project metadata name
/// </summary>
private const string ProjectMetadataName = "ProjectMetadataName";
/// <summary>
/// Project metadata value
/// </summary>
private const string ProjectMetadataValue = "ProjectMetadataValue";
/// <summary>
/// Same property name
/// </summary>
private const string PropertyName = "ImportedProperty";
#endregion
/// <summary>
/// Import filename
/// </summary>
private string _importFilename;
#region Test lifetime
/// <summary>
/// Configures the overall test.
/// </summary>
public ProtectImports_Tests()
{
string importContents =
@"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<PropertyGroup>
<$propertyName>OldPropertyValue</$propertyName>
</PropertyGroup>
<ItemDefinitionGroup>
<$itemType>
<$overridableMetadataName>ImportValue</$overridableMetadataName>
<$nonOverridableMetadataName>ImportValue</$nonOverridableMetadataName>
</$itemType>
</ItemDefinitionGroup>
<ItemGroup>
<$itemType Include=""$itemName"">
<$importedMetadataName>$importedMetadataValue</$importedMetadataName>
</$itemType>
</ItemGroup>
</Project>";
importContents = Expand(importContents);
_importFilename = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile() + ".targets";
File.WriteAllText(_importFilename, importContents);
}
/// <summary>
/// Undoes the test configuration.
/// </summary>
public void Dispose()
{
if (File.Exists(_importFilename))
{
File.Delete(_importFilename);
}
}
#endregion
#region Property Tests
/// <summary>
/// Tests against edits into imported properties through the property itself.
/// </summary>
[Fact]
public void PropertySetViaProperty()
{
Assert.Throws<InvalidOperationException>(() =>
{
Project project = GetProject();
ProjectProperty property = GetProperty(project);
// This should throw
property.UnevaluatedValue = NewValue;
}
);
}
/// <summary>
/// Tests against edits into imported properties through the project.
/// Instead of editing the existing property, because it originated
/// in an imported file, it should create a new one in the main project.
/// </summary>
[Fact]
public void PropertySetViaProject()
{
Project project = GetProject();
GetProperty(project);
project.SetProperty(PropertyName, NewValue);
Assert.Equal(NewValue, project.GetPropertyValue(PropertyName));
}
/// <summary>
/// Tests against edits into imported properties through the property itself.
/// </summary>
[Fact]
public void PropertyRemove()
{
Assert.Throws<InvalidOperationException>(() =>
{
Project project = GetProject();
ProjectProperty property = GetProperty(project);
// This should throw
project.RemoveProperty(property);
}
);
}
#endregion
#region Item Tests
/// <summary>
/// Tests imported item type change.
/// </summary>
[Fact]
public void ItemImportedChangeType()
{
Assert.Throws<InvalidOperationException>(() =>
{
Project project = GetProject();
ProjectItem item = GetImportedItem(project);
// This should throw
item.ItemType = "NewItemType";
}
);
}
/// <summary>
/// Tests imported item renaming.
/// </summary>
[Fact]
public void ItemImportedRename()
{
Assert.Throws<InvalidOperationException>(() =>
{
Project project = GetProject();
ProjectItem item = GetImportedItem(project);
// This should throw
item.Rename("NewItemName");
}
);
}
/// <summary>
/// Tests imported item SetUnevaluatedValue.
/// </summary>
[Fact]
public void ItemImportedSetUnevaluatedValue()
{
Assert.Throws<InvalidOperationException>(() =>
{
Project project = GetProject();
ProjectItem item = GetImportedItem(project);
// This should throw
item.UnevaluatedInclude = "NewItemName";
}
);
}
/// <summary>
/// Tests imported item removal.
/// </summary>
[Fact]
public void ItemImportedRemove()
{
Assert.Throws<InvalidOperationException>(() =>
{
Project project = GetProject();
ProjectItem item = GetImportedItem(project);
// This should throw
project.RemoveItem(item);
}
);
}
/// <summary>
/// Tests project item type change.
/// </summary>
[Fact]
public void ItemProjectChangeType()
{
Project project = GetProject();
ProjectItem item = GetProjectItem(project);
item.ItemType = NewValue;
Assert.Single(project.GetItems(NewValue)); // "Item in project didn't change name"
Assert.True(project.IsDirty); // "Project was not marked dirty."
}
/// <summary>
/// Tests project item renaming.
/// </summary>
[Fact]
public void ItemProjectRename()
{
Project project = GetProject();
ProjectItem item = GetProjectItem(project);
item.Rename(NewValue);
Assert.Equal(NewValue, item.EvaluatedInclude); // "Item in project didn't change name."
Assert.True(project.IsDirty); // "Project was not marked dirty."
}
/// <summary>
/// Tests project item SetUnevaluatedValue.
/// </summary>
[Fact]
public void ItemProjectSetUnevaluatedValue()
{
Project project = GetProject();
ProjectItem item = GetProjectItem(project);
item.UnevaluatedInclude = NewValue;
Assert.Equal(NewValue, item.EvaluatedInclude); // "Item in project didn't change name."
Assert.True(project.IsDirty); // "Project was not marked dirty."
}
/// <summary>
/// Tests project item removal.
/// </summary>
[Fact]
public void ItemProjectRemove()
{
Project project = GetProject();
ProjectItem item = GetProjectItem(project);
project.RemoveItem(item);
Assert.Single(project.GetItems(ItemType)); // "Item in project wasn't removed."
Assert.True(project.IsDirty); // "Project was not marked dirty."
}
#endregion
#region Metadata Tests
/// <summary>
/// Tests setting existing metadata in import.
/// </summary>
[Fact]
public void MetadataImportSetViaProject()
{
Assert.Throws<InvalidOperationException>(() =>
{
Project project = GetProject();
ProjectItem item = GetImportedItem(project);
// This should throw
item.SetMetadataValue(ImportedMetadataName, "NewImportedMetadataValue");
}
);
}
/// <summary>
/// Tests setting new metadata in import.
/// </summary>
[Fact]
public void MetadataImportAdd()
{
Assert.Throws<InvalidOperationException>(() =>
{
Project project = GetProject();
ProjectItem item = GetImportedItem(project);
// This should throw
item.SetMetadataValue("NewMetadata", "NewImportedMetadataValue");
}
);
}
/// <summary>
/// Tests setting new metadata in import.
/// </summary>
[Fact]
public void MetadataImportSetViaMetadata()
{
Assert.Throws<InvalidOperationException>(() =>
{
Project project = GetProject();
ProjectMetadata metadata = GetImportedMetadata(project);
// This should throw
metadata.UnevaluatedValue = NewValue;
}
);
}
/// <summary>
/// Tests removing metadata in import.
/// </summary>
[Fact]
public void MetadataImportRemove()
{
Assert.Throws<InvalidOperationException>(() =>
{
Project project = GetProject();
ProjectItem item = GetImportedItem(project);
// This should throw
item.RemoveMetadata(ImportedMetadataName);
}
);
}
/// <summary>
/// Tests setting existing metadata in import.
/// </summary>
[Fact]
public void MetadataProjectSetViaItem()
{
Project project = GetProject();
ProjectItem item = GetProjectItem(project);
item.SetMetadataValue(ProjectMetadataName, NewValue);
Assert.Equal(NewValue, item.GetMetadataValue(ProjectMetadataName)); // "Metadata not saved correctly in project."
Assert.True(project.IsDirty); // "Project was not marked dirty."
}
/// <summary>
/// Tests setting new metadata in import.
/// </summary>
[Fact]
public void MetadataProjectAdd()
{
Project project = GetProject();
ProjectItem item = GetProjectItem(project);
string newName = "NewMetadata";
item.SetMetadataValue(newName, NewValue);
Assert.Equal(NewValue, item.GetMetadataValue(newName)); // "Metadata not saved correctly in project."
Assert.True(project.IsDirty); // "Project was not marked dirty."
}
/// <summary>
/// Tests setting new metadata in import.
/// </summary>
[Fact]
public void MetadataProjectSetViaMetadata()
{
Project project = GetProject();
ProjectMetadata metadata = GetProjectMetadata(project);
string newValue = "NewProjectMetadataValue";
metadata.UnevaluatedValue = newValue;
Assert.Equal(newValue, metadata.EvaluatedValue);
Assert.True(project.IsDirty); // "Project was not marked dirty."
}
/// <summary>
/// Tests removing metadata in import.
/// </summary>
[Fact]
public void MetadataProjectRemove()
{
Project project = GetProject();
ProjectItem item = GetProjectItem(project);
item.RemoveMetadata(ProjectMetadataName);
Assert.False(item.HasMetadata(ProjectMetadataName)); // "Metadata was not removed from project."
Assert.True(project.IsDirty); // "Project was not marked dirty."
}
#endregion
#region Metadata in Item Definition Tests
/// <summary>
/// Tests setting new metadata in import.
/// </summary>
[Fact]
public void DefinitionMetadataImportSetViaMetadata()
{
Assert.Throws<InvalidOperationException>(() =>
{
Project project = GetProject();
ProjectMetadata metadata = GetNonOverridableMetadata(project);
// This should throw
metadata.UnevaluatedValue = NewValue;
}
);
}
/// <summary>
/// Tests removing metadata in imported item definition.
/// </summary>
[Fact]
public void DefinitionMetadataImportRemove()
{
Assert.Throws<InvalidOperationException>(() =>
{
Project project = GetProject();
ProjectItem item = GetProjectItem(project);
// This should throw
item.RemoveMetadata(NonOverridableMetadataName);
}
);
}
/// <summary>
/// Tests setting existing metadata in import.
/// </summary>
[Fact]
public void DefinitionMetadataProjectSetViaProject()
{
Project project = GetProject();
ProjectItem item = GetProjectItem(project);
item.SetMetadataValue(OverridableMetadataName, NewValue);
Assert.Equal(NewValue, item.GetMetadataValue(OverridableMetadataName)); // "Metadata not set correctly in project."
Assert.True(project.IsDirty); // "Project was not marked dirty."
}
/// <summary>
/// Tests setting new metadata in import.
/// </summary>
[Fact]
public void DefinitionMetadataProjectSetViaMetadata()
{
Project project = GetProject();
ProjectMetadata metadata = GetOverridableMetadata(project);
metadata.UnevaluatedValue = NewValue;
Assert.Equal(NewValue, metadata.EvaluatedValue);
Assert.True(project.IsDirty); // "Project was not marked dirty."
}
/// <summary>
/// Tests removing metadata in import.
/// </summary>
[Fact]
public void DefinitionMetadataProjectRemove()
{
Project project = GetProject();
ProjectItem item = GetProjectItem(project);
item.RemoveMetadata(OverridableMetadataName);
ProjectMetadata metadata = item.GetMetadata(OverridableMetadataName);
Assert.NotNull(metadata); // "Imported metadata not found after the project's one was removed."
Assert.True(metadata.IsImported); // "IsImported property is not set."
}
#endregion
#region Test helpers
/// <summary>
/// Expands variables in the string contents.
/// </summary>
/// <param name="original">String to be expanded.</param>
/// <returns>Expanded string.</returns>
private string Expand(string original)
{
string expanded = original.Replace("$importFilename", _importFilename);
expanded = expanded.Replace("$importedMetadataName", ImportedMetadataName);
expanded = expanded.Replace("$importedMetadataValue", ImportedMetadataValue);
expanded = expanded.Replace("$itemName", ItemName);
expanded = expanded.Replace("$itemType", ItemType);
expanded = expanded.Replace("$projectMetadataName", ProjectMetadataName);
expanded = expanded.Replace("$overridableMetadataName", OverridableMetadataName);
expanded = expanded.Replace("$nonOverridableMetadataName", NonOverridableMetadataName);
expanded = expanded.Replace("$projectMetadataValue", ProjectMetadataValue);
expanded = expanded.Replace("$propertyName", PropertyName);
return expanded;
}
/// <summary>
/// Gets the test item from the import.
/// </summary>
/// <param name="project">The project.</param>
/// <returns>The item.</returns>
private ProjectItem GetImportedItem(Project project)
{
IEnumerable<ProjectItem> items = project.GetItems(ItemType).Where(pi => pi.IsImported);
Assert.Single(items); // "Wrong number of items in the import."
ProjectItem item = items.First();
Assert.Equal(_importFilename, item.Xml.ContainingProject.FullPath); // "Item was not found in the imported project."
return item;
}
/// <summary>
/// Gets the test metadata from the import.
/// </summary>
/// <param name="project">The project.</param>
/// <returns>The metadata.</returns>
private ProjectMetadata GetImportedMetadata(Project project)
{
ProjectItem item = GetImportedItem(project);
IEnumerable<ProjectMetadata> metadatum = item.Metadata.Where(m => m.Name == ImportedMetadataName);
Assert.Single(metadatum); // "Incorrect number of imported metadata found."
ProjectMetadata metadata = metadatum.First();
Assert.True(metadata.IsImported); // "IsImport property is not set."
return metadata;
}
/// <summary>
/// Gets the test templetized metadata from the import.
/// </summary>
/// <param name="project">The project.</param>
/// <returns>The metadata.</returns>
private ProjectMetadata GetNonOverridableMetadata(Project project)
{
ProjectItem item = GetProjectItem(project);
IEnumerable<ProjectMetadata> metadatum = item.Metadata.Where(m => m.Name == NonOverridableMetadataName);
Assert.Single(metadatum); // "Incorrect number of imported metadata found."
ProjectMetadata metadata = metadatum.First();
Assert.True(metadata.IsImported); // "IsImport property is not set."
return metadata;
}
/// <summary>
/// Gets the test templetized metadata from the project.
/// </summary>
/// <param name="project">The project.</param>
/// <returns>The metadata.</returns>
private ProjectMetadata GetOverridableMetadata(Project project)
{
ProjectItem item = GetProjectItem(project);
IEnumerable<ProjectMetadata> metadatum = item.Metadata.Where(m => m.Name == OverridableMetadataName);
Assert.Single(metadatum); // "Incorrect number of imported metadata found."
ProjectMetadata metadata = metadatum.First();
Assert.False(metadata.IsImported); // "IsImport property is set."
return metadata;
}
/// <summary>
/// Creates a new project from expanding the template contents.
/// </summary>
/// <returns>The project instance.</returns>
private Project GetProject()
{
string projectContents =
@"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<PropertyGroup>
<$propertyName>OldPropertyValueInProject</$propertyName>
</PropertyGroup>
<ItemGroup>
<$itemType Include=""$itemName"">
<$projectMetadataName>projectValue</$projectMetadataName>
<$overridableMetadataName>ProjectValue</$overridableMetadataName>
</$itemType>
</ItemGroup>
<Import Project=""$importFilename""/>
</Project>";
projectContents = Expand(projectContents);
Project project = new Project(XmlReader.Create(new StringReader(projectContents)));
return project;
}
/// <summary>
/// Gets the test property.
/// </summary>
/// <param name="project">The test project.</param>
/// <returns>The test property.</returns>
private ProjectProperty GetProperty(Project project)
{
ProjectProperty property = project.GetProperty(PropertyName);
Assert.Equal(_importFilename, property.Xml.ContainingProject.FullPath); // "Property was not found in the imported project."
Assert.True(property.IsImported); // "IsImported property was not set."
return property;
}
/// <summary>
/// Gets the test item from the project.
/// </summary>
/// <param name="project">The project.</param>
/// <returns>The item.</returns>
private ProjectItem GetProjectItem(Project project)
{
IEnumerable<ProjectItem> items = project.GetItems(ItemType).Where(pi => !pi.IsImported);
Assert.Single(items); // "Wrong number of items in the project."
ProjectItem item = items.First();
Assert.Null(item.Xml.ContainingProject.FullPath); // "Item was not found in the project." // null because XML is in-memory
return item;
}
/// <summary>
/// Gets the test metadata from the project.
/// </summary>
/// <param name="project">The project.</param>
/// <returns>The metadata.</returns>
private ProjectMetadata GetProjectMetadata(Project project)
{
ProjectItem item = GetProjectItem(project);
IEnumerable<ProjectMetadata> metadatum = item.Metadata.Where(m => m.Name == ProjectMetadataName);
Assert.Single(metadatum); // "Incorrect number of imported metadata found."
ProjectMetadata metadata = metadatum.First();
Assert.False(metadata.IsImported); // "IsImport property is set."
return metadata;
}
#endregion
}
}
| |
// Copyright 2010 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using JetBrains.Annotations;
using NodaTime.Annotations;
using NodaTime.Fields;
using NodaTime.Text;
using NodaTime.Utility;
using System;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using static NodaTime.NodaConstants;
namespace NodaTime
{
// Note: documentation that refers to the LocalDateTime type within this class must use the fully-qualified
// reference to avoid being resolved to the LocalDateTime property instead.
/// <summary>
/// LocalTime is an immutable struct representing a time of day, with no reference
/// to a particular calendar, time zone or date.
/// </summary>
/// <remarks>
/// Ordering and equality are defined in the natural way, simply comparing the number of "nanoseconds since midnight".
/// </remarks>
/// <threadsafety>This type is an immutable value type. See the thread safety section of the user guide for more information.</threadsafety>
[TypeConverter(typeof(LocalTimeTypeConverter))]
public readonly struct LocalTime : IEquatable<LocalTime>, IComparable<LocalTime>, IFormattable, IComparable, IXmlSerializable
{
/// <summary>
/// Local time at midnight, i.e. 0 hours, 0 minutes, 0 seconds.
/// </summary>
public static LocalTime Midnight { get; } = new LocalTime(0, 0, 0);
/// <summary>
/// The minimum value of this type; equivalent to <see cref="Midnight"/>.
/// </summary>
public static LocalTime MinValue => Midnight;
/// <summary>
/// Local time at noon, i.e. 12 hours, 0 minutes, 0 seconds.
/// </summary>
public static LocalTime Noon { get; } = new LocalTime(12, 0, 0);
/// <summary>
/// The maximum value of this type, one nanosecond before midnight.
/// </summary>
/// <remarks>This is useful if you have to use an inclusive upper bound for some reason.
/// In general, it's better to use an exclusive upper bound, in which case use midnight of
/// the following day.</remarks>
public static LocalTime MaxValue { get; } = new LocalTime(NanosecondsPerDay - 1);
/// <summary>
/// Nanoseconds since midnight, in the range [0, 86,400,000,000,000).
/// </summary>
private readonly long nanoseconds;
/// <summary>
/// Creates a local time at the given hour and minute, with second, millisecond-of-second
/// and tick-of-millisecond values of zero.
/// </summary>
/// <param name="hour">The hour of day.</param>
/// <param name="minute">The minute of the hour.</param>
/// <exception cref="ArgumentOutOfRangeException">The parameters do not form a valid time.</exception>
/// <returns>The resulting time.</returns>
public LocalTime(int hour, int minute)
{
// Avoid the method calls which give a decent exception unless we're actually going to fail.
if (hour < 0 || hour > HoursPerDay - 1 ||
minute < 0 || minute > MinutesPerHour - 1)
{
Preconditions.CheckArgumentRange(nameof(hour), hour, 0, HoursPerDay - 1);
Preconditions.CheckArgumentRange(nameof(minute), minute, 0, MinutesPerHour - 1);
}
nanoseconds = unchecked(hour * NanosecondsPerHour + minute * NanosecondsPerMinute);
}
/// <summary>
/// Creates a local time at the given hour, minute and second,
/// with millisecond-of-second and tick-of-millisecond values of zero.
/// </summary>
/// <param name="hour">The hour of day.</param>
/// <param name="minute">The minute of the hour.</param>
/// <param name="second">The second of the minute.</param>
/// <exception cref="ArgumentOutOfRangeException">The parameters do not form a valid time.</exception>
/// <returns>The resulting time.</returns>
public LocalTime(int hour, int minute, int second)
{
// Avoid the method calls which give a decent exception unless we're actually going to fail.
if (hour < 0 || hour > HoursPerDay - 1 ||
minute < 0 || minute > MinutesPerHour - 1 ||
second < 0 || second > SecondsPerMinute - 1)
{
Preconditions.CheckArgumentRange(nameof(hour), hour, 0, HoursPerDay - 1);
Preconditions.CheckArgumentRange(nameof(minute), minute, 0, MinutesPerHour - 1);
Preconditions.CheckArgumentRange(nameof(second), second, 0, SecondsPerMinute - 1);
}
nanoseconds = unchecked(hour * NanosecondsPerHour +
minute * NanosecondsPerMinute +
second * NanosecondsPerSecond);
}
/// <summary>
/// Creates a local time at the given hour, minute, second and millisecond,
/// with a tick-of-millisecond value of zero.
/// </summary>
/// <param name="hour">The hour of day.</param>
/// <param name="minute">The minute of the hour.</param>
/// <param name="second">The second of the minute.</param>
/// <param name="millisecond">The millisecond of the second.</param>
/// <exception cref="ArgumentOutOfRangeException">The parameters do not form a valid time.</exception>
/// <returns>The resulting time.</returns>
public LocalTime(int hour, int minute, int second, int millisecond)
{
// Avoid the method calls which give a decent exception unless we're actually going to fail.
if (hour < 0 || hour > HoursPerDay - 1 ||
minute < 0 || minute > MinutesPerHour - 1 ||
second < 0 || second > SecondsPerMinute - 1 ||
millisecond < 0 || millisecond > MillisecondsPerSecond - 1)
{
Preconditions.CheckArgumentRange(nameof(hour), hour, 0, HoursPerDay - 1);
Preconditions.CheckArgumentRange(nameof(minute), minute, 0, MinutesPerHour - 1);
Preconditions.CheckArgumentRange(nameof(second), second, 0, SecondsPerMinute - 1);
Preconditions.CheckArgumentRange(nameof(millisecond), millisecond, 0, MillisecondsPerSecond - 1);
}
nanoseconds = unchecked(
hour * NanosecondsPerHour +
minute * NanosecondsPerMinute +
second * NanosecondsPerSecond +
millisecond * NanosecondsPerMillisecond);
}
/// <summary>
/// Factory method to create a local time at the given hour, minute, second, millisecond and tick within millisecond.
/// </summary>
/// <param name="hour">The hour of day.</param>
/// <param name="minute">The minute of the hour.</param>
/// <param name="second">The second of the minute.</param>
/// <param name="millisecond">The millisecond of the second.</param>
/// <param name="tickWithinMillisecond">The tick within the millisecond.</param>
/// <exception cref="ArgumentOutOfRangeException">The parameters do not form a valid time.</exception>
/// <returns>The resulting time.</returns>
public static LocalTime FromHourMinuteSecondMillisecondTick(int hour, int minute, int second, int millisecond, int tickWithinMillisecond)
{
// Avoid the method calls which give a decent exception unless we're actually going to fail.
if (hour < 0 || hour > HoursPerDay - 1 ||
minute < 0 || minute > MinutesPerHour - 1 ||
second < 0 || second > SecondsPerMinute - 1 ||
millisecond < 0 || millisecond > MillisecondsPerSecond - 1 ||
tickWithinMillisecond < 0 || tickWithinMillisecond > TicksPerMillisecond - 1)
{
Preconditions.CheckArgumentRange(nameof(hour), hour, 0, HoursPerDay - 1);
Preconditions.CheckArgumentRange(nameof(minute), minute, 0, MinutesPerHour - 1);
Preconditions.CheckArgumentRange(nameof(second), second, 0, SecondsPerMinute - 1);
Preconditions.CheckArgumentRange(nameof(millisecond), millisecond, 0, MillisecondsPerSecond - 1);
Preconditions.CheckArgumentRange(nameof(tickWithinMillisecond), tickWithinMillisecond, 0, TicksPerMillisecond - 1);
}
long nanoseconds = unchecked(
hour * NanosecondsPerHour +
minute * NanosecondsPerMinute +
second * NanosecondsPerSecond +
millisecond * NanosecondsPerMillisecond +
tickWithinMillisecond * NanosecondsPerTick);
return new LocalTime(nanoseconds);
}
/// <summary>
/// Factory method for creating a local time from the hour of day, minute of hour, second of minute, and tick of second.
/// </summary>
/// <remarks>
/// This is not a constructor overload as it would have the same signature as the one taking millisecond of second.
/// </remarks>
/// <param name="hour">The hour of day in the desired time, in the range [0, 23].</param>
/// <param name="minute">The minute of hour in the desired time, in the range [0, 59].</param>
/// <param name="second">The second of minute in the desired time, in the range [0, 59].</param>
/// <param name="tickWithinSecond">The tick within the second in the desired time, in the range [0, 9999999].</param>
/// <exception cref="ArgumentOutOfRangeException">The parameters do not form a valid time.</exception>
/// <returns>The resulting time.</returns>
public static LocalTime FromHourMinuteSecondTick(int hour, int minute, int second, int tickWithinSecond)
{
// Avoid the method calls which give a decent exception unless we're actually going to fail.
if (hour < 0 || hour > HoursPerDay - 1 ||
minute < 0 || minute > MinutesPerHour - 1 ||
second < 0 || second > SecondsPerMinute - 1 ||
tickWithinSecond < 0 || tickWithinSecond > TicksPerSecond - 1)
{
Preconditions.CheckArgumentRange(nameof(hour), hour, 0, HoursPerDay - 1);
Preconditions.CheckArgumentRange(nameof(minute), minute, 0, MinutesPerHour - 1);
Preconditions.CheckArgumentRange(nameof(second), second, 0, SecondsPerMinute - 1);
Preconditions.CheckArgumentRange(nameof(tickWithinSecond), tickWithinSecond, 0, TicksPerSecond - 1);
}
return new LocalTime(unchecked(
hour * NanosecondsPerHour +
minute * NanosecondsPerMinute +
second * NanosecondsPerSecond +
tickWithinSecond * NanosecondsPerTick));
}
/// <summary>
/// Factory method for creating a local time from the hour of day, minute of hour, second of minute, and nanosecond of second.
/// </summary>
/// <remarks>
/// This is not a constructor overload as it would have the same signature as the one taking millisecond of second.
/// </remarks>
/// <param name="hour">The hour of day in the desired time, in the range [0, 23].</param>
/// <param name="minute">The minute of hour in the desired time, in the range [0, 59].</param>
/// <param name="second">The second of minute in the desired time, in the range [0, 59].</param>
/// <param name="nanosecondWithinSecond">The nanosecond within the second in the desired time, in the range [0, 999999999].</param>
/// <exception cref="ArgumentOutOfRangeException">The parameters do not form a valid time.</exception>
/// <returns>The resulting time.</returns>
public static LocalTime FromHourMinuteSecondNanosecond(int hour, int minute, int second, long nanosecondWithinSecond)
{
// Avoid the method calls which give a decent exception unless we're actually going to fail.
if (hour < 0 || hour > HoursPerDay - 1 ||
minute < 0 || minute > MinutesPerHour - 1 ||
second < 0 || second > SecondsPerMinute - 1 ||
nanosecondWithinSecond < 0 || nanosecondWithinSecond > NanosecondsPerSecond - 1)
{
Preconditions.CheckArgumentRange(nameof(hour), hour, 0, HoursPerDay - 1);
Preconditions.CheckArgumentRange(nameof(minute), minute, 0, MinutesPerHour - 1);
Preconditions.CheckArgumentRange(nameof(second), second, 0, SecondsPerMinute - 1);
Preconditions.CheckArgumentRange(nameof(nanosecondWithinSecond), nanosecondWithinSecond, 0, NanosecondsPerSecond - 1);
}
return new LocalTime(unchecked(
hour * NanosecondsPerHour +
minute * NanosecondsPerMinute +
second * NanosecondsPerSecond +
nanosecondWithinSecond));
}
/// <summary>
/// Constructor only called from other parts of Noda Time - trusted to be the range [0, NanosecondsPerDay).
/// </summary>
internal LocalTime([Trusted] long nanoseconds)
{
Preconditions.DebugCheckArgumentRange(nameof(nanoseconds), nanoseconds, 0, NanosecondsPerDay - 1);
this.nanoseconds = nanoseconds;
}
/// <summary>
/// Factory method for creating a local time from the number of nanoseconds which have elapsed since midnight.
/// </summary>
/// <param name="nanoseconds">The number of nanoseconds, in the range [0, 86,399,999,999,999]</param>
/// <returns>The resulting time.</returns>
public static LocalTime FromNanosecondsSinceMidnight(long nanoseconds)
{
// Avoid the method calls which give a decent exception unless we're actually going to fail.
if (nanoseconds < 0 || nanoseconds > NanosecondsPerDay - 1)
{
Preconditions.CheckArgumentRange(nameof(nanoseconds), nanoseconds, 0, NanosecondsPerDay - 1);
}
return new LocalTime(nanoseconds);
}
/// <summary>
/// Factory method for creating a local time from the number of ticks which have elapsed since midnight.
/// </summary>
/// <param name="ticks">The number of ticks, in the range [0, 863,999,999,999]</param>
/// <returns>The resulting time.</returns>
public static LocalTime FromTicksSinceMidnight(long ticks)
{
// Avoid the method calls which give a decent exception unless we're actually going to fail.
if (ticks < 0 || ticks > TicksPerDay - 1)
{
Preconditions.CheckArgumentRange(nameof(ticks), ticks, 0, TicksPerDay - 1);
}
return new LocalTime(unchecked(ticks * NanosecondsPerTick));
}
/// <summary>
/// Factory method for creating a local time from the number of milliseconds which have elapsed since midnight.
/// </summary>
/// <param name="milliseconds">The number of milliseconds, in the range [0, 86,399,999]</param>
/// <returns>The resulting time.</returns>
public static LocalTime FromMillisecondsSinceMidnight(int milliseconds)
{
// Avoid the method calls which give a decent exception unless we're actually going to fail.
if (milliseconds < 0 || milliseconds > MillisecondsPerDay - 1)
{
Preconditions.CheckArgumentRange(nameof(milliseconds), milliseconds, 0, MillisecondsPerDay - 1);
}
return new LocalTime(unchecked(milliseconds * NanosecondsPerMillisecond));
}
/// <summary>
/// Factory method for creating a local time from the number of seconds which have elapsed since midnight.
/// </summary>
/// <param name="seconds">The number of seconds, in the range [0, 86,399]</param>
/// <returns>The resulting time.</returns>
public static LocalTime FromSecondsSinceMidnight(int seconds)
{
// Avoid the method calls which give a decent exception unless we're actually going to fail.
if (seconds < 0 || seconds > SecondsPerDay - 1)
{
Preconditions.CheckArgumentRange(nameof(seconds), seconds, 0, SecondsPerDay - 1);
}
return new LocalTime(unchecked(seconds * NanosecondsPerSecond));
}
/// <summary>
/// Factory method for creating a local time from the number of minutes which have elapsed since midnight.
/// </summary>
/// <param name="minutes">The number of minutes, in the range [0, 1439]</param>
/// <returns>The resulting time.</returns>
public static LocalTime FromMinutesSinceMidnight(int minutes)
{
// Avoid the method calls which give a decent exception unless we're actually going to fail.
if (minutes < 0 || minutes > MinutesPerDay - 1)
{
Preconditions.CheckArgumentRange(nameof(minutes), minutes, 0, MinutesPerDay - 1);
}
return new LocalTime(unchecked(minutes * NanosecondsPerMinute));
}
/// <summary>
/// Factory method for creating a local time from the number of hours which have elapsed since midnight.
/// </summary>
/// <param name="hours">The number of hours, in the range [0, 23]</param>
/// <returns>The resulting time.</returns>
public static LocalTime FromHoursSinceMidnight(int hours)
{
// Avoid the method calls which give a decent exception unless we're actually going to fail.
if (hours < 0 || hours > HoursPerDay - 1)
{
Preconditions.CheckArgumentRange(nameof(hours), hours, 0, HoursPerDay - 1);
}
return new LocalTime(unchecked(hours * NanosecondsPerHour));
}
/// <summary>
/// Gets the hour of day of this local time, in the range 0 to 23 inclusive.
/// </summary>
/// <value>The hour of day of this local time, in the range 0 to 23 inclusive.</value>
public int Hour =>
// Effectively nanoseconds / NanosecondsPerHour, but apparently rather more efficient.
(int) ((nanoseconds >> 13) / 439453125);
/// <summary>
/// Gets the hour of the half-day of this local time, in the range 1 to 12 inclusive.
/// </summary>
/// <value>The hour of the half-day of this local time, in the range 1 to 12 inclusive.</value>
public int ClockHourOfHalfDay
{
get
{
unchecked
{
int hourOfHalfDay = unchecked(Hour % 12);
return hourOfHalfDay == 0 ? 12 : hourOfHalfDay;
}
}
}
/// <summary>
/// Gets the minute of this local time, in the range 0 to 59 inclusive.
/// </summary>
/// <value>The minute of this local time, in the range 0 to 59 inclusive.</value>
public int Minute
{
get
{
unchecked
{
// Effectively nanoseconds / NanosecondsPerMinute, but apparently rather more efficient.
int minuteOfDay = (int) ((nanoseconds >> 11) / 29296875);
return minuteOfDay % MinutesPerHour;
}
}
}
/// <summary>
/// Gets the second of this local time within the minute, in the range 0 to 59 inclusive.
/// </summary>
/// <value>The second of this local time within the minute, in the range 0 to 59 inclusive.</value>
public int Second
{
get
{
unchecked
{
int secondOfDay = (int) (nanoseconds / (int) NanosecondsPerSecond);
return secondOfDay % SecondsPerMinute;
}
}
}
/// <summary>
/// Gets the millisecond of this local time within the second, in the range 0 to 999 inclusive.
/// </summary>
/// <value>The millisecond of this local time within the second, in the range 0 to 999 inclusive.</value>
public int Millisecond
{
get
{
unchecked
{
long milliSecondOfDay = (nanoseconds / (int) NanosecondsPerMillisecond);
return (int) (milliSecondOfDay % MillisecondsPerSecond);
}
}
}
// TODO(optimization): Rewrite for performance?
/// <summary>
/// Gets the tick of this local time within the second, in the range 0 to 9,999,999 inclusive.
/// </summary>
/// <value>The tick of this local time within the second, in the range 0 to 9,999,999 inclusive.</value>
public int TickOfSecond => unchecked((int) (TickOfDay % (int) TicksPerSecond));
/// <summary>
/// Gets the tick of this local time within the day, in the range 0 to 863,999,999,999 inclusive.
/// </summary>
/// <remarks>
/// If the value does not fall on a tick boundary, it will be truncated towards zero.
/// </remarks>
/// <value>The tick of this local time within the day, in the range 0 to 863,999,999,999 inclusive.</value>
public long TickOfDay => nanoseconds / NanosecondsPerTick;
/// <summary>
/// Gets the nanosecond of this local time within the second, in the range 0 to 999,999,999 inclusive.
/// </summary>
/// <value>The nanosecond of this local time within the second, in the range 0 to 999,999,999 inclusive.</value>
public int NanosecondOfSecond => unchecked((int) (nanoseconds % NanosecondsPerSecond));
/// <summary>
/// Gets the nanosecond of this local time within the day, in the range 0 to 86,399,999,999,999 inclusive.
/// </summary>
/// <value>The nanosecond of this local time within the day, in the range 0 to 86,399,999,999,999 inclusive.</value>
public long NanosecondOfDay => nanoseconds;
/// <summary>
/// Creates a new local time by adding a period to an existing time. The period must not contain
/// any date-related units (days etc) with non-zero values.
/// </summary>
/// <param name="time">The time to add the period to</param>
/// <param name="period">The period to add</param>
/// <returns>The result of adding the period to the time, wrapping via midnight if necessary</returns>
public static LocalTime operator +(LocalTime time, Period period)
{
Preconditions.CheckNotNull(period, nameof(period));
Preconditions.CheckArgument(!period.HasDateComponent, nameof(period), "Cannot add a period with a date component to a time");
return time.PlusHours(period.Hours)
.PlusMinutes(period.Minutes)
.PlusSeconds(period.Seconds)
.PlusMilliseconds(period.Milliseconds)
.PlusTicks(period.Ticks)
.PlusNanoseconds(period.Nanoseconds);
}
/// <summary>
/// Adds the specified period to the time. Friendly alternative to <c>operator+()</c>.
/// </summary>
/// <param name="time">The time to add the period to</param>
/// <param name="period">The period to add. Must not contain any (non-zero) date units.</param>
/// <returns>The sum of the given time and period</returns>
public static LocalTime Add(LocalTime time, Period period) => time + period;
/// <summary>
/// Adds the specified period to this time. Fluent alternative to <c>operator+()</c>.
/// </summary>
/// <param name="period">The period to add. Must not contain any (non-zero) date units.</param>
/// <returns>The sum of this time and the given period</returns>
[Pure]
public LocalTime Plus(Period period) => this + period;
/// <summary>
/// Creates a new local time by subtracting a period from an existing time. The period must not contain
/// any date-related units (days etc) with non-zero values.
/// This is a convenience operator over the <see cref="Minus(Period)"/> method.
/// </summary>
/// <param name="time">The time to subtract the period from</param>
/// <param name="period">The period to subtract</param>
/// <returns>The result of subtract the period from the time, wrapping via midnight if necessary</returns>
public static LocalTime operator -(LocalTime time, Period period)
{
Preconditions.CheckNotNull(period, nameof(period));
Preconditions.CheckArgument(!period.HasDateComponent, nameof(period), "Cannot subtract a period with a date component from a time");
return time.PlusHours(-period.Hours)
.PlusMinutes(-period.Minutes)
.PlusSeconds(-period.Seconds)
.PlusMilliseconds(-period.Milliseconds)
.PlusTicks(-period.Ticks)
.PlusNanoseconds(-period.Nanoseconds);
}
/// <summary>
/// Subtracts the specified period from the time. Friendly alternative to <c>operator-()</c>.
/// </summary>
/// <param name="time">The time to subtract the period from</param>
/// <param name="period">The period to subtract. Must not contain any (non-zero) date units.</param>
/// <returns>The result of subtracting the given period from the time.</returns>
public static LocalTime Subtract(LocalTime time, Period period) => time - period;
/// <summary>
/// Subtracts the specified period from this time. Fluent alternative to <c>operator-()</c>.
/// </summary>
/// <param name="period">The period to subtract. Must not contain any (non-zero) date units.</param>
/// <returns>The result of subtracting the given period from this time.</returns>
[Pure]
public LocalTime Minus(Period period) => this - period;
/// <summary>
/// Subtracts one time from another, returning the result as a <see cref="Period"/>.
/// </summary>
/// <remarks>
/// This is simply a convenience operator for calling <see cref="Period.Between(NodaTime.LocalTime,NodaTime.LocalTime)"/>.
/// </remarks>
/// <param name="lhs">The time to subtract from</param>
/// <param name="rhs">The time to subtract</param>
/// <returns>The result of subtracting one time from another.</returns>
public static Period operator -(LocalTime lhs, LocalTime rhs) => Period.Between(rhs, lhs);
/// <summary>
/// Subtracts one time from another, returning the result as a <see cref="Period"/> with units of years, months and days.
/// </summary>
/// <remarks>
/// This is simply a convenience method for calling <see cref="Period.Between(NodaTime.LocalTime,NodaTime.LocalTime)"/>.
/// </remarks>
/// <param name="lhs">The time to subtract from</param>
/// <param name="rhs">The time to subtract</param>
/// <returns>The result of subtracting one time from another.</returns>
public static Period Subtract(LocalTime lhs, LocalTime rhs) => lhs - rhs;
/// <summary>
/// Subtracts the specified time from this time, returning the result as a <see cref="Period"/>.
/// Fluent alternative to <c>operator-()</c>.
/// </summary>
/// <param name="time">The time to subtract from this</param>
/// <returns>The difference between the specified time and this one</returns>
[Pure]
public Period Minus(LocalTime time) => this - time;
/// <summary>
/// Compares two local times for equality.
/// See the type documentation for a description of equality semantics.
/// </summary>
/// <param name="lhs">The first value to compare</param>
/// <param name="rhs">The second value to compare</param>
/// <returns>True if the two times are the same; false otherwise</returns>
public static bool operator ==(LocalTime lhs, LocalTime rhs) => lhs.nanoseconds == rhs.nanoseconds;
/// <summary>
/// Compares two local times for inequality.
/// See the type documentation for a description of equality semantics.
/// </summary>
/// <param name="lhs">The first value to compare</param>
/// <param name="rhs">The second value to compare</param>
/// <returns>False if the two times are the same; true otherwise</returns>
public static bool operator !=(LocalTime lhs, LocalTime rhs) => lhs.nanoseconds != rhs.nanoseconds;
/// <summary>
/// Compares two LocalTime values to see if the left one is strictly earlier than the right one.
/// See the type documentation for a description of ordering semantics.
/// </summary>
/// <param name="lhs">First operand of the comparison</param>
/// <param name="rhs">Second operand of the comparison</param>
/// <returns>true if the <paramref name="lhs"/> is strictly earlier than <paramref name="rhs"/>, false otherwise.</returns>
public static bool operator <(LocalTime lhs, LocalTime rhs) => lhs.nanoseconds < rhs.nanoseconds;
/// <summary>
/// Compares two LocalTime values to see if the left one is earlier than or equal to the right one.
/// See the type documentation for a description of ordering semantics.
/// </summary>
/// <param name="lhs">First operand of the comparison</param>
/// <param name="rhs">Second operand of the comparison</param>
/// <returns>true if the <paramref name="lhs"/> is earlier than or equal to <paramref name="rhs"/>, false otherwise.</returns>
public static bool operator <=(LocalTime lhs, LocalTime rhs) => lhs.nanoseconds <= rhs.nanoseconds;
/// <summary>
/// Compares two LocalTime values to see if the left one is strictly later than the right one.
/// See the type documentation for a description of ordering semantics.
/// </summary>
/// <param name="lhs">First operand of the comparison</param>
/// <param name="rhs">Second operand of the comparison</param>
/// <returns>true if the <paramref name="lhs"/> is strictly later than <paramref name="rhs"/>, false otherwise.</returns>
public static bool operator >(LocalTime lhs, LocalTime rhs) => lhs.nanoseconds > rhs.nanoseconds;
/// <summary>
/// Compares two LocalTime values to see if the left one is later than or equal to the right one.
/// See the type documentation for a description of ordering semantics.
/// </summary>
/// <param name="lhs">First operand of the comparison</param>
/// <param name="rhs">Second operand of the comparison</param>
/// <returns>true if the <paramref name="lhs"/> is later than or equal to <paramref name="rhs"/>, false otherwise.</returns>
public static bool operator >=(LocalTime lhs, LocalTime rhs) => lhs.nanoseconds >= rhs.nanoseconds;
/// <summary>
/// Indicates whether this time is earlier, later or the same as another one.
/// See the type documentation for a description of ordering semantics.
/// </summary>
/// <param name="other">The other date/time to compare this one with</param>
/// <returns>A value less than zero if this time is earlier than <paramref name="other"/>;
/// zero if this time is the same as <paramref name="other"/>; a value greater than zero if this time is
/// later than <paramref name="other"/>.</returns>
public int CompareTo(LocalTime other) => nanoseconds.CompareTo(other.nanoseconds);
/// <summary>
/// Implementation of <see cref="IComparable.CompareTo"/> to compare two LocalTimes.
/// See the type documentation for a description of ordering semantics.
/// </summary>
/// <remarks>
/// This uses explicit interface implementation to avoid it being called accidentally. The generic implementation should usually be preferred.
/// </remarks>
/// <exception cref="ArgumentException"><paramref name="obj"/> is non-null but does not refer to an instance of <see cref="LocalTime"/>.</exception>
/// <param name="obj">The object to compare this value with.</param>
/// <returns>The result of comparing this LocalTime with another one; see <see cref="CompareTo(NodaTime.LocalTime)"/> for general details.
/// If <paramref name="obj"/> is null, this method returns a value greater than 0.
/// </returns>
int IComparable.CompareTo(object obj)
{
if (obj is null)
{
return 1;
}
Preconditions.CheckArgument(obj is LocalTime, nameof(obj), "Object must be of type NodaTime.LocalTime.");
return CompareTo((LocalTime) obj);
}
/// <summary>
/// Returns a hash code for this local time.
/// See the type documentation for a description of equality semantics.
/// </summary>
/// <returns>A hash code for this local time.</returns>
public override int GetHashCode() => nanoseconds.GetHashCode();
/// <summary>
/// Compares this local time with the specified one for equality.
/// See the type documentation for a description of equality semantics.
/// </summary>
/// <param name="other">The other local time to compare this one with</param>
/// <returns>True if the specified time is equal to this one; false otherwise</returns>
public bool Equals(LocalTime other) => this == other;
/// <summary>
/// Compares this local time with the specified reference.
/// See the type documentation for a description of equality semantics.
/// </summary>
/// <param name="obj">The object to compare this one with</param>
/// <returns>True if the specified value is a local time which is equal to this one; false otherwise</returns>
public override bool Equals(object? obj) => obj is LocalTime other && this == other;
/// <summary>
/// Returns a new LocalTime representing the current value with the given number of hours added.
/// </summary>
/// <remarks>
/// If the value goes past the start or end of the day, it wraps - so 11pm plus two hours is 1am, for example.
/// </remarks>
/// <param name="hours">The number of hours to add</param>
/// <returns>The current value plus the given number of hours.</returns>
[Pure]
public LocalTime PlusHours(long hours) => TimePeriodField.Hours.Add(this, hours);
/// <summary>
/// Returns a new LocalTime representing the current value with the given number of minutes added.
/// </summary>
/// <remarks>
/// If the value goes past the start or end of the day, it wraps - so 11pm plus 120 minutes is 1am, for example.
/// </remarks>
/// <param name="minutes">The number of minutes to add</param>
/// <returns>The current value plus the given number of minutes.</returns>
[Pure]
public LocalTime PlusMinutes(long minutes) => TimePeriodField.Minutes.Add(this, minutes);
/// <summary>
/// Returns a new LocalTime representing the current value with the given number of seconds added.
/// </summary>
/// <remarks>
/// If the value goes past the start or end of the day, it wraps - so 11:59pm plus 120 seconds is 12:01am, for example.
/// </remarks>
/// <param name="seconds">The number of seconds to add</param>
/// <returns>The current value plus the given number of seconds.</returns>
[Pure]
public LocalTime PlusSeconds(long seconds) => TimePeriodField.Seconds.Add(this, seconds);
/// <summary>
/// Returns a new LocalTime representing the current value with the given number of milliseconds added.
/// </summary>
/// <param name="milliseconds">The number of milliseconds to add</param>
/// <returns>The current value plus the given number of milliseconds.</returns>
[Pure]
public LocalTime PlusMilliseconds(long milliseconds) => TimePeriodField.Milliseconds.Add(this, milliseconds);
/// <summary>
/// Returns a new LocalTime representing the current value with the given number of ticks added.
/// </summary>
/// <param name="ticks">The number of ticks to add</param>
/// <returns>The current value plus the given number of ticks.</returns>
[Pure]
public LocalTime PlusTicks(long ticks) => TimePeriodField.Ticks.Add(this, ticks);
/// <summary>
/// Returns a new LocalTime representing the current value with the given number of nanoseconds added.
/// </summary>
/// <param name="nanoseconds">The number of nanoseconds to add</param>
/// <returns>The current value plus the given number of ticks.</returns>
[Pure]
public LocalTime PlusNanoseconds(long nanoseconds) => TimePeriodField.Nanoseconds.Add(this, nanoseconds);
/// <summary>
/// Returns this time, with the given adjuster applied to it.
/// </summary>
/// <remarks>
/// If the adjuster attempts to construct an invalid time, any exception thrown by
/// that construction attempt will be propagated through this method.
/// </remarks>
/// <param name="adjuster">The adjuster to apply.</param>
/// <returns>The adjusted time.</returns>
[Pure]
public LocalTime With(Func<LocalTime, LocalTime> adjuster) =>
Preconditions.CheckNotNull(adjuster, nameof(adjuster)).Invoke(this);
/// <summary>
/// Returns an <see cref="OffsetTime"/> for this time-of-day with the given offset.
/// </summary>
/// <remarks>This method is purely a convenient alternative to calling the <see cref="OffsetTime"/> constructor directly.</remarks>
/// <param name="offset">The offset to apply.</param>
/// <returns>The result of this time-of-day offset by the given amount.</returns>
[Pure]
public OffsetTime WithOffset(Offset offset) => new OffsetTime(this, offset);
/// <summary>
/// Combines this <see cref="LocalTime"/> with the given <see cref="LocalDate"/>
/// into a single <see cref="LocalDateTime"/>.
/// Fluent alternative to <c>operator+()</c>.
/// </summary>
/// <param name="date">The date to combine with this time</param>
/// <returns>The <see cref="LocalDateTime"/> representation of the given time on this date</returns>
[Pure]
public LocalDateTime On(LocalDate date) => date + this;
/// <summary>
/// Deconstruct this time into its components.
/// </summary>
/// <param name="hour">The hour of the time.</param>
/// <param name="minute">The minute of the hour.</param>
/// <param name="second">The second within the minute.</param>
[Pure]
public void Deconstruct(out int hour, out int minute, out int second)
{
hour = Hour;
minute = Minute;
second = Second;
}
/// <summary>
/// Returns the later time of the given two.
/// </summary>
/// <param name="x">The first time to compare.</param>
/// <param name="y">The second time to compare.</param>
/// <returns>The later instant of <paramref name="x"/> or <paramref name="y"/>.</returns>
public static LocalTime Max(LocalTime x, LocalTime y)
{
return x > y ? x : y;
}
/// <summary>
/// Returns the earlier time of the given two.
/// </summary>
/// <param name="x">The first time to compare.</param>
/// <param name="y">The second time to compare.</param>
/// <returns>The earlier time of <paramref name="x"/> or <paramref name="y"/>.</returns>
public static LocalTime Min(LocalTime x, LocalTime y) => x < y ? x : y;
#region Formatting
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>
/// The value of the current instance in the default format pattern ("T"), using the current thread's
/// culture to obtain a format provider.
/// </returns>
public override string ToString() => LocalTimePattern.BclSupport.Format(this, null, CultureInfo.CurrentCulture);
/// <summary>
/// Formats the value of the current instance using the specified pattern.
/// </summary>
/// <returns>
/// A <see cref="T:System.String" /> containing the value of the current instance in the specified format.
/// </returns>
/// <param name="patternText">The <see cref="T:System.String" /> specifying the pattern to use,
/// or null to use the default format pattern ("T").
/// </param>
/// <param name="formatProvider">The <see cref="T:System.IFormatProvider" /> to use when formatting the value,
/// or null to use the current thread's culture to obtain a format provider.
/// </param>
/// <filterpriority>2</filterpriority>
public string ToString(string? patternText, IFormatProvider? formatProvider) =>
LocalTimePattern.BclSupport.Format(this, patternText, formatProvider);
#endregion Formatting
#region XML serialization
/// <inheritdoc />
XmlSchema IXmlSerializable.GetSchema() => null!; // TODO(nullable): Return XmlSchema? when docfx works with that
/// <inheritdoc />
void IXmlSerializable.ReadXml(XmlReader reader)
{
Preconditions.CheckNotNull(reader, nameof(reader));
var pattern = LocalTimePattern.ExtendedIso;
string text = reader.ReadElementContentAsString();
Unsafe.AsRef(this) = pattern.Parse(text).Value;
}
/// <inheritdoc />
void IXmlSerializable.WriteXml(XmlWriter writer)
{
Preconditions.CheckNotNull(writer, nameof(writer));
writer.WriteString(LocalTimePattern.ExtendedIso.Format(this));
}
#endregion
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Textures;
using osu.Framework.Input;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Framework.Utils;
using osu.Game.Graphics;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects.Drawables;
using osu.Game.Rulesets.Osu.UI;
using osu.Game.Screens.Play;
using osu.Game.Skinning;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Rulesets.Osu.Skinning.Legacy
{
public class LegacyCursorParticles : CompositeDrawable, IKeyBindingHandler<OsuAction>
{
public bool Active => breakSpewer?.Active.Value == true || kiaiSpewer?.Active.Value == true;
private LegacyCursorParticleSpewer breakSpewer;
private LegacyCursorParticleSpewer kiaiSpewer;
[Resolved(canBeNull: true)]
private Player player { get; set; }
[Resolved(canBeNull: true)]
private OsuPlayfield playfield { get; set; }
[Resolved(canBeNull: true)]
private GameplayState gameplayState { get; set; }
[BackgroundDependencyLoader]
private void load(ISkinSource skin, OsuColour colours)
{
var texture = skin.GetTexture("star2");
var starBreakAdditive = skin.GetConfig<OsuSkinColour, Color4>(OsuSkinColour.StarBreakAdditive)?.Value ?? new Color4(255, 182, 193, 255);
if (texture != null)
{
// stable "magic ratio". see OsuPlayfieldAdjustmentContainer for full explanation.
texture.ScaleAdjust *= 1.6f;
}
InternalChildren = new[]
{
breakSpewer = new LegacyCursorParticleSpewer(texture, 20)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Colour = starBreakAdditive,
Direction = SpewDirection.None,
},
kiaiSpewer = new LegacyCursorParticleSpewer(texture, 60)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Colour = starBreakAdditive,
Direction = SpewDirection.None,
},
};
if (player != null)
((IBindable<bool>)breakSpewer.Active).BindTo(player.IsBreakTime);
}
protected override void Update()
{
if (playfield == null || gameplayState == null) return;
DrawableHitObject kiaiHitObject = null;
// Check whether currently in a kiai section first. This is only done as an optimisation to avoid enumerating AliveObjects when not necessary.
if (gameplayState.Beatmap.ControlPointInfo.EffectPointAt(Time.Current).KiaiMode)
kiaiHitObject = playfield.HitObjectContainer.AliveObjects.FirstOrDefault(isTracking);
kiaiSpewer.Active.Value = kiaiHitObject != null;
}
private bool isTracking(DrawableHitObject h)
{
if (!h.HitObject.Kiai)
return false;
switch (h)
{
case DrawableSlider slider:
return slider.Tracking.Value;
case DrawableSpinner spinner:
return spinner.RotationTracker.Tracking;
}
return false;
}
public bool OnPressed(KeyBindingPressEvent<OsuAction> e)
{
handleInput(e.Action, true);
return false;
}
public void OnReleased(KeyBindingReleaseEvent<OsuAction> e)
{
handleInput(e.Action, false);
}
private bool leftPressed;
private bool rightPressed;
private void handleInput(OsuAction action, bool pressed)
{
switch (action)
{
case OsuAction.LeftButton:
leftPressed = pressed;
break;
case OsuAction.RightButton:
rightPressed = pressed;
break;
}
if (leftPressed && rightPressed)
breakSpewer.Direction = SpewDirection.Omni;
else if (leftPressed)
breakSpewer.Direction = SpewDirection.Left;
else if (rightPressed)
breakSpewer.Direction = SpewDirection.Right;
else
breakSpewer.Direction = SpewDirection.None;
}
private class LegacyCursorParticleSpewer : ParticleSpewer, IRequireHighFrequencyMousePosition
{
private const int particle_duration_min = 300;
private const int particle_duration_max = 1000;
public SpewDirection Direction { get; set; }
protected override bool CanSpawnParticles => base.CanSpawnParticles && cursorScreenPosition.HasValue;
protected override float ParticleGravity => 240;
public LegacyCursorParticleSpewer(Texture texture, int perSecond)
: base(texture, perSecond, particle_duration_max)
{
Active.BindValueChanged(_ => resetVelocityCalculation());
}
private Vector2? cursorScreenPosition;
private Vector2 cursorVelocity;
private const double max_velocity_frame_length = 15;
private double velocityFrameLength;
private Vector2 totalPosDifference;
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => true;
protected override bool OnMouseMove(MouseMoveEvent e)
{
if (cursorScreenPosition == null)
{
cursorScreenPosition = e.ScreenSpaceMousePosition;
return base.OnMouseMove(e);
}
// calculate cursor velocity.
totalPosDifference += e.ScreenSpaceMousePosition - cursorScreenPosition.Value;
cursorScreenPosition = e.ScreenSpaceMousePosition;
velocityFrameLength += Math.Abs(Clock.ElapsedFrameTime);
if (velocityFrameLength > max_velocity_frame_length)
{
cursorVelocity = totalPosDifference / (float)velocityFrameLength;
totalPosDifference = Vector2.Zero;
velocityFrameLength = 0;
}
return base.OnMouseMove(e);
}
private void resetVelocityCalculation()
{
cursorScreenPosition = null;
totalPosDifference = Vector2.Zero;
velocityFrameLength = 0;
}
protected override FallingParticle CreateParticle() =>
new FallingParticle
{
StartPosition = ToLocalSpace(cursorScreenPosition ?? Vector2.Zero),
Duration = RNG.NextSingle(particle_duration_min, particle_duration_max),
StartAngle = (float)(RNG.NextDouble() * 4 - 2),
EndAngle = RNG.NextSingle(-2f, 2f),
EndScale = RNG.NextSingle(2f),
Velocity = getVelocity(),
};
private Vector2 getVelocity()
{
Vector2 velocity = Vector2.Zero;
switch (Direction)
{
case SpewDirection.Left:
velocity = new Vector2(
RNG.NextSingle(-460f, 0),
RNG.NextSingle(-40f, 40f)
);
break;
case SpewDirection.Right:
velocity = new Vector2(
RNG.NextSingle(0, 460f),
RNG.NextSingle(-40f, 40f)
);
break;
case SpewDirection.Omni:
velocity = new Vector2(
RNG.NextSingle(-460f, 460f),
RNG.NextSingle(-160f, 160f)
);
break;
}
velocity += cursorVelocity * 40;
return velocity;
}
}
private enum SpewDirection
{
None,
Left,
Right,
Omni,
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using Microsoft.Test.ModuleCore;
using System.IO;
namespace CoreXml.Test.XLinq
{
public partial class XNodeBuilderFunctionalTests : TestModule
{
public partial class XNodeBuilderTests : XLinqTestCase
{
public partial class NamespacehandlingWriterSanity : XLinqTestCase
{
#region helpers
private string SaveXElementUsingXmlWriter(XElement elem, NamespaceHandling nsHandling)
{
StringWriter sw = new StringWriter();
using (XmlWriter w = XmlWriter.Create(sw, new XmlWriterSettings() { NamespaceHandling = nsHandling, OmitXmlDeclaration = true }))
{
elem.WriteTo(w);
}
sw.Dispose();
return sw.ToString();
}
#endregion
//[Variation(Desc = "1 level down", Priority = 0, Params = new object[] { "<p:A xmlns:p='nsp'><p:B xmlns:p='nsp'><p:C xmlns:p='nsp'/></p:B></p:A>" })]
//[Variation(Desc = "1 level down II.", Priority = 0, Params = new object[] { "<A><p:B xmlns:p='nsp'><p:C xmlns:p='nsp'/></p:B></A>" })] // start at not root node
//[Variation(Desc = "2 levels down", Priority = 1, Params = new object[] { "<p:A xmlns:p='nsp'><B><p:C xmlns:p='nsp'/></B></p:A>" })]
//[Variation(Desc = "2 levels down II.", Priority = 1, Params = new object[] { "<p:A xmlns:p='nsp'><B><C xmlns:p='nsp'/></B></p:A>" })]
//[Variation(Desc = "2 levels down III.", Priority = 1, Params = new object[] { "<A xmlns:p='nsp'><B><p:C xmlns:p='nsp'/></B></A>" })]
//[Variation(Desc = "Siblings", Priority = 2, Params = new object[] { "<A xmlns:p='nsp'><p:B xmlns:p='nsp'/><C xmlns:p='nsp'/><p:C xmlns:p='nsp'/></A>" })]
//[Variation(Desc = "Children", Priority = 2, Params = new object[] { "<A xmlns:p='nsp'><p:B xmlns:p='nsp'><C xmlns:p='nsp'><p:C xmlns:p='nsp'/></C></p:B></A>" })]
//[Variation(Desc = "Xml namespace I.", Priority = 3, Params = new object[] { "<A xmlns:xml='http://www.w3.org/XML/1998/namespace'/>" })]
//[Variation(Desc = "Xml namespace II.", Priority = 3, Params = new object[] { "<p:A xmlns:p='nsp'><p:B xmlns:p='nsp'><p:C xmlns:p='nsp' xmlns:xml='http://www.w3.org/XML/1998/namespace'/></p:B></p:A>" })]
//[Variation(Desc = "Xml namespace III.", Priority = 3, Params = new object[] { "<p:A xmlns:p='nsp'><p:B xmlns:xml='http://www.w3.org/XML/1998/namespace' xmlns:p='nsp'><p:C xmlns:p='nsp' xmlns:xml='http://www.w3.org/XML/1998/namespace'/></p:B></p:A>" })]
//[Variation(Desc = "Default namespaces", Priority = 1, Params = new object[] { "<A xmlns='nsp'><p:B xmlns:p='nsp'><C xmlns='nsp' /></p:B></A>" })]
//[Variation(Desc = "Not used NS declarations", Priority = 2, Params = new object[] { "<A xmlns='nsp' xmlns:u='not-used'><p:B xmlns:p='nsp'><C xmlns:u='not-used' xmlns='nsp' /></p:B></A>" })]
//[Variation(Desc = "SameNS, different prefix", Priority = 2, Params = new object[] { "<p:A xmlns:p='nsp'><B xmlns:q='nsp'><p:C xmlns:p='nsp'/></B></p:A>" })]
public void testFromTheRootNodeSimple()
{
string xml = CurrentChild.Params[0] as string;
XElement elem = XElement.Parse(xml);
// Write using XmlWriter in duplicate namespace decl. removal mode
string removedByWriter = SaveXElementUsingXmlWriter(elem, NamespaceHandling.OmitDuplicates);
// Remove the namespace decl. duplicates from the Xlinq tree
(from a in elem.DescendantsAndSelf().Attributes()
where a.IsNamespaceDeclaration && ((a.Name.LocalName == "xml" && (string)a == XNamespace.Xml.NamespaceName) ||
(from parentDecls in a.Parent.Ancestors().Attributes(a.Name)
where parentDecls.IsNamespaceDeclaration && (string)parentDecls == (string)a
select parentDecls).Any()
)
select a).ToList().Remove();
// Write XElement using XmlWriter without omitting
string removedByManual = SaveXElementUsingXmlWriter(elem, NamespaceHandling.Default);
ReaderDiff.Compare(removedByWriter, removedByManual);
}
//[Variation(Desc = "Default ns parent autogenerated", Priority = 1)]
public void testFromTheRootNodeTricky()
{
XElement e = new XElement("{nsp}A", new XElement("{nsp}B", new XAttribute("xmlns", "nsp")));
ReaderDiff.Compare(SaveXElementUsingXmlWriter(e, NamespaceHandling.OmitDuplicates), "<A xmlns='nsp'><B/></A>");
}
//[Variation(Desc = "Conflicts: NS redefinition", Priority = 2, Params = new object[] { "<p:A xmlns:p='nsp'><p:B xmlns:p='ns-other'><p:C xmlns:p='nsp'><D xmlns:p='nsp'/></p:C></p:B></p:A>",
// "<p:A xmlns:p='nsp'><p:B xmlns:p='ns-other'><p:C xmlns:p='nsp'><D/></p:C></p:B></p:A>" })]
//[Variation(Desc = "Conflicts: NS redefinition, default NS", Priority = 2, Params = new object[] { "<A xmlns='nsp'><B xmlns='ns-other'><C xmlns='nsp'><D xmlns='nsp'/></C></B></A>",
// "<A xmlns='nsp'><B xmlns='ns-other'><C xmlns='nsp'><D/></C></B></A>" })]
//[Variation(Desc = "Conflicts: NS redefinition, default NS II.", Priority = 2, Params = new object[] { "<A xmlns=''><B xmlns='ns-other'><C xmlns=''><D xmlns=''/></C></B></A>",
// "<A><B xmlns='ns-other'><C xmlns=''><D/></C></B></A>" })]
//[Variation(Desc = "Conflicts: NS undeclaration, default NS", Priority = 2, Params = new object[] { "<A xmlns='nsp'><B xmlns=''><C xmlns='nsp'><D xmlns='nsp'/></C></B></A>",
// "<A xmlns='nsp'><B xmlns=''><C xmlns='nsp'><D/></C></B></A>" })]
public void testConflicts()
{
XElement e1 = XElement.Parse(CurrentChild.Params[0] as string);
ReaderDiff.Compare(SaveXElementUsingXmlWriter(e1, NamespaceHandling.OmitDuplicates), CurrentChild.Params[1] as string);
}
//[Variation(Desc = "Not from root", Priority = 1)]
public void testFromChildNode1()
{
XElement e = new XElement("root",
new XAttribute(XNamespace.Xmlns + "p1", "nsp"),
new XElement("{nsp}A",
new XElement("{nsp}B",
new XAttribute("xmlns", "nsp"))));
ReaderDiff.Compare(SaveXElementUsingXmlWriter(e.Element("{nsp}A"), NamespaceHandling.OmitDuplicates), "<p1:A xmlns:p1='nsp'><B xmlns='nsp'/></p1:A>");
}
//[Variation(Desc = "Not from root II.", Priority = 1)]
public void testFromChildNode2()
{
XElement e = new XElement("root",
new XAttribute(XNamespace.Xmlns + "p1", "nsp"),
new XElement("{nsp}A",
new XElement("{nsp}B",
new XAttribute(XNamespace.Xmlns + "p1", "nsp"))));
ReaderDiff.Compare(SaveXElementUsingXmlWriter(e.Element("{nsp}A"), NamespaceHandling.OmitDuplicates), "<p1:A xmlns:p1='nsp'><p1:B/></p1:A>");
}
//[Variation(Desc = "Not from root III.", Priority = 2)]
public void testFromChildNode3()
{
XElement e = new XElement("root",
new XAttribute(XNamespace.Xmlns + "p1", "nsp"),
new XElement("{nsp}A",
new XElement("{nsp}B",
new XAttribute(XNamespace.Xmlns + "p1", "nsp"))));
ReaderDiff.Compare(SaveXElementUsingXmlWriter(e.Descendants("{nsp}B").FirstOrDefault(), NamespaceHandling.OmitDuplicates), "<p1:B xmlns:p1='nsp'/>");
}
//[Variation(Desc = "Not from root IV.", Priority = 2)]
public void testFromChildNode4()
{
XElement e = new XElement("root",
new XAttribute(XNamespace.Xmlns + "p1", "nsp"),
new XElement("{nsp}A",
new XElement("{nsp}B")));
ReaderDiff.Compare(SaveXElementUsingXmlWriter(e.Descendants("{nsp}B").FirstOrDefault(), NamespaceHandling.OmitDuplicates), "<p1:B xmlns:p1='nsp'/>");
}
//[Variation(Desc = "Write into used reader I.", Priority = 0, Params = new object[] { "<A xmlns:p1='nsp'/>", "<p1:root xmlns:p1='nsp'><A/></p1:root>" })]
//[Variation(Desc = "Write into used reader II.", Priority = 2, Params = new object[] { "<p1:A xmlns:p1='nsp'/>", "<p1:root xmlns:p1='nsp'><p1:A/></p1:root>" })]
//[Variation(Desc = "Write into used reader III.", Priority = 2, Params = new object[] { "<p1:A xmlns:p1='nsp'><B xmlns:p1='nsp'/></p1:A>", "<p1:root xmlns:p1='nsp'><p1:A><B/></p1:A></p1:root>" })]
public void testIntoOpenedWriter()
{
XElement e = XElement.Parse(CurrentChild.Params[0] as string);
StringWriter sw = new StringWriter();
using (XmlWriter w = XmlWriter.Create(sw, new XmlWriterSettings() { NamespaceHandling = NamespaceHandling.OmitDuplicates, OmitXmlDeclaration = true }))
{
// prepare writer
w.WriteStartDocument();
w.WriteStartElement("p1", "root", "nsp");
// write xelement
e.WriteTo(w);
// close the prep. lines
w.WriteEndElement();
w.WriteEndDocument();
}
sw.Dispose();
ReaderDiff.Compare(sw.ToString(), CurrentChild.Params[1] as string);
}
//[Variation(Desc = "Write into used reader I. (def. ns.)", Priority = 0, Params = new object[] { "<A xmlns='nsp'/>", "<root xmlns='nsp'><A/></root>" })]
//[Variation(Desc = "Write into used reader II. (def. ns.)", Priority = 2, Params = new object[] { "<A xmlns='ns-other'><B xmlns='nsp'><C xmlns='nsp'/></B></A>",
// "<root xmlns='nsp'><A xmlns='ns-other'><B xmlns='nsp'><C/></B></A></root>" })]
public void testIntoOpenedWriterDefaultNS()
{
XElement e = XElement.Parse(CurrentChild.Params[0] as string);
StringWriter sw = new StringWriter();
using (XmlWriter w = XmlWriter.Create(sw, new XmlWriterSettings() { NamespaceHandling = NamespaceHandling.OmitDuplicates, OmitXmlDeclaration = true }))
{
// prepare writer
w.WriteStartDocument();
w.WriteStartElement("", "root", "nsp");
// write xelement
e.WriteTo(w);
// close the prep. lines
w.WriteEndElement();
w.WriteEndDocument();
}
sw.Dispose();
ReaderDiff.Compare(sw.ToString(), CurrentChild.Params[1] as string);
}
//[Variation(Desc = "Write into used reader (Xlinq lookup + existing hint in the Writer; different prefix)",
// Priority = 2,
// Params = new object[] { "<p1:root xmlns:p1='nsp'><p2:B xmlns:p2='nsp'/></p1:root>" })]
public void testIntoOpenedWriterXlinqLookup1()
{
XElement e = new XElement("A",
new XAttribute(XNamespace.Xmlns + "p2", "nsp"),
new XElement("{nsp}B"));
StringWriter sw = new StringWriter();
using (XmlWriter w = XmlWriter.Create(sw, new XmlWriterSettings() { NamespaceHandling = NamespaceHandling.OmitDuplicates, OmitXmlDeclaration = true }))
{
// prepare writer
w.WriteStartDocument();
w.WriteStartElement("p1", "root", "nsp");
// write xelement
e.Element("{nsp}B").WriteTo(w);
// close the prep. lines
w.WriteEndElement();
w.WriteEndDocument();
}
sw.Dispose();
ReaderDiff.Compare(sw.ToString(), CurrentChild.Params[0] as string);
}
//[Variation(Desc = "Write into used reader (Xlinq lookup + existing hint in the Writer; same prefix)",
// Priority = 2,
// Params = new object[] { "<p1:root xmlns:p1='nsp'><p1:B /></p1:root>" })]
public void testIntoOpenedWriterXlinqLookup2()
{
XElement e = new XElement("A",
new XAttribute(XNamespace.Xmlns + "p1", "nsp"),
new XElement("{nsp}B"));
StringWriter sw = new StringWriter();
using (XmlWriter w = XmlWriter.Create(sw, new XmlWriterSettings() { NamespaceHandling = NamespaceHandling.OmitDuplicates, OmitXmlDeclaration = true }))
{
// prepare writer
w.WriteStartDocument();
w.WriteStartElement("p1", "root", "nsp");
// write xelement
e.Element("{nsp}B").WriteTo(w);
// close the prep. lines
w.WriteEndElement();
w.WriteEndDocument();
}
sw.Dispose();
ReaderDiff.Compare(sw.ToString(), CurrentChild.Params[0] as string);
}
}
}
}
}
| |
/*
Copyright 2013 Google Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Xunit;
using Google.Apis.Discovery;
using Google.Apis.Http;
using Google.Apis.Json;
using Google.Apis.Requests;
using Google.Apis.Services;
using Google.Apis.Tests;
using Google.Apis.Util;
namespace Google.Apis.Tests.Apis.Services
{
/// <summary>Test for the BaseClientService class.</summary>
public class BaseClientServiceTest
{
/// <summary>A Json schema for testing serialization/deserialization.</summary>
internal class MockJsonSchema : IDirectResponseSchema
{
[JsonProperty("kind")]
public string Kind { get; set; }
[JsonProperty("longUrl")]
public string LongURL { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
public RequestError Error { get; set; }
public string ETag { get; set; }
}
/// <summary>Validates the deserialization result.</summary>
private void CheckDeserializationResult(MockJsonSchema result)
{
Assert.NotNull(result);
Assert.Equal(result.Kind, Is.EqualTo("urlshortener#url"));
Assert.Equal(result.LongURL, Is.EqualTo("http://google.com/"));
Assert.Null(result.Status);
}
/// <summary>Creates a client service for the given features.</summary>
private IClientService CreateClientService(Features? features = null)
{
var client = new MockClientService();
if (features.HasValue)
{
client.SetFeatures(new[] { features.Value.GetStringValue() });
}
return client;
}
/// <summary>This tests deserialization with data wrapping.</summary>
[Fact]
public void TestDeserialization_WithDataWrapping()
{
const string Response =
@"{ ""data"" :
{
""kind"": ""urlshortener#url"",
""longUrl"": ""http://google.com/"",
}
}";
var client = CreateClientService(Features.LegacyDataResponse);
// Check that the default serializer is set.
Assert.IsType<NewtonsoftJsonSerializer>(client.Serializer);
// Check that the response is decoded correctly.
// TODO(neil-119): verify UTF-8 or UTF-16LE on Linux/Mac
var stream = new MemoryStream(Encoding.UTF8.GetBytes(Response));
var response = new HttpResponseMessage { Content = new StreamContent(stream) };
CheckDeserializationResult(client.DeserializeResponse<MockJsonSchema>(response).Result);
}
/// <summary>This tests Deserialization without data wrapping.</summary>
[Fact]
public void TestDeserialization_WithoutDataWrapping()
{
const string Response = @"{""kind"":""urlshortener#url"",""longUrl"":""http://google.com/""}";
// by default the request provider doesn't contain the LegacyDataResponse
var client = CreateClientService();
// Check that the default serializer is set
Assert.IsType<NewtonsoftJsonSerializer>(client.Serializer);
// Check that the response is decoded correctly
// TODO(neil-119): verify UTF-8 or UTF-16LE on Linux/Mac
var stream = new MemoryStream(Encoding.UTF8.GetBytes(Response));
var response = new HttpResponseMessage { Content = new StreamContent(stream) };
CheckDeserializationResult(client.DeserializeResponse<MockJsonSchema>(response).Result);
}
/// <summary>Tests serialization with data wrapping.</summary>
[Fact]
public void TestSerialization_WithDataWrapping()
{
const string Response =
"{\"data\":{\"kind\":\"urlshortener#url\",\"longUrl\":\"http://google.com/\"}}";
MockJsonSchema schema = new MockJsonSchema();
schema.Kind = "urlshortener#url";
schema.LongURL = "http://google.com/";
var client = CreateClientService(Features.LegacyDataResponse);
// Check if a response is serialized correctly
string result = client.SerializeObject(schema);
Assert.Equal(Response, result);
}
/// <summary>Tests serialization without data wrapping.</summary>
[Fact]
public void TestSerialization_WithoutDataWrapping()
{
const string Response = @"{""kind"":""urlshortener#url"",""longUrl"":""http://google.com/""}";
MockJsonSchema schema = new MockJsonSchema();
schema.Kind = "urlshortener#url";
schema.LongURL = "http://google.com/";
var client = CreateClientService();
// Check if a response is serialized correctly.
string result = client.SerializeObject(schema);
Assert.Equal(Response, result);
}
/// <summary>
/// Confirms that the serializer won't do anything if a string is the requested response type.
/// </summary>
[Fact]
public void TestDeserializationString()
{
const string Response = @"{""kind"":""urlshortener#url"",""longUrl"":""http://google.com/""}";
MockClientService client = new MockClientService();
// Check that the response is decoded correctly
// TODO(neil-119): verify UTF-8 or UTF-16LE on Linux/Mac
var stream = new MemoryStream(Encoding.UTF8.GetBytes(Response));
var response = new HttpResponseMessage { Content = new StreamContent(stream) };
string result = client.DeserializeResponse<string>(response).Result;
Assert.Equal(Response, result);
}
/// <summary>Tests deserialization for server error response.</summary>
[Theory]
[InlineData(Features.LegacyDataResponse)]
[InlineData(null)]
public void TestErrorDeserialization(object features)
{
const string ErrorResponse =
@"{
""error"": {
""errors"": [
{
""domain"": ""global"",
""reason"": ""required"",
""message"": ""Required"",
""locationType"": ""parameter"",
""location"": ""resource.longUrl""
}
],
""code"": 400,
""message"": ""Required""
}
}";
var client = CreateClientService((Features?)features);
// TODO(neil-119): verify UTF-8 or UTF-16LE on Linux/Mac
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(ErrorResponse)))
{
var response = new HttpResponseMessage { Content = new StreamContent(stream) };
RequestError error = client.DeserializeError(response).Result;
Assert.Equal(400, error.Code);
Assert.Equal("Required", error.Message);
Assert.Equal(1, error.Errors.Count);
}
}
#region Authentication
/// <summary>
/// A mock authentication message handler which returns an unauthorized response in the first call, and a
/// successful response in the second.
/// </summary>
class MockAuthenticationMessageHandler : CountableMessageHandler
{
internal static string FirstToken = "invalid";
internal static string SecondToken = "valid";
protected override Task<HttpResponseMessage> SendAsyncCore(HttpRequestMessage request,
CancellationToken cancellationToken)
{
TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
switch (Calls)
{
case 1:
Assert.Equal(request.Headers.GetValues("Authorization").Count(), Is.EqualTo(1));
Assert.Equal(request.Headers.GetValues("Authorization").First(), Is.EqualTo(FirstToken));
tcs.SetResult(new HttpResponseMessage
{
StatusCode = System.Net.HttpStatusCode.Unauthorized
});
break;
case 2:
Assert.Equal(request.Headers.GetValues("Authorization").Count(), Is.EqualTo(1));
Assert.Equal(request.Headers.GetValues("Authorization").First(), Is.EqualTo(SecondToken));
tcs.SetResult(new HttpResponseMessage());
break;
default:
throw new Exception("There should be only two calls");
}
return tcs.Task;
}
}
#endregion
#region Constructor
/// <summary>
/// Tests the default values of <seealso cref="Google.Apis.Services.BaseClientService"/>
/// </summary>
[Fact]
public void Constructor_DefaultValues()
{
var service = new MockClientService(new BaseClientService.Initializer());
Assert.NotNull(service.HttpClient);
Assert.Null(service.HttpClientInitializer);
Assert.True(service.GZipEnabled);
// Back-off handler for unsuccessful response (503) is added by default.
Assert.Equal(service.HttpClient.MessageHandler.UnsuccessfulResponseHandlers.Count, Is.EqualTo(1));
Assert.IsAssignableFrom<BackOffHandler>(service.HttpClient.MessageHandler.UnsuccessfulResponseHandlers[0]);
// An execute interceptors is expected (for handling GET requests with URLs that are too long)
Assert.Equal(service.HttpClient.MessageHandler.ExecuteInterceptors.Count, Is.EqualTo(1));
Assert.IsAssignableFrom<MaxUrlLengthInterceptor>(service.HttpClient.MessageHandler.ExecuteInterceptors[0]);
}
#endregion
private const uint DefaultMaxUrlLength = BaseClientService.DefaultMaxUrlLength;
/// <summary>
/// Verifies that URLs over 2K characters on GET requests are correctly translated to a POST request.
/// </summary>
[Fact]
public void TestGetWithUrlTooLongByDefault()
{
// Build a query string such that the whole URI adds up to 2049 characters
var query = "q=" + new String('x', 1020) + "&x=" + new String('y', 1000);
var uri = "http://www.example.com/";
var requestUri = uri + "?" + query;
var request = new HttpRequestMessage(HttpMethod.Get, requestUri);
var messageHandler = new MockMessageHandler();
using (var service = new MockClientService(new BaseClientService.Initializer()
{
HttpClientFactory = new MockHttpClientFactory(messageHandler)
}))
{
service.HttpClient.SendAsync(request);
// Confirm the test URI is one character too long.
Assert.Equal((long)requestUri.Length, (long)Is.EqualTo(DefaultMaxUrlLength + 1));
// Confirm the request was modified correctly:
Assert.Equal(request.Method, Is.EqualTo(HttpMethod.Post));
Assert.Equal(request.Headers.GetValues("X-HTTP-Method-Override").Single(), Is.EqualTo("GET"));
Assert.Equal(request.Content.Headers.ContentType, Is.EqualTo(new MediaTypeHeaderValue("application/x-www-form-urlencoded")));
Assert.Equal(request.RequestUri, Is.EqualTo(new Uri(uri)));
Assert.Equal(messageHandler.RequestContent, Is.EqualTo(query));
}
}
/// <summary>
/// Verifies that URLs of great lengths on GET requests are NOT translated to a POST request when the user
/// sets the <c>maxUrlLength = 0</c>.
/// </summary>
[Fact]
public void TestGetWithUrlMaxLengthDisabled()
{
var query = "q=" + new String('x', 5000) + "&x=" + new String('y', 6000);
var uri = "http://www.example.com/";
var requestUri = uri + "?" + query;
var request = new HttpRequestMessage(HttpMethod.Get, requestUri);
var messageHandler = new MockMessageHandler();
var initializer = (new BaseClientService.Initializer
{
HttpClientFactory = new MockHttpClientFactory(messageHandler),
MaxUrlLength = 0
});
using (var service = new MockClientService(initializer))
{
service.HttpClient.SendAsync(request);
// Confirm the request was not modified.
Assert.Equal(request.RequestUri.ToString().Length, Is.EqualTo(requestUri.Length));
Assert.Equal(request.Method, Is.EqualTo(HttpMethod.Get));
Assert.False(request.Headers.Contains("X-HTTP-Method-Override"));
Assert.Null(request.Content);
Assert.Equal(request.RequestUri, Is.EqualTo(new Uri(requestUri)));
}
}
}
}
| |
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace ZXing.Client.Result
{
/// <summary> <p>Abstract class representing the result of decoding a barcode, as more than
/// a String -- as some type of structured data. This might be a subclass which represents
/// a URL, or an e-mail address. {@link #parseResult(com.google.zxing.Result)} will turn a raw
/// decoded string into the most appropriate type of structured representation.</p>
///
/// <p>Thanks to Jeff Griffin for proposing rewrite of these classes that relies less
/// on exception-based mechanisms during parsing.</p>
/// </summary>
/// <author>Sean Owen</author>
public abstract class ResultParser
{
private static readonly ResultParser[] PARSERS = {
new BookmarkDoCoMoResultParser(),
new AddressBookDoCoMoResultParser(),
new EmailDoCoMoResultParser(),
new AddressBookAUResultParser(),
new VCardResultParser(),
new BizcardResultParser(),
new VEventResultParser(),
new EmailAddressResultParser(),
new SMTPResultParser(),
new TelResultParser(),
new SMSMMSResultParser(),
new SMSTOMMSTOResultParser(),
new GeoResultParser(),
new WifiResultParser(),
new URLTOResultParser(),
new URIResultParser(),
new ISBNResultParser(),
new ProductResultParser(),
new ExpandedProductResultParser(),
new VINResultParser(),
};
#if SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || PORTABLE
private static readonly Regex DIGITS = new Regex(@"\A(?:" + "\\d+" + @")\z");
private static readonly Regex AMPERSAND = new Regex("&");
private static readonly Regex EQUALS = new Regex("=");
#else
private static readonly Regex DIGITS = new Regex(@"\A(?:" + "\\d+" + @")\z", RegexOptions.Compiled);
private static readonly Regex AMPERSAND = new Regex("&", RegexOptions.Compiled);
private static readonly Regex EQUALS = new Regex("=", RegexOptions.Compiled);
#endif
/// <summary>
/// Attempts to parse the raw {@link Result}'s contents as a particular type
/// of information (email, URL, etc.) and return a {@link ParsedResult} encapsulating
/// the result of parsing.
/// </summary>
/// <param name="theResult">The result.</param>
/// <returns></returns>
public abstract ParsedResult parse(ZXing.Result theResult);
public static ParsedResult parseResult(ZXing.Result theResult)
{
foreach (var parser in PARSERS)
{
var result = parser.parse(theResult);
if (result != null)
{
return result;
}
}
return new TextParsedResult(theResult.Text, null);
}
protected static void maybeAppend(String value, System.Text.StringBuilder result)
{
if (value != null)
{
result.Append('\n');
result.Append(value);
}
}
protected static void maybeAppend(String[] value, System.Text.StringBuilder result)
{
if (value != null)
{
for (int i = 0; i < value.Length; i++)
{
result.Append('\n');
result.Append(value[i]);
}
}
}
protected static String[] maybeWrap(System.String value_Renamed)
{
return value_Renamed == null ? null : new System.String[] { value_Renamed };
}
protected static String unescapeBackslash(System.String escaped)
{
if (escaped != null)
{
int backslash = escaped.IndexOf('\\');
if (backslash >= 0)
{
int max = escaped.Length;
var unescaped = new System.Text.StringBuilder(max - 1);
unescaped.Append(escaped.ToCharArray(), 0, backslash);
bool nextIsEscaped = false;
for (int i = backslash; i < max; i++)
{
char c = escaped[i];
if (nextIsEscaped || c != '\\')
{
unescaped.Append(c);
nextIsEscaped = false;
}
else
{
nextIsEscaped = true;
}
}
return unescaped.ToString();
}
}
return escaped;
}
protected static int parseHexDigit(char c)
{
if (c >= 'a')
{
if (c <= 'f')
{
return 10 + (c - 'a');
}
}
else if (c >= 'A')
{
if (c <= 'F')
{
return 10 + (c - 'A');
}
}
else if (c >= '0')
{
if (c <= '9')
{
return c - '0';
}
}
return -1;
}
internal static bool isStringOfDigits(String value, int length)
{
return value != null && length > 0 && length == value.Length && DIGITS.Match(value).Success;
}
internal static bool isSubstringOfDigits(String value, int offset, int length)
{
if (value == null || length <= 0)
{
return false;
}
int max = offset + length;
return value.Length >= max && DIGITS.Match(value, offset, length).Success;
}
internal static IDictionary<string, string> parseNameValuePairs(String uri)
{
int paramStart = uri.IndexOf('?');
if (paramStart < 0)
{
return null;
}
var result = new Dictionary<String, String>(3);
foreach (var keyValue in AMPERSAND.Split(uri.Substring(paramStart + 1)))
{
appendKeyValue(keyValue, result);
}
return result;
}
private static void appendKeyValue(String keyValue, IDictionary<String, String> result)
{
String[] keyValueTokens = EQUALS.Split(keyValue, 2);
if (keyValueTokens.Length == 2)
{
String key = keyValueTokens[0];
String value = keyValueTokens[1];
try
{
//value = URLDecoder.decode(value, "UTF-8");
value = urlDecode(value);
result[key] = value;
}
catch (Exception uee)
{
throw new InvalidOperationException("url decoding failed", uee); // can't happen
}
result[key] = value;
}
}
internal static String[] matchPrefixedField(String prefix, String rawText, char endChar, bool trim)
{
IList<string> matches = null;
int i = 0;
int max = rawText.Length;
while (i < max)
{
//UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'"
i = rawText.IndexOf(prefix, i);
if (i < 0)
{
break;
}
i += prefix.Length; // Skip past this prefix we found to start
int start = i; // Found the start of a match here
bool done = false;
while (!done)
{
//UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'"
i = rawText.IndexOf(endChar, i);
if (i < 0)
{
// No terminating end character? uh, done. Set i such that loop terminates and break
i = rawText.Length;
done = true;
}
else if (rawText[i - 1] == '\\')
{
// semicolon was escaped so continue
i++;
}
else
{
// found a match
if (matches == null)
{
matches = new List<string>();
}
String element = unescapeBackslash(rawText.Substring(start, (i) - (start)));
if (trim)
{
element = element.Trim();
}
if (!String.IsNullOrEmpty(element))
{
matches.Add(element);
}
i++;
done = true;
}
}
}
if (matches == null || (matches.Count == 0))
{
return null;
}
return SupportClass.toStringArray(matches);
}
internal static String matchSinglePrefixedField(String prefix, String rawText, char endChar, bool trim)
{
String[] matches = matchPrefixedField(prefix, rawText, endChar, trim);
return matches == null ? null : matches[0];
}
protected static String urlDecode(String escaped)
{
// Should we better use HttpUtility.UrlDecode?
// Is HttpUtility.UrlDecode available for all platforms?
// What about encoding like UTF8?
if (escaped == null)
{
return null;
}
char[] escapedArray = escaped.ToCharArray();
int first = findFirstEscape(escapedArray);
if (first < 0)
{
return escaped;
}
int max = escapedArray.Length;
// final length is at most 2 less than original due to at least 1 unescaping
var unescaped = new System.Text.StringBuilder(max - 2);
// Can append everything up to first escape character
unescaped.Append(escapedArray, 0, first);
for (int i = first; i < max; i++)
{
char c = escapedArray[i];
if (c == '+')
{
// + is translated directly into a space
unescaped.Append(' ');
}
else if (c == '%')
{
// Are there even two more chars? if not we will just copy the escaped sequence and be done
if (i >= max - 2)
{
unescaped.Append('%'); // append that % and move on
}
else
{
int firstDigitValue = parseHexDigit(escapedArray[++i]);
int secondDigitValue = parseHexDigit(escapedArray[++i]);
if (firstDigitValue < 0 || secondDigitValue < 0)
{
// bad digit, just move on
unescaped.Append('%');
unescaped.Append(escapedArray[i - 1]);
unescaped.Append(escapedArray[i]);
}
unescaped.Append((char)((firstDigitValue << 4) + secondDigitValue));
}
}
else
{
unescaped.Append(c);
}
}
return unescaped.ToString();
}
private static int findFirstEscape(char[] escapedArray)
{
int max = escapedArray.Length;
for (int i = 0; i < max; i++)
{
char c = escapedArray[i];
if (c == '+' || c == '%')
{
return i;
}
}
return -1;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using Orleans.Runtime;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;
//
// Number of #ifs can be reduced (or removed), once we separate test projects by feature/area, otherwise we are ending up with ambigous types and build errors.
//
#if ORLEANS_CLUSTERING
namespace Orleans.Clustering.AzureStorage
#elif ORLEANS_PERSISTENCE
namespace Orleans.Persistence.AzureStorage
#elif ORLEANS_REMINDERS
namespace Orleans.Reminders.AzureStorage
#elif ORLEANS_STREAMING
namespace Orleans.Streaming.AzureStorage
#elif ORLEANS_EVENTHUBS
namespace Orleans.Streaming.EventHubs
#elif TESTER_AZUREUTILS
namespace Orleans.Tests.AzureUtils
#else
// No default namespace intentionally to cause compile errors if something is not defined
#endif
{
/// <summary>
/// Utility class to encapsulate row-based access to Azure table storage.
/// </summary>
/// <remarks>
/// These functions are mostly intended for internal usage by Orleans runtime, but due to certain assembly packaging constrants this class needs to have public visibility.
/// </remarks>
/// <typeparam name="T">Table data entry used by this table / manager.</typeparam>
public class AzureTableDataManager<T> where T : class, ITableEntity, new()
{
/// <summary> Name of the table this instance is managing. </summary>
public string TableName { get; private set; }
/// <summary> Logger for this table manager instance. </summary>
protected internal ILogger Logger { get; private set; }
/// <summary> Connection string for the Azure storage account used to host this table. </summary>
protected string ConnectionString { get; set; }
private CloudTable tableReference;
private readonly CounterStatistic numServerBusy = CounterStatistic.FindOrCreate(StatisticNames.AZURE_SERVER_BUSY, true);
/// <summary>
/// Constructor
/// </summary>
/// <param name="tableName">Name of the table to be connected to.</param>
/// <param name="storageConnectionString">Connection string for the Azure storage account used to host this table.</param>
/// <param name="loggerFactory">Logger factory to use.</param>
public AzureTableDataManager(string tableName, string storageConnectionString, ILoggerFactory loggerFactory)
{
Logger = loggerFactory.CreateLogger<AzureTableDataManager<T>>();
TableName = tableName;
ConnectionString = storageConnectionString;
AzureStorageUtils.ValidateTableName(tableName);
}
/// <summary>
/// Connects to, or creates and initializes a new Azure table if it does not already exist.
/// </summary>
/// <returns>Completion promise for this operation.</returns>
public async Task InitTableAsync()
{
const string operation = "InitTable";
var startTime = DateTime.UtcNow;
try
{
CloudTableClient tableCreationClient = GetCloudTableCreationClient();
CloudTable tableRef = tableCreationClient.GetTableReference(TableName);
bool didCreate = await tableRef.CreateIfNotExistsAsync();
Logger.Info((int)Utilities.ErrorCode.AzureTable_01, "{0} Azure storage table {1}", (didCreate ? "Created" : "Attached to"), TableName);
CloudTableClient tableOperationsClient = GetCloudTableOperationsClient();
tableReference = tableOperationsClient.GetTableReference(TableName);
}
catch (Exception exc)
{
Logger.Error((int)Utilities.ErrorCode.AzureTable_02, $"Could not initialize connection to storage table {TableName}", exc);
throw;
}
finally
{
CheckAlertSlowAccess(startTime, operation);
}
}
/// <summary>
/// Deletes the Azure table.
/// </summary>
/// <returns>Completion promise for this operation.</returns>
public async Task DeleteTableAsync()
{
const string operation = "DeleteTable";
var startTime = DateTime.UtcNow;
try
{
CloudTableClient tableCreationClient = GetCloudTableCreationClient();
CloudTable tableRef = tableCreationClient.GetTableReference(TableName);
bool didDelete = await tableRef.DeleteIfExistsAsync();
if (didDelete)
{
Logger.Info((int)Utilities.ErrorCode.AzureTable_03, "Deleted Azure storage table {0}", TableName);
}
}
catch (Exception exc)
{
Logger.Error((int)Utilities.ErrorCode.AzureTable_04, "Could not delete storage table {0}", exc);
throw;
}
finally
{
CheckAlertSlowAccess(startTime, operation);
}
}
/// <summary>
/// Deletes all entities the Azure table.
/// </summary>
/// <returns>Completion promise for this operation.</returns>
public async Task ClearTableAsync()
{
IEnumerable<Tuple<T,string>> items = await ReadAllTableEntriesAsync();
IEnumerable<Task> work = items.GroupBy(item => item.Item1.PartitionKey)
.SelectMany(partition => partition.ToBatch(AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS))
.Select(batch => DeleteTableEntriesAsync(batch.ToList()));
await Task.WhenAll(work);
}
/// <summary>
/// Create a new data entry in the Azure table (insert new, not update existing).
/// Fails if the data already exists.
/// </summary>
/// <param name="data">Data to be inserted into the table.</param>
/// <returns>Value promise with new Etag for this data entry after completing this storage operation.</returns>
public async Task<string> CreateTableEntryAsync(T data)
{
const string operation = "CreateTableEntry";
var startTime = DateTime.UtcNow;
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("Creating {0} table entry: {1}", TableName, data);
try
{
// WAS:
// svc.AddObject(TableName, data);
// SaveChangesOptions.None
try
{
// Presumably FromAsync(BeginExecute, EndExecute) has a slightly better performance then CreateIfNotExistsAsync.
var opResult = await tableReference.ExecuteAsync(TableOperation.Insert(data));
return opResult.Etag;
}
catch (Exception exc)
{
CheckAlertWriteError(operation, data, null, exc);
throw;
}
}
finally
{
CheckAlertSlowAccess(startTime, operation);
}
}
/// <summary>
/// Inserts a data entry in the Azure table: creates a new one if does not exists or overwrites (without eTag) an already existing version (the "update in place" semantincs).
/// </summary>
/// <param name="data">Data to be inserted or replaced in the table.</param>
/// <returns>Value promise with new Etag for this data entry after completing this storage operation.</returns>
public async Task<string> UpsertTableEntryAsync(T data)
{
const string operation = "UpsertTableEntry";
var startTime = DateTime.UtcNow;
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} entry {1} into table {2}", operation, data, TableName);
try
{
try
{
// WAS:
// svc.AttachTo(TableName, data, null);
// svc.UpdateObject(data);
// SaveChangesOptions.ReplaceOnUpdate,
var opResult = await tableReference.ExecuteAsync(TableOperation.InsertOrReplace(data));
return opResult.Etag;
}
catch (Exception exc)
{
Logger.Warn((int)Utilities.ErrorCode.AzureTable_06,
$"Intermediate error upserting entry {(data == null ? "null" : data.ToString())} to the table {TableName}", exc);
throw;
}
}
finally
{
CheckAlertSlowAccess(startTime, operation);
}
}
/// <summary>
/// Merges a data entry in the Azure table.
/// </summary>
/// <param name="data">Data to be merged in the table.</param>
/// <param name="eTag">ETag to apply.</param>
/// <returns>Value promise with new Etag for this data entry after completing this storage operation.</returns>
internal async Task<string> MergeTableEntryAsync(T data, string eTag)
{
const string operation = "MergeTableEntry";
var startTime = DateTime.UtcNow;
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} entry {1} into table {2}", operation, data, TableName);
try
{
try
{
// WAS:
// svc.AttachTo(TableName, data, ANY_ETAG);
// svc.UpdateObject(data);
data.ETag = eTag;
// Merge requires an ETag (which may be the '*' wildcard).
var opResult = await tableReference.ExecuteAsync(TableOperation.Merge(data));
return opResult.Etag;
}
catch (Exception exc)
{
Logger.Warn((int)Utilities.ErrorCode.AzureTable_07,
$"Intermediate error merging entry {(data == null ? "null" : data.ToString())} to the table {TableName}", exc);
throw;
}
}
finally
{
CheckAlertSlowAccess(startTime, operation);
}
}
/// <summary>
/// Updates a data entry in the Azure table: updates an already existing data in the table, by using eTag.
/// Fails if the data does not already exist or of eTag does not match.
/// </summary>
/// <param name="data">Data to be updated into the table.</param>
/// /// <param name="dataEtag">ETag to use.</param>
/// <returns>Value promise with new Etag for this data entry after completing this storage operation.</returns>
public async Task<string> UpdateTableEntryAsync(T data, string dataEtag)
{
const string operation = "UpdateTableEntryAsync";
var startTime = DateTime.UtcNow;
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} table {1} entry {2}", operation, TableName, data);
try
{
try
{
data.ETag = dataEtag;
var opResult = await tableReference.ExecuteAsync(TableOperation.Replace(data));
//The ETag of data is needed in further operations.
return opResult.Etag;
}
catch (Exception exc)
{
CheckAlertWriteError(operation, data, null, exc);
throw;
}
}
finally
{
CheckAlertSlowAccess(startTime, operation);
}
}
/// <summary>
/// Deletes an already existing data in the table, by using eTag.
/// Fails if the data does not already exist or if eTag does not match.
/// </summary>
/// <param name="data">Data entry to be deleted from the table.</param>
/// <param name="eTag">ETag to use.</param>
/// <returns>Completion promise for this storage operation.</returns>
public async Task DeleteTableEntryAsync(T data, string eTag)
{
const string operation = "DeleteTableEntryAsync";
var startTime = DateTime.UtcNow;
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} table {1} entry {2}", operation, TableName, data);
try
{
data.ETag = eTag;
try
{
await tableReference.ExecuteAsync(TableOperation.Delete(data));
}
catch (Exception exc)
{
Logger.Warn((int)Utilities.ErrorCode.AzureTable_08,
$"Intermediate error deleting entry {data} from the table {TableName}.", exc);
throw;
}
}
finally
{
CheckAlertSlowAccess(startTime, operation);
}
}
/// <summary>
/// Read a single table entry from the storage table.
/// </summary>
/// <param name="partitionKey">The partition key for the entry.</param>
/// <param name="rowKey">The row key for the entry.</param>
/// <returns>Value promise for tuple containing the data entry and its corresponding etag.</returns>
public async Task<Tuple<T, string>> ReadSingleTableEntryAsync(string partitionKey, string rowKey)
{
const string operation = "ReadSingleTableEntryAsync";
var startTime = DateTime.UtcNow;
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} table {1} partitionKey {2} rowKey = {3}", operation, TableName, partitionKey, rowKey);
T retrievedResult = default(T);
try
{
try
{
string queryString = TableQueryFilterBuilder.MatchPartitionKeyAndRowKeyFilter(partitionKey, rowKey);
var query = new TableQuery<T>().Where(queryString);
TableQuerySegment<T> segment = await tableReference.ExecuteQuerySegmentedAsync(query, null);
retrievedResult = segment.Results.SingleOrDefault();
}
catch (StorageException exception)
{
if (!AzureStorageUtils.TableStorageDataNotFound(exception))
throw;
}
//The ETag of data is needed in further operations.
if (retrievedResult != null) return new Tuple<T, string>(retrievedResult, retrievedResult.ETag);
if (Logger.IsEnabled(LogLevel.Debug)) Logger.Debug("Could not find table entry for PartitionKey={0} RowKey={1}", partitionKey, rowKey);
return null; // No data
}
finally
{
CheckAlertSlowAccess(startTime, operation);
}
}
/// <summary>
/// Read all entries in one partition of the storage table.
/// NOTE: This could be an expensive and slow operation for large table partitions!
/// </summary>
/// <param name="partitionKey">The key for the partition to be searched.</param>
/// <returns>Enumeration of all entries in the specified table partition.</returns>
public Task<IEnumerable<Tuple<T, string>>> ReadAllTableEntriesForPartitionAsync(string partitionKey)
{
string query = TableQuery.GenerateFilterCondition(nameof(ITableEntity.PartitionKey), QueryComparisons.Equal, partitionKey);
return ReadTableEntriesAndEtagsAsync(query);
}
/// <summary>
/// Read all entries in the table.
/// NOTE: This could be a very expensive and slow operation for large tables!
/// </summary>
/// <returns>Enumeration of all entries in the table.</returns>
public Task<IEnumerable<Tuple<T, string>>> ReadAllTableEntriesAsync()
{
return ReadTableEntriesAndEtagsAsync(null);
}
/// <summary>
/// Deletes a set of already existing data entries in the table, by using eTag.
/// Fails if the data does not already exist or if eTag does not match.
/// </summary>
/// <param name="collection">Data entries and their corresponding etags to be deleted from the table.</param>
/// <returns>Completion promise for this storage operation.</returns>
public async Task DeleteTableEntriesAsync(IReadOnlyCollection<Tuple<T, string>> collection)
{
const string operation = "DeleteTableEntries";
var startTime = DateTime.UtcNow;
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("Deleting {0} table entries: {1}", TableName, Utils.EnumerableToString(collection));
if (collection == null) throw new ArgumentNullException("collection");
if (collection.Count > AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS)
{
throw new ArgumentOutOfRangeException("collection", collection.Count,
"Too many rows for bulk delete - max " + AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS);
}
if (collection.Count == 0)
{
return;
}
try
{
var entityBatch = new TableBatchOperation();
foreach (var tuple in collection)
{
// WAS:
// svc.AttachTo(TableName, tuple.Item1, tuple.Item2);
// svc.DeleteObject(tuple.Item1);
// SaveChangesOptions.ReplaceOnUpdate | SaveChangesOptions.Batch,
T item = tuple.Item1;
item.ETag = tuple.Item2;
entityBatch.Delete(item);
}
try
{
await tableReference.ExecuteBatchAsync(entityBatch);
}
catch (Exception exc)
{
Logger.Warn((int)Utilities.ErrorCode.AzureTable_08,
$"Intermediate error deleting entries {Utils.EnumerableToString(collection)} from the table {TableName}.", exc);
throw;
}
}
finally
{
CheckAlertSlowAccess(startTime, operation);
}
}
/// <summary>
/// Read data entries and their corresponding eTags from the Azure table.
/// </summary>
/// <param name="filter">Filter string to use for querying the table and filtering the results.</param>
/// <returns>Enumeration of entries in the table which match the query condition.</returns>
public async Task<IEnumerable<Tuple<T, string>>> ReadTableEntriesAndEtagsAsync(string filter)
{
const string operation = "ReadTableEntriesAndEtags";
var startTime = DateTime.UtcNow;
try
{
TableQuery<T> cloudTableQuery = filter == null
? new TableQuery<T>()
: new TableQuery<T>().Where(filter);
try
{
Func<Task<List<T>>> executeQueryHandleContinuations = async () =>
{
TableQuerySegment<T> querySegment = null;
var list = new List<T>();
//ExecuteSegmentedAsync not supported in "WindowsAzure.Storage": "7.2.1" yet
while (querySegment == null || querySegment.ContinuationToken != null)
{
querySegment = await tableReference.ExecuteQuerySegmentedAsync(cloudTableQuery, querySegment?.ContinuationToken);
list.AddRange(querySegment);
}
return list;
};
IBackoffProvider backoff = new FixedBackoff(AzureTableDefaultPolicies.PauseBetweenTableOperationRetries);
List<T> results = await AsyncExecutorWithRetries.ExecuteWithRetries(
counter => executeQueryHandleContinuations(),
AzureTableDefaultPolicies.MaxTableOperationRetries,
(exc, counter) => AzureStorageUtils.AnalyzeReadException(exc.GetBaseException(), counter, TableName, Logger),
AzureTableDefaultPolicies.TableOperationTimeout,
backoff);
// Data was read successfully if we got to here
return results.Select(i => Tuple.Create(i, i.ETag)).ToList();
}
catch (Exception exc)
{
// Out of retries...
var errorMsg = $"Failed to read Azure storage table {TableName}: {exc.Message}";
if (!AzureStorageUtils.TableStorageDataNotFound(exc))
{
Logger.Warn((int)Utilities.ErrorCode.AzureTable_09, errorMsg, exc);
}
throw new OrleansException(errorMsg, exc);
}
}
finally
{
CheckAlertSlowAccess(startTime, operation);
}
}
/// <summary>
/// Inserts a set of new data entries into the table.
/// Fails if the data does already exists.
/// </summary>
/// <param name="collection">Data entries to be inserted into the table.</param>
/// <returns>Completion promise for this storage operation.</returns>
public async Task BulkInsertTableEntries(IReadOnlyCollection<T> collection)
{
const string operation = "BulkInsertTableEntries";
if (collection == null) throw new ArgumentNullException("collection");
if (collection.Count > AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS)
{
throw new ArgumentOutOfRangeException("collection", collection.Count,
"Too many rows for bulk update - max " + AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS);
}
if (collection.Count == 0)
{
return;
}
var startTime = DateTime.UtcNow;
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("Bulk inserting {0} entries to {1} table", collection.Count, TableName);
try
{
// WAS:
// svc.AttachTo(TableName, entry);
// svc.UpdateObject(entry);
// SaveChangesOptions.None | SaveChangesOptions.Batch,
// SaveChangesOptions.None == Insert-or-merge operation, SaveChangesOptions.Batch == Batch transaction
// http://msdn.microsoft.com/en-us/library/hh452241.aspx
var entityBatch = new TableBatchOperation();
foreach (T entry in collection)
{
entityBatch.Insert(entry);
}
try
{
// http://msdn.microsoft.com/en-us/library/hh452241.aspx
await tableReference.ExecuteBatchAsync(entityBatch);
}
catch (Exception exc)
{
Logger.Warn((int)Utilities.ErrorCode.AzureTable_37,
$"Intermediate error bulk inserting {collection.Count} entries in the table {TableName}", exc);
}
}
finally
{
CheckAlertSlowAccess(startTime, operation);
}
}
#region Internal functions
internal async Task<Tuple<string, string>> InsertTwoTableEntriesConditionallyAsync(T data1, T data2, string data2Etag)
{
const string operation = "InsertTableEntryConditionally";
string data2Str = (data2 == null ? "null" : data2.ToString());
var startTime = DateTime.UtcNow;
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} into table {1} data1 {2} data2 {3}", operation, TableName, data1, data2Str);
try
{
try
{
// WAS:
// Only AddObject, do NOT AttachTo. If we did both UpdateObject and AttachTo, it would have been equivalent to InsertOrReplace.
// svc.AddObject(TableName, data);
// ---
// svc.AttachTo(TableName, tableVersion, tableVersionEtag);
// svc.UpdateObject(tableVersion);
// SaveChangesOptions.ReplaceOnUpdate | SaveChangesOptions.Batch,
// EntityDescriptor dataResult = svc.GetEntityDescriptor(data);
// return dataResult.ETag;
var entityBatch = new TableBatchOperation();
entityBatch.Add(TableOperation.Insert(data1));
data2.ETag = data2Etag;
entityBatch.Add(TableOperation.Replace(data2));
var opResults = await tableReference.ExecuteBatchAsync(entityBatch);
//The batch results are returned in order of execution,
//see reference at https://msdn.microsoft.com/en-us/library/microsoft.windowsazure.storage.table.cloudtable.executebatch.aspx.
//The ETag of data is needed in further operations.
return new Tuple<string, string>(opResults[0].Etag, opResults[1].Etag);
}
catch (Exception exc)
{
CheckAlertWriteError(operation, data1, data2Str, exc);
throw;
}
}
finally
{
CheckAlertSlowAccess(startTime, operation);
}
}
internal async Task<Tuple<string, string>> UpdateTwoTableEntriesConditionallyAsync(T data1, string data1Etag, T data2, string data2Etag)
{
const string operation = "UpdateTableEntryConditionally";
string data2Str = (data2 == null ? "null" : data2.ToString());
var startTime = DateTime.UtcNow;
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} table {1} data1 {2} data2 {3}", operation, TableName, data1, data2Str);
try
{
try
{
// WAS:
// Only AddObject, do NOT AttachTo. If we did both UpdateObject and AttachTo, it would have been equivalent to InsertOrReplace.
// svc.AttachTo(TableName, data, dataEtag);
// svc.UpdateObject(data);
// ----
// svc.AttachTo(TableName, tableVersion, tableVersionEtag);
// svc.UpdateObject(tableVersion);
// SaveChangesOptions.ReplaceOnUpdate | SaveChangesOptions.Batch,
// EntityDescriptor dataResult = svc.GetEntityDescriptor(data);
// return dataResult.ETag;
var entityBatch = new TableBatchOperation();
data1.ETag = data1Etag;
entityBatch.Add(TableOperation.Replace(data1));
if (data2 != null && data2Etag != null)
{
data2.ETag = data2Etag;
entityBatch.Add(TableOperation.Replace(data2));
}
var opResults = await tableReference.ExecuteBatchAsync(entityBatch);
//The batch results are returned in order of execution,
//see reference at https://msdn.microsoft.com/en-us/library/microsoft.windowsazure.storage.table.cloudtable.executebatch.aspx.
//The ETag of data is needed in further operations.
return new Tuple<string, string>(opResults[0].Etag, opResults[1].Etag);
}
catch (Exception exc)
{
CheckAlertWriteError(operation, data1, data2Str, exc);
throw;
}
}
finally
{
CheckAlertSlowAccess(startTime, operation);
}
}
// Utility methods
private CloudTableClient GetCloudTableOperationsClient()
{
try
{
CloudStorageAccount storageAccount = AzureStorageUtils.GetCloudStorageAccount(ConnectionString);
CloudTableClient operationsClient = storageAccount.CreateCloudTableClient();
operationsClient.DefaultRequestOptions.RetryPolicy = AzureTableDefaultPolicies.TableOperationRetryPolicy;
operationsClient.DefaultRequestOptions.ServerTimeout = AzureTableDefaultPolicies.TableOperationTimeout;
// Values supported can be AtomPub, Json, JsonFullMetadata or JsonNoMetadata with Json being the default value
operationsClient.DefaultRequestOptions.PayloadFormat = TablePayloadFormat.JsonNoMetadata;
return operationsClient;
}
catch (Exception exc)
{
Logger.Error((int)Utilities.ErrorCode.AzureTable_17, "Error creating CloudTableOperationsClient.", exc);
throw;
}
}
private CloudTableClient GetCloudTableCreationClient()
{
try
{
CloudStorageAccount storageAccount = AzureStorageUtils.GetCloudStorageAccount(ConnectionString);
CloudTableClient creationClient = storageAccount.CreateCloudTableClient();
creationClient.DefaultRequestOptions.RetryPolicy = AzureTableDefaultPolicies.TableCreationRetryPolicy;
creationClient.DefaultRequestOptions.ServerTimeout = AzureTableDefaultPolicies.TableCreationTimeout;
// Values supported can be AtomPub, Json, JsonFullMetadata or JsonNoMetadata with Json being the default value
creationClient.DefaultRequestOptions.PayloadFormat = TablePayloadFormat.JsonNoMetadata;
return creationClient;
}
catch (Exception exc)
{
Logger.Error((int)Utilities.ErrorCode.AzureTable_18, "Error creating CloudTableCreationClient.", exc);
throw;
}
}
private void CheckAlertWriteError(string operation, object data1, string data2, Exception exc)
{
HttpStatusCode httpStatusCode;
string restStatus;
if(AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus) && AzureStorageUtils.IsContentionError(httpStatusCode))
{
// log at Verbose, since failure on conditional is not not an error. Will analyze and warn later, if required.
if(Logger.IsEnabled(LogLevel.Debug)) Logger.Debug((int)Utilities.ErrorCode.AzureTable_13,
$"Intermediate Azure table write error {operation} to table {TableName} data1 {(data1 ?? "null")} data2 {(data2 ?? "null")}", exc);
}
else
{
Logger.Error((int)Utilities.ErrorCode.AzureTable_14,
$"Azure table access write error {operation} to table {TableName} entry {data1}", exc);
}
}
private void CheckAlertSlowAccess(DateTime startOperation, string operation)
{
var timeSpan = DateTime.UtcNow - startOperation;
if (timeSpan > AzureTableDefaultPolicies.TableOperationTimeout)
{
Logger.Warn((int)Utilities.ErrorCode.AzureTable_15, "Slow access to Azure Table {0} for {1}, which took {2}.", TableName, operation, timeSpan);
}
}
#endregion
/// <summary>
/// Helper functions for building table queries.
/// </summary>
private class TableQueryFilterBuilder
{
/// <summary>
/// Builds query string to match partitionkey
/// </summary>
/// <param name="partitionKey"></param>
/// <returns></returns>
public static string MatchPartitionKeyFilter(string partitionKey)
{
return TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey);
}
/// <summary>
/// Builds query string to match rowkey
/// </summary>
/// <param name="rowKey"></param>
/// <returns></returns>
public static string MatchRowKeyFilter(string rowKey)
{
return TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, rowKey);
}
/// <summary>
/// Builds a query string that matches a specific partitionkey and rowkey.
/// </summary>
/// <param name="partitionKey"></param>
/// <param name="rowKey"></param>
/// <returns></returns>
public static string MatchPartitionKeyAndRowKeyFilter(string partitionKey, string rowKey)
{
return TableQuery.CombineFilters(MatchPartitionKeyFilter(partitionKey), TableOperators.And,
MatchRowKeyFilter(rowKey));
}
}
}
internal static class TableDataManagerInternalExtensions
{
internal static IEnumerable<IEnumerable<TItem>> ToBatch<TItem>(this IEnumerable<TItem> source, int size)
{
using (IEnumerator<TItem> enumerator = source.GetEnumerator())
while (enumerator.MoveNext())
yield return Take(enumerator, size);
}
private static IEnumerable<TItem> Take<TItem>(IEnumerator<TItem> source, int size)
{
int i = 0;
do
yield return source.Current;
while (++i < size && source.MoveNext());
}
}
}
| |
//
// Options.cs
//
// Authors:
// Jonathan Pryor <jpryor@novell.com>
//
// Copyright (C) 2008 Novell (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.
//
// Compile With:
// gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll
// gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll
//
// The LINQ version just changes the implementation of
// OptionSet.Parse(IEnumerable<string>), and confers no semantic changes.
//
// A Getopt::Long-inspired option parsing library for C#.
//
// NDesk.Options.OptionSet is built upon a key/value table, where the
// key is a option format string and the value is a delegate that is
// invoked when the format string is matched.
//
// Option format strings:
// Regex-like BNF Grammar:
// name: .+
// type: [=:]
// sep: ( [^{}]+ | '{' .+ '}' )?
// aliases: ( name type sep ) ( '|' name type sep )*
//
// Each '|'-delimited name is an alias for the associated action. If the
// format string ends in a '=', it has a required value. If the format
// string ends in a ':', it has an optional value. If neither '=' or ':'
// is present, no value is supported. `=' or `:' need only be defined on one
// alias, but if they are provided on more than one they must be consistent.
//
// Each alias portion may also end with a "key/value separator", which is used
// to split option values if the option accepts > 1 value. If not specified,
// it defaults to '=' and ':'. If specified, it can be any character except
// '{' and '}' OR the *string* between '{' and '}'. If no separator should be
// used (i.e. the separate values should be distinct arguments), then "{}"
// should be used as the separator.
//
// Options are extracted either from the current option by looking for
// the option name followed by an '=' or ':', or is taken from the
// following option IFF:
// - The current option does not contain a '=' or a ':'
// - The current option requires a value (i.e. not a Option type of ':')
//
// The `name' used in the option format string does NOT include any leading
// option indicator, such as '-', '--', or '/'. All three of these are
// permitted/required on any named option.
//
// Option bundling is permitted so long as:
// - '-' is used to start the option group
// - all of the bundled options are a single character
// - at most one of the bundled options accepts a value, and the value
// provided starts from the next character to the end of the string.
//
// This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value'
// as '-Dname=value'.
//
// Option processing is disabled by specifying "--". All options after "--"
// are returned by OptionSet.Parse() unchanged and unprocessed.
//
// Unprocessed options are returned from OptionSet.Parse().
//
// Examples:
// int verbose = 0;
// OptionSet p = new OptionSet ()
// .Add ("v", v => ++verbose)
// .Add ("name=|value=", v => Console.WriteLine (v));
// p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"});
//
// The above would parse the argument string array, and would invoke the
// lambda expression three times, setting `verbose' to 3 when complete.
// It would also print out "A" and "B" to standard output.
// The returned array would contain the string "extra".
//
// C# 3.0 collection initializers are supported and encouraged:
// var p = new OptionSet () {
// { "h|?|help", v => ShowHelp () },
// };
//
// System.ComponentModel.TypeConverter is also supported, allowing the use of
// custom data types in the callback type; TypeConverter.ConvertFromString()
// is used to convert the value option to an instance of the specified
// type:
//
// var p = new OptionSet () {
// { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) },
// };
//
// Random other tidbits:
// - Boolean options (those w/o '=' or ':' in the option format string)
// are explicitly enabled if they are followed with '+', and explicitly
// disabled if they are followed with '-':
// string a = null;
// var p = new OptionSet () {
// { "a", s => a = s },
// };
// p.Parse (new string[]{"-a"}); // sets v != null
// p.Parse (new string[]{"-a+"}); // sets v != null
// p.Parse (new string[]{"-a-"}); // sets v == null
//
// The NUnit version of this file introduces conditional compilation for
// building under .NET Standard
//
// 11/5/2015 -
// Change namespace to avoid conflict with user code use of mono.options
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using NUnit.Compatibility;
// Missing XML Docs
#pragma warning disable 1591
#if !NETSTANDARD1_6
using System.Security.Permissions;
using System.Runtime.Serialization;
#endif
namespace NUnit.Options
{
public class OptionValueCollection : IList, IList<string> {
List<string> values = new List<string> ();
OptionContext c;
internal OptionValueCollection (OptionContext c)
{
this.c = c;
}
#region ICollection
void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);}
bool ICollection.IsSynchronized {get {return (values as ICollection).IsSynchronized;}}
object ICollection.SyncRoot {get {return (values as ICollection).SyncRoot;}}
#endregion
#region ICollection<T>
public void Add (string item) {values.Add (item);}
public void Clear () {values.Clear ();}
public bool Contains (string item) {return values.Contains (item);}
public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);}
public bool Remove (string item) {return values.Remove (item);}
public int Count {get {return values.Count;}}
public bool IsReadOnly {get {return false;}}
#endregion
#region IEnumerable
IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();}
#endregion
#region IEnumerable<T>
public IEnumerator<string> GetEnumerator () {return values.GetEnumerator ();}
#endregion
#region IList
int IList.Add (object value) {return (values as IList).Add (value);}
bool IList.Contains (object value) {return (values as IList).Contains (value);}
int IList.IndexOf (object value) {return (values as IList).IndexOf (value);}
void IList.Insert (int index, object value) {(values as IList).Insert (index, value);}
void IList.Remove (object value) {(values as IList).Remove (value);}
void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);}
bool IList.IsFixedSize {get {return false;}}
object IList.this [int index] {get {return this [index];} set {(values as IList)[index] = value;}}
#endregion
#region IList<T>
public int IndexOf (string item) {return values.IndexOf (item);}
public void Insert (int index, string item) {values.Insert (index, item);}
public void RemoveAt (int index) {values.RemoveAt (index);}
private void AssertValid (int index)
{
if (c.Option == null)
throw new InvalidOperationException ("OptionContext.Option is null.");
if (index >= c.Option.MaxValueCount)
throw new ArgumentOutOfRangeException ("index");
if (c.Option.OptionValueType == OptionValueType.Required &&
index >= values.Count)
throw new OptionException (string.Format (
c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName),
c.OptionName);
}
public string this [int index] {
get {
AssertValid (index);
return index >= values.Count ? null : values [index];
}
set {
values [index] = value;
}
}
#endregion
public List<string> ToList ()
{
return new List<string> (values);
}
public string[] ToArray ()
{
return values.ToArray ();
}
public override string ToString ()
{
return string.Join (", ", values.ToArray ());
}
}
public class OptionContext {
private Option option;
private string name;
private int index;
private OptionSet set;
private OptionValueCollection c;
public OptionContext (OptionSet set)
{
this.set = set;
this.c = new OptionValueCollection (this);
}
public Option Option {
get {return option;}
set {option = value;}
}
public string OptionName {
get {return name;}
set {name = value;}
}
public int OptionIndex {
get {return index;}
set {index = value;}
}
public OptionSet OptionSet {
get {return set;}
}
public OptionValueCollection OptionValues {
get {return c;}
}
}
public enum OptionValueType {
None,
Optional,
Required,
}
public abstract class Option {
string prototype, description;
string[] names;
OptionValueType type;
int count;
string[] separators;
protected Option (string prototype, string description)
: this (prototype, description, 1)
{
}
protected Option (string prototype, string description, int maxValueCount)
{
if (prototype == null)
throw new ArgumentNullException ("prototype");
if (prototype.Length == 0)
throw new ArgumentException ("Cannot be the empty string.", "prototype");
if (maxValueCount < 0)
throw new ArgumentOutOfRangeException ("maxValueCount");
this.prototype = prototype;
this.names = prototype.Split ('|');
this.description = description;
this.count = maxValueCount;
this.type = ParsePrototype ();
if (this.count == 0 && type != OptionValueType.None)
throw new ArgumentException (
"Cannot provide maxValueCount of 0 for OptionValueType.Required or " +
"OptionValueType.Optional.",
"maxValueCount");
if (this.type == OptionValueType.None && maxValueCount > 1)
throw new ArgumentException (
string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount),
"maxValueCount");
if (Array.IndexOf (names, "<>") >= 0 &&
((names.Length == 1 && this.type != OptionValueType.None) ||
(names.Length > 1 && this.MaxValueCount > 1)))
throw new ArgumentException (
"The default option handler '<>' cannot require values.",
"prototype");
}
public string Prototype {get {return prototype;}}
public string Description {get {return description;}}
public OptionValueType OptionValueType {get {return type;}}
public int MaxValueCount {get {return count;}}
public string[] GetNames ()
{
return (string[]) names.Clone ();
}
public string[] GetValueSeparators ()
{
if (separators == null)
return new string [0];
return (string[]) separators.Clone ();
}
protected static T Parse<T> (string value, OptionContext c)
{
Type tt = typeof (T);
bool nullable = tt.GetTypeInfo().IsValueType && tt.GetTypeInfo().IsGenericType &&
!tt.GetTypeInfo().IsGenericTypeDefinition &&
tt.GetGenericTypeDefinition () == typeof (Nullable<>);
Type targetType = nullable ? tt.GetGenericArguments () [0] : typeof (T);
#if !NETSTANDARD1_6
TypeConverter conv = TypeDescriptor.GetConverter (targetType);
#endif
T t = default (T);
try {
if (value != null)
#if NETSTANDARD1_6
t = (T)Convert.ChangeType(value, tt, CultureInfo.InvariantCulture);
#else
t = (T) conv.ConvertFromString (value);
#endif
}
catch (Exception e) {
throw new OptionException (
string.Format (
c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."),
value, targetType.Name, c.OptionName),
c.OptionName, e);
}
return t;
}
internal string[] Names {get {return names;}}
internal string[] ValueSeparators {get {return separators;}}
static readonly char[] NameTerminator = new char[]{'=', ':'};
private OptionValueType ParsePrototype ()
{
char type = '\0';
List<string> seps = new List<string> ();
for (int i = 0; i < names.Length; ++i) {
string name = names [i];
if (name.Length == 0)
throw new ArgumentException ("Empty option names are not supported.", "prototype");
int end = name.IndexOfAny (NameTerminator);
if (end == -1)
continue;
names [i] = name.Substring (0, end);
if (type == '\0' || type == name [end])
type = name [end];
else
throw new ArgumentException (
string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]),
"prototype");
AddSeparators (name, end, seps);
}
if (type == '\0')
return OptionValueType.None;
if (count <= 1 && seps.Count != 0)
throw new ArgumentException (
string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count),
"prototype");
if (count > 1) {
if (seps.Count == 0)
this.separators = new string[]{":", "="};
else if (seps.Count == 1 && seps [0].Length == 0)
this.separators = null;
else
this.separators = seps.ToArray ();
}
return type == '=' ? OptionValueType.Required : OptionValueType.Optional;
}
private static void AddSeparators (string name, int end, ICollection<string> seps)
{
int start = -1;
for (int i = end+1; i < name.Length; ++i) {
switch (name [i]) {
case '{':
if (start != -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
start = i+1;
break;
case '}':
if (start == -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
seps.Add (name.Substring (start, i-start));
start = -1;
break;
default:
if (start == -1)
seps.Add (name [i].ToString ());
break;
}
}
if (start != -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
}
public void Invoke (OptionContext c)
{
OnParseComplete (c);
c.OptionName = null;
c.Option = null;
c.OptionValues.Clear ();
}
protected abstract void OnParseComplete (OptionContext c);
public override string ToString ()
{
return Prototype;
}
}
#if !NETSTANDARD1_6
[Serializable]
#endif
public class OptionException : Exception
{
private string option;
public OptionException ()
{
}
public OptionException (string message, string optionName)
: base (message)
{
this.option = optionName;
}
public OptionException (string message, string optionName, Exception innerException)
: base (message, innerException)
{
this.option = optionName;
}
#if !NETSTANDARD1_6
protected OptionException (SerializationInfo info, StreamingContext context)
: base (info, context)
{
this.option = info.GetString ("OptionName");
}
#endif
public string OptionName {
get {return this.option;}
}
#if !NETSTANDARD1_6
[SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
public override void GetObjectData (SerializationInfo info, StreamingContext context)
{
base.GetObjectData (info, context);
info.AddValue ("OptionName", option);
}
#endif
}
public delegate void OptionAction<TKey, TValue> (TKey key, TValue value);
public class OptionSet : KeyedCollection<string, Option>
{
string localizer(string msg)
{
return msg;
}
public string MessageLocalizer(string msg)
{
return msg;
}
protected override string GetKeyForItem (Option item)
{
if (item == null)
throw new ArgumentNullException ("option");
if (item.Names != null && item.Names.Length > 0)
return item.Names [0];
// This should never happen, as it's invalid for Option to be
// constructed w/o any names.
throw new InvalidOperationException ("Option has no names!");
}
[Obsolete ("Use KeyedCollection.this[string]")]
protected Option GetOptionForName (string option)
{
if (option == null)
throw new ArgumentNullException ("option");
try {
return base [option];
}
catch (KeyNotFoundException) {
return null;
}
}
protected override void InsertItem (int index, Option item)
{
base.InsertItem (index, item);
AddImpl (item);
}
protected override void RemoveItem (int index)
{
base.RemoveItem (index);
Option p = Items [index];
// KeyedCollection.RemoveItem() handles the 0th item
for (int i = 1; i < p.Names.Length; ++i) {
Dictionary.Remove (p.Names [i]);
}
}
protected override void SetItem (int index, Option item)
{
base.SetItem (index, item);
RemoveItem (index);
AddImpl (item);
}
private void AddImpl (Option option)
{
if (option == null)
throw new ArgumentNullException ("option");
List<string> added = new List<string> (option.Names.Length);
try {
// KeyedCollection.InsertItem/SetItem handle the 0th name.
for (int i = 1; i < option.Names.Length; ++i) {
Dictionary.Add (option.Names [i], option);
added.Add (option.Names [i]);
}
}
catch (Exception) {
foreach (string name in added)
Dictionary.Remove (name);
throw;
}
}
public new OptionSet Add (Option option)
{
base.Add (option);
return this;
}
sealed class ActionOption : Option {
Action<OptionValueCollection> action;
public ActionOption (string prototype, string description, int count, Action<OptionValueCollection> action)
: base (prototype, description, count)
{
if (action == null)
throw new ArgumentNullException ("action");
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (c.OptionValues);
}
}
public OptionSet Add (string prototype, Action<string> action)
{
return Add (prototype, null, action);
}
public OptionSet Add (string prototype, string description, Action<string> action)
{
if (action == null)
throw new ArgumentNullException ("action");
Option p = new ActionOption (prototype, description, 1,
delegate (OptionValueCollection v) { action (v [0]); });
base.Add (p);
return this;
}
public OptionSet Add (string prototype, OptionAction<string, string> action)
{
return Add (prototype, null, action);
}
public OptionSet Add (string prototype, string description, OptionAction<string, string> action)
{
if (action == null)
throw new ArgumentNullException ("action");
Option p = new ActionOption (prototype, description, 2,
delegate (OptionValueCollection v) {action (v [0], v [1]);});
base.Add (p);
return this;
}
sealed class ActionOption<T> : Option {
Action<T> action;
public ActionOption (string prototype, string description, Action<T> action)
: base (prototype, description, 1)
{
if (action == null)
throw new ArgumentNullException ("action");
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (Parse<T> (c.OptionValues [0], c));
}
}
sealed class ActionOption<TKey, TValue> : Option {
OptionAction<TKey, TValue> action;
public ActionOption (string prototype, string description, OptionAction<TKey, TValue> action)
: base (prototype, description, 2)
{
if (action == null)
throw new ArgumentNullException ("action");
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (
Parse<TKey> (c.OptionValues [0], c),
Parse<TValue> (c.OptionValues [1], c));
}
}
public OptionSet Add<T> (string prototype, Action<T> action)
{
return Add (prototype, null, action);
}
public OptionSet Add<T> (string prototype, string description, Action<T> action)
{
return Add (new ActionOption<T> (prototype, description, action));
}
public OptionSet Add<TKey, TValue> (string prototype, OptionAction<TKey, TValue> action)
{
return Add (prototype, null, action);
}
public OptionSet Add<TKey, TValue> (string prototype, string description, OptionAction<TKey, TValue> action)
{
return Add (new ActionOption<TKey, TValue> (prototype, description, action));
}
protected virtual OptionContext CreateOptionContext ()
{
return new OptionContext (this);
}
public List<string> Parse (IEnumerable<string> arguments)
{
OptionContext c = CreateOptionContext ();
c.OptionIndex = -1;
bool process = true;
List<string> unprocessed = new List<string> ();
Option def = Contains ("<>") ? this ["<>"] : null;
foreach (string argument in arguments) {
++c.OptionIndex;
if (argument == "--") {
process = false;
continue;
}
if (!process) {
Unprocessed (unprocessed, def, c, argument);
continue;
}
if (!Parse (argument, c))
Unprocessed (unprocessed, def, c, argument);
}
if (c.Option != null)
c.Option.Invoke (c);
return unprocessed;
}
private static bool Unprocessed (ICollection<string> extra, Option def, OptionContext c, string argument)
{
if (def == null) {
extra.Add (argument);
return false;
}
c.OptionValues.Add (argument);
c.Option = def;
c.Option.Invoke (c);
return false;
}
private readonly Regex ValueOption = new Regex (
@"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$");
protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value)
{
if (argument == null)
throw new ArgumentNullException ("argument");
flag = name = sep = value = null;
Match m = ValueOption.Match (argument);
if (!m.Success) {
return false;
}
flag = m.Groups ["flag"].Value;
name = m.Groups ["name"].Value;
if (m.Groups ["sep"].Success && m.Groups ["value"].Success) {
sep = m.Groups ["sep"].Value;
value = m.Groups ["value"].Value;
}
return true;
}
protected virtual bool Parse (string argument, OptionContext c)
{
if (c.Option != null) {
ParseValue (argument, c);
return true;
}
string f, n, s, v;
if (!GetOptionParts (argument, out f, out n, out s, out v))
return false;
Option p;
if (Contains (n)) {
p = this [n];
c.OptionName = f + n;
c.Option = p;
switch (p.OptionValueType) {
case OptionValueType.None:
c.OptionValues.Add (n);
c.Option.Invoke (c);
break;
case OptionValueType.Optional:
case OptionValueType.Required:
ParseValue (v, c);
break;
}
return true;
}
// no match; is it a bool option?
if (ParseBool (argument, n, c))
return true;
// is it a bundled option?
if (ParseBundledValue (f, string.Concat (n + s + v), c))
return true;
return false;
}
private void ParseValue (string option, OptionContext c)
{
if (option != null)
foreach (string o in c.Option.ValueSeparators != null
? option.Split (c.Option.ValueSeparators, StringSplitOptions.None)
: new string[]{option}) {
c.OptionValues.Add (o);
}
if (c.OptionValues.Count == c.Option.MaxValueCount ||
c.Option.OptionValueType == OptionValueType.Optional)
c.Option.Invoke (c);
else if (c.OptionValues.Count > c.Option.MaxValueCount) {
throw new OptionException (localizer (string.Format (
"Error: Found {0} option values when expecting {1}.",
c.OptionValues.Count, c.Option.MaxValueCount)),
c.OptionName);
}
}
private bool ParseBool (string option, string n, OptionContext c)
{
Option p;
string rn;
if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') &&
Contains ((rn = n.Substring (0, n.Length-1)))) {
p = this [rn];
string v = n [n.Length-1] == '+' ? option : null;
c.OptionName = option;
c.Option = p;
c.OptionValues.Add (v);
p.Invoke (c);
return true;
}
return false;
}
private bool ParseBundledValue (string f, string n, OptionContext c)
{
if (f != "-")
return false;
for (int i = 0; i < n.Length; ++i) {
Option p;
string opt = f + n [i].ToString ();
string rn = n [i].ToString ();
if (!Contains (rn)) {
if (i == 0)
return false;
throw new OptionException (string.Format (localizer (
"Cannot bundle unregistered option '{0}'."), opt), opt);
}
p = this [rn];
switch (p.OptionValueType) {
case OptionValueType.None:
Invoke (c, opt, n, p);
break;
case OptionValueType.Optional:
case OptionValueType.Required: {
string v = n.Substring (i+1);
c.Option = p;
c.OptionName = opt;
ParseValue (v.Length != 0 ? v : null, c);
return true;
}
default:
throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType);
}
}
return true;
}
private static void Invoke (OptionContext c, string name, string value, Option option)
{
c.OptionName = name;
c.Option = option;
c.OptionValues.Add (value);
option.Invoke (c);
}
private const int OptionWidth = 29;
public void WriteOptionDescriptions (TextWriter o)
{
foreach (Option p in this) {
int written = 0;
if (!WriteOptionPrototype (o, p, ref written))
continue;
if (written < OptionWidth)
o.Write (new string (' ', OptionWidth - written));
else {
o.WriteLine ();
o.Write (new string (' ', OptionWidth));
}
bool indent = false;
string prefix = new string (' ', OptionWidth+2);
foreach (string line in GetLines (localizer (GetDescription (p.Description)))) {
if (indent)
o.Write (prefix);
o.WriteLine (line);
indent = true;
}
}
}
bool WriteOptionPrototype (TextWriter o, Option p, ref int written)
{
string[] names = p.Names;
int i = GetNextOptionIndex (names, 0);
if (i == names.Length)
return false;
if (names [i].Length == 1) {
Write (o, ref written, " -");
Write (o, ref written, names [0]);
}
else {
Write (o, ref written, " --");
Write (o, ref written, names [0]);
}
for ( i = GetNextOptionIndex (names, i+1);
i < names.Length; i = GetNextOptionIndex (names, i+1)) {
Write (o, ref written, ", ");
Write (o, ref written, names [i].Length == 1 ? "-" : "--");
Write (o, ref written, names [i]);
}
if (p.OptionValueType == OptionValueType.Optional ||
p.OptionValueType == OptionValueType.Required) {
if (p.OptionValueType == OptionValueType.Optional) {
Write (o, ref written, localizer ("["));
}
Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description)));
string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0
? p.ValueSeparators [0]
: " ";
for (int c = 1; c < p.MaxValueCount; ++c) {
Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description)));
}
if (p.OptionValueType == OptionValueType.Optional) {
Write (o, ref written, localizer ("]"));
}
}
return true;
}
static int GetNextOptionIndex (string[] names, int i)
{
while (i < names.Length && names [i] == "<>") {
++i;
}
return i;
}
static void Write (TextWriter o, ref int n, string s)
{
n += s.Length;
o.Write (s);
}
private static string GetArgumentName (int index, int maxIndex, string description)
{
if (description == null)
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
string[] nameStart;
if (maxIndex == 1)
nameStart = new string[]{"{0:", "{"};
else
nameStart = new string[]{"{" + index + ":"};
for (int i = 0; i < nameStart.Length; ++i) {
int start, j = 0;
do {
start = description.IndexOf (nameStart [i], j);
} while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false);
if (start == -1)
continue;
int end = description.IndexOf ("}", start);
if (end == -1)
continue;
return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length);
}
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
}
private static string GetDescription (string description)
{
if (description == null)
return string.Empty;
StringBuilder sb = new StringBuilder (description.Length);
int start = -1;
for (int i = 0; i < description.Length; ++i) {
switch (description [i]) {
case '{':
if (i == start) {
sb.Append ('{');
start = -1;
}
else if (start < 0)
start = i + 1;
break;
case '}':
if (start < 0) {
if ((i+1) == description.Length || description [i+1] != '}')
throw new InvalidOperationException ("Invalid option description: " + description);
++i;
sb.Append ("}");
}
else {
sb.Append (description.Substring (start, i - start));
start = -1;
}
break;
case ':':
if (start < 0)
goto default;
start = i + 1;
break;
default:
if (start < 0)
sb.Append (description [i]);
break;
}
}
return sb.ToString ();
}
private static IEnumerable<string> GetLines (string description)
{
if (string.IsNullOrEmpty (description)) {
yield return string.Empty;
yield break;
}
int length = 80 - OptionWidth - 1;
int start = 0, end;
do {
end = GetLineEnd (start, length, description);
char c = description [end-1];
if (char.IsWhiteSpace (c))
--end;
bool writeContinuation = end != description.Length && !IsEolChar (c);
string line = description.Substring (start, end - start) +
(writeContinuation ? "-" : "");
yield return line;
start = end;
if (char.IsWhiteSpace (c))
++start;
length = 80 - OptionWidth - 2 - 1;
} while (end < description.Length);
}
private static bool IsEolChar (char c)
{
return !char.IsLetterOrDigit (c);
}
private static int GetLineEnd (int start, int length, string description)
{
int end = System.Math.Min (start + length, description.Length);
int sep = -1;
for (int i = start+1; i < end; ++i) {
if (description [i] == '\n')
return i+1;
if (IsEolChar (description [i]))
sep = i+1;
}
if (sep == -1 || end == description.Length)
return end;
return sep;
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class OTTextSprite : OTSprite
{
public string text;
[HideInInspector]
public string _text;
public TextAsset textFile;
public int wordWrap = 0;
public bool justify = false;
public float lineHeightModifier = 1;
private string _text_;
private TextAsset _textFile;
private int _wordWrap = 0;
private bool _justify = false;
private float _lineHeightModifier = 1;
long _bytesLines = 0;
List<OTTextAlinea> _parsed = new List<OTTextAlinea>();
Vector3[] verts = new Vector3[] {};
Vector2[] _uv = new Vector2[] {};
int[] tris = new int[] {};
long GetBytes()
{
if (textFile!=null)
return _textFile.bytes.Length;
else
return text.Length;
}
string GetDY()
{
OTSpriteAtlas atlas = (spriteContainer as OTSpriteAtlas);
if (atlas == null) return "";
string dy = atlas.GetMeta("dy");
if (dy=="")
{
if (atlas.atlasData.Length>0)
{
OTAtlasData d = atlas.DataByName(""+((byte)'J'));
if (d==null)
d = atlas.DataByName("J");
if (d==null)
d = atlas.atlasData[0];
if (d!=null)
dy = ""+(d.offset.y + d.size.y);
}
else
dy = "50";
}
float idy = (float)System.Convert.ToDouble(dy);
idy *= lineHeightModifier;
idy = Mathf.Round(idy);
return ""+idy;
}
public Vector2 CursorPosition(IVector2 pos)
{
if (text == "")
return transform.position;
Rect r = worldRect;
Vector2 p = new Vector2(r.xMin, r.yMin + r.height/2);
int px = 0;
int tx = 0;
for (int i=0; i<sizeChars.Length; i++)
{
if (i<sizeChars.Length && i<pos.x)
px+=(sizeChars[i]);
tx+=(sizeChars[i]);
}
if (tx>0 && px >0)
return p + new Vector2((r.width/tx) * px,0);
else
return transform.position;
}
int[] sizeChars = new int[]{};
int lineHeight = 0;
void ParseText()
{
_bytesLines = GetBytes();
char[] chars = text.ToCharArray();
if (textFile!=null)
chars = textFile.text.ToCharArray();
for (int p=0; p<_parsed.Count; p++)
_parsed[p].Clean();
_parsed.Clear();
int dy = System.Convert.ToUInt16(GetDY());
int yPosition = 0;
OTSpriteAtlas atlas = (spriteContainer as OTSpriteAtlas);
OTAtlasData data = atlas.atlasData[0];
if (data!=null && data.frameSize.y>0 && lineHeight == 0)
lineHeight = (int)data.frameSize.y;
sizeChars = new int[]{};
System.Array.Resize<int>(ref sizeChars, chars.Length);
int ci = 0;
OTTextAlinea alinea = new OTTextAlinea(yPosition, lineHeight);
foreach(char c in chars) {
if (c=='\r')
{
sizeChars[ci++] = 0;
continue;
}
if (c=='\n')
{
alinea.End();
_parsed.Add(alinea);
yPosition -= dy;
alinea = new OTTextAlinea(yPosition, lineHeight);
sizeChars[ci++] = 0;
continue;
}
data = atlas.DataByName(""+c);
OTContainer.Frame frame = atlas.FrameByName(""+c);
if (data==null || frame.name=="")
{
string charName = ((int)c).ToString();
data = atlas.DataByName(charName);
frame = atlas.FrameByName(charName);
}
if (data==null || frame.name=="")
{
data = atlas.DataByName(""+c+".png");
frame = atlas.FrameByName(""+c+".png");
}
if (data==null || frame.name=="")
{
byte b = System.Text.Encoding.ASCII.GetBytes("?")[0];
data = atlas.DataByName(""+b);
frame = atlas.FrameByName(""+b);
}
if (data==null || frame.name=="")
{
data = atlas.DataByName("32");
frame = atlas.FrameByName("32");
}
if (data!=null && data.frameSize.y>0 && lineHeight == 0)
lineHeight = (int)data.frameSize.y;
if (data!=null && frame.name == data.name)
{
if (data.name!="32")
{
Vector3[] verts = new Vector3[] {
new Vector3(frame.offset.x, -frame.offset.y,0),
new Vector3(frame.offset.x+frame.size.x, -frame.offset.y,0),
new Vector3(frame.offset.x+frame.size.x, -frame.offset.y-frame.size.y,0),
new Vector3(frame.offset.x, -frame.offset.y - frame.size.y,0)
};
alinea.Add(((char)c).ToString(), data, verts, frame.uv);
}
else
alinea.NextWord(data);
string dx = data.GetMeta("dx");
int width = 0;
if (dx=="")
width = (int)(data.offset.x + data.size.x);
else
width = System.Convert.ToUInt16(dx);
if (width == 0) width = 30;
sizeChars[ci++] = width;
}
}
alinea.End();
_parsed.Add(alinea);
if (wordWrap > 0)
for (int p=0; p<_parsed.Count; p++)
{
_parsed[p].WordWrap(wordWrap, dy);
for (int pp = p+1; pp<_parsed.Count; pp++)
_parsed[pp].lines[0].yPosition -= (dy * (_parsed[p].lines.Count-1));
}
}
protected override Mesh GetMesh()
{
if (_spriteContainer==null || (_spriteContainer!=null && !_spriteContainer.isReady))
return null;
ParseText();
verts = new Vector3[] {};
_uv = new Vector2[] {};
tris = new int[] {};
Mesh mesh = InitMesh();
mesh.vertices = verts;
mesh.uv = _uv;
mesh.triangles = tris;
mesh.RecalculateBounds();
mesh.RecalculateNormals();
// calculate maximum width
int wi = 0;
for (int p = 0; p<_parsed.Count; p++)
for (int l=0; l<_parsed[p].lines.Count; l++)
if (_parsed[p].lines[l].width>wi)
wi = _parsed[p].lines[l].width;
for (int p = 0; p<_parsed.Count; p++)
{
for (int l=0; l<_parsed[p].lines.Count; l++)
{
Vector3[] lineVerts = _parsed[p].lines[l].GetVerts(wi,pivotPoint, (l==_parsed[p].lines.Count-1)?false:justify);
Vector2[] lineUV = _parsed[p].lines[l].uv;
int vIdx = verts.Length;
int uIdx = _uv.Length;
int tIdx = tris.Length;
System.Array.Resize<Vector3>(ref verts, verts.Length + lineVerts.Length);
lineVerts.CopyTo(verts,vIdx);
System.Array.Resize<int>(ref tris, tris.Length + (6 * (_parsed[p].lines[l].charCount+1)));
for (int tr = 0; tr<= _parsed[p].lines[l].charCount; tr++)
{
new int[] {
vIdx, vIdx+1, vIdx+2,
vIdx+2, vIdx+3, vIdx
}.CopyTo(tris, tIdx);
vIdx += 4;
tIdx += 6;
}
System.Array.Resize<Vector2>(ref _uv, _uv.Length + lineUV.Length );
lineUV.CopyTo(_uv, uIdx);
}
}
mesh.vertices = TranslatePivotVerts(mesh, verts);
mesh.uv = _uv;
mesh.triangles = tris;
mesh.RecalculateBounds();
mesh.RecalculateNormals();
return mesh;
}
protected override void AfterMesh()
{
base.AfterMesh();
if (otTransform.parent!=null && otTransform.parent.GetComponent("OTSpriteBatch")!=null)
otTransform.parent.SendMessage("SpriteAfterMesh",this,SendMessageOptions.DontRequireReceiver);
if (otCollider!=null && otCollider is BoxCollider)
{
BoxCollider b = (otCollider as BoxCollider);
b.center = mesh.bounds.center;
b.size = mesh.bounds.extents*2;
}
}
//-----------------------------------------------------------------------------
// overridden subclass methods
//-----------------------------------------------------------------------------
protected override void CheckSettings()
{
if (_spriteContainer!=null && _spriteContainer.isReady)
{
if (_spriteContainer_ != spriteContainer)
meshDirty = true;
}
else
{
if (spriteContainer==null && _spriteContainer_!=null)
meshDirty = true;
}
base.CheckSettings();
}
protected override string GetTypeName()
{
return "TextSprite";
}
protected override void HandleUV()
{
if (spriteContainer != null && spriteContainer.isReady)
{
}
}
protected override void Clean()
{
adjustFrameSize = false;
base.Clean();
offset = Vector2.zero;
}
public override void PassiveUpdate()
{
if (_text_!=text || _textFile!=textFile || _bytesLines != GetBytes() ||
_wordWrap!=wordWrap || _justify!=justify || _lineHeightModifier!=lineHeightModifier)
Update();
}
//-----------------------------------------------------------------------------
// class methods
//-----------------------------------------------------------------------------
protected override void Awake()
{
passiveControl = true;
base.Awake();
_text_ = text;
_text = text;
_textFile = textFile;
_wordWrap = wordWrap;
_justify = justify;
_lineHeightModifier = lineHeightModifier;
if (lastContainer!=null && _spriteContainer == null && _containerName == "")
{
_spriteContainer = lastContainer;
_tintColor = lastColor;
_materialReference = lastMatRef;
_depth = lastDepth;
}
}
protected override void Start()
{
base.Start();
}
public static OTContainer lastContainer = null;
public static Color lastColor;
public static string lastMatRef;
public static int lastDepth;
// Update is called once per frame
protected override void Update()
{
if (spriteContainer==null || (spriteContainer!=null && !spriteContainer.isReady))
return;
if (Application.isEditor)
{
lastContainer = spriteContainer;
lastColor = tintColor;
lastMatRef = materialReference;
lastDepth = depth;
if (wordWrap<0) wordWrap = 0;
}
if (_text_!=text || _textFile!=textFile || _bytesLines != GetBytes() ||
_wordWrap!=wordWrap || _justify!=justify || _lineHeightModifier!=lineHeightModifier)
{
_text_ = text;
_text = text;
_textFile = textFile;
_wordWrap = wordWrap;
_justify = justify;
_lineHeightModifier = lineHeightModifier;
meshDirty = true;
}
base.Update();
}
}
class OTTextAlinea
{
public List<OTTextLine> lines = new List<OTTextLine>();
public OTTextAlinea(int yPosition, int lineHeight)
{
lines.Add(new OTTextLine(yPosition, true, lineHeight));
}
public void Clean()
{
for (int l=0; l<lines.Count; l++)
lines[l].Clean();
lines.Clear();
}
public void Add(string c, OTAtlasData data, Vector3[] verts, Vector2[] uv)
{
lines[lines.Count-1].Add(c, data, verts, uv);
}
public void NextWord(OTAtlasData space)
{
lines[lines.Count-1].NextWord(space);
}
public void End()
{
lines[lines.Count-1].End();
}
public void WordWrap(int wrapWidth, int dy)
{
List<OTTextLine> _lines = new List<OTTextLine>();
for (int l=0; l<lines.Count; l++)
_lines.AddRange(lines[l].WordWrap(wrapWidth, dy));
if (_lines.Count>1)
{
lines.Clear();
lines.AddRange(_lines);
}
}
}
class OTTextLine
{
public int charCount;
public int yPosition;
int lineHeight = 0;
public string text
{
get
{
string res = "";
for (int w=0; w<words.Count; w++)
{
res += words[w].text;
if (w<words.Count-1)
res +=" ";
}
return res;
}
}
public Vector2[] uv
{
get
{
Vector2[] _uv = new Vector2[]{
new Vector2(0,0),
new Vector2(0,0),
new Vector2(0,0),
new Vector2(0,0)
};
for (int w=0; w<words.Count; w++)
{
Vector2[] wUV = words[w].uv;
System.Array.Resize<Vector2>(ref _uv, _uv.Length + wUV.Length);
wUV.CopyTo(_uv, _uv.Length - wUV.Length);
}
return _uv;
}
}
public Vector3[] GetVerts(int maxWidth, Vector2 pivot, bool justify)
{
int tt = 0;
float twx = 0;
float spacing = 0;
if (words.Count>1)
spacing = (maxWidth - width)/(words.Count-1);
if (maxWidth>0 && !justify)
twx = (float)(maxWidth - width) * (pivot.x + 0.5f);
Vector3[] _verts = new Vector3[] {
new Vector3(0,0,0),
new Vector3(1,0,0),
new Vector3(1,-lineHeight,0),
new Vector3(0,-lineHeight,0)
};
for (int w=0; w<words.Count; w++)
{
Vector3[] wVerts = words[w].verts;
if (tt>0 || twx > 0 || yPosition!=0)
{
Matrix4x4 mx = new Matrix4x4();
mx.SetTRS(new Vector3(tt+twx,yPosition,0), Quaternion.identity, Vector3.one);
for (int i=0; i<wVerts.Length; i++)
wVerts[i] = mx.MultiplyPoint3x4(wVerts[i]);
}
tt += words[w].width + words[w].space;
if (justify)
tt+=(int)spacing;
System.Array.Resize<Vector3>(ref _verts, _verts.Length + wVerts.Length);
wVerts.CopyTo(_verts, _verts.Length - wVerts.Length);
}
return _verts;
}
public int width = 0;
public List<OTTextWord> words = new List<OTTextWord>();
public void Clean()
{
width = 0;
charCount = 0;
for (int w=0; w<words.Count; w++)
words[w].Clean();
words.Clear();
}
OTTextWord word;
public OTTextLine(int yPosition, bool createWord, int lineHeight)
{
this.yPosition = yPosition;
this.lineHeight = lineHeight;
word = null;
if (createWord)
Word();
}
void Word()
{
words.Add(new OTTextWord());
word = words[words.Count-1];
}
public void NextWord(OTAtlasData space)
{
word.End(space);
Word();
}
public void End()
{
if (word!=null)
word.End(null);
width = 0;
charCount = 0;
for (int i=0; i<words.Count; i++)
{
width += (words[i].width + words[i].space);
charCount += words[i].atlasData.Count;
}
}
public void Add(string c, OTAtlasData data, Vector3[] verts, Vector2[] uv )
{
word.Add(c, data, verts, uv);
}
public List<OTTextLine> WordWrap(int wrapWidth, int dy)
{
List<OTTextLine> wLines = new List<OTTextLine>();
if (words.Count>0)
{
OTTextLine line = new OTTextLine(yPosition, false, lineHeight);
wLines.Add(line);
int ww = 0; int yp = yPosition;
for (int w=0; w<words.Count; w++)
{
line.words.Add(words[w]);
if (w < words.Count-1)
{
ww += words[w].width;
if (ww >= wrapWidth || ww + words[w].space >= wrapWidth || ww + words[w+1].width > wrapWidth)
{
// wrap
ww = 0;
yp -= dy;
line.End();
line = new OTTextLine(yp, false, lineHeight);
wLines.Add(line);
}
else
ww += words[w].space;
}
}
line.End();
}
return wLines;
}
}
class OTTextWord
{
public int width = 0;
public string text = "";
public List<OTAtlasData> atlasData = new List<OTAtlasData>();
public List<int> txList = new List<int>();
public int space = 0;
public Vector3[] verts = new Vector3[] {};
public Vector2[] uv = new Vector2[] {};
public void Clean()
{
atlasData.Clear();
txList.Clear();
System.Array.Resize(ref verts, 0);
System.Array.Resize(ref uv, 0);
}
public void Add(string c, OTAtlasData data, Vector3[] verts, Vector2[] uv)
{
text+=c;
int tx = 0;
string dx = data.GetMeta("dx");
if (dx=="")
tx = (int)(data.offset.x + data.size.x);
else
tx = System.Convert.ToUInt16(dx);
txList.Add(tx);
atlasData.Add(data);
int tt = 0;
for (int i=0; i<txList.Count-1; i++)
tt+=txList[i];
Matrix4x4 mx = new Matrix4x4();
mx.SetTRS(new Vector3(tt,0,0), Quaternion.identity, Vector3.one);
for (int i=0; i<verts.Length; i++)
verts[i] = mx.MultiplyPoint3x4(verts[i]);
System.Array.Resize<Vector3>(ref this.verts, this.verts.Length + verts.Length);
verts.CopyTo(this.verts, this.verts.Length - verts.Length);
System.Array.Resize<Vector2>(ref this.uv, this.uv.Length + uv.Length);
uv.CopyTo(this.uv, this.uv.Length - uv.Length);
}
public void End(OTAtlasData space)
{
width = 0;
string dx = "";
for (int i=0; i<atlasData.Count; i++)
{
dx = atlasData[i].GetMeta("dx");
if (dx=="")
width += (int)(atlasData[i].offset.x + atlasData[i].size.x);
else
width += System.Convert.ToUInt16(dx);
}
if (space!=null)
{
dx = space.GetMeta("dx");
if (dx=="")
this.space = (int)(space.offset.x + space.size.x);
else
this.space = System.Convert.ToUInt16(dx);
if (this.space == 0)
this.space = 30;
}
}
}
| |
// Copyright (C) Pash Contributors. License: GPL/BSD. See https://github.com/Pash-Project/Pash/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Language;
using System.Management.Automation.Provider;
using System.Management.Automation.Runspaces;
using System.Reflection;
using Extensions.Enumerable;
using Pash.Implementation.Native;
using Pash.ParserIntrinsics;
using Microsoft.PowerShell.Commands;
namespace Pash.Implementation
{
internal class CommandManager
{
private Dictionary<string, ScriptInfo> _scripts;
private readonly LocalRunspace _runspace;
public CommandManager(LocalRunspace runspace)
{
_runspace = runspace;
_scripts = new Dictionary<string, ScriptInfo>(StringComparer.CurrentCultureIgnoreCase);
}
private void LoadScripts()
{
foreach (ScriptConfigurationEntry entry in _runspace.ExecutionContext.RunspaceConfiguration.Scripts)
{
try
{
var scriptBlock = new ScriptBlock(Parser.ParseInput(entry.Definition));
_scripts.Add(entry.Name, new ScriptInfo(entry.Name, scriptBlock,
ScopeUsages.NewScriptScope));
continue;
}
catch
{
throw new Exception("DuplicateScriptName: " + entry.Name);
}
}
}
public CommandProcessorBase CreateCommandProcessor(Command command)
{
string cmdText = command.CommandText;
CommandInfo commandInfo = null;
bool useLocalScope = command.UseLocalScope;
if (command.IsScript) //CommandText contains a script block. Parse it
{
command.ScriptBlockAst = Parser.ParseInput(cmdText);
}
//either we parsed something like "& { foo; bar }", or the CommandText was a script and was just parsed
if (command.ScriptBlockAst != null)
{
commandInfo = new ScriptInfo("", command.ScriptBlockAst.GetScriptBlock(),
useLocalScope ? ScopeUsages.NewScope : ScopeUsages.CurrentScope);
}
else //otherwise it's a real command (cmdlet, script, function, application)
{
commandInfo = FindCommand(cmdText, useLocalScope);
}
// make sure we only create a valid command processor if it's a valid command
commandInfo.Validate();
switch (commandInfo.CommandType)
{
case CommandTypes.Application:
return new ApplicationProcessor((ApplicationInfo)commandInfo);
case CommandTypes.Cmdlet:
return new CommandProcessor(commandInfo as CmdletInfo);
case CommandTypes.Script:
case CommandTypes.ExternalScript:
case CommandTypes.Function:
return new ScriptBlockProcessor(commandInfo as IScriptBlockInfo, commandInfo);
default:
throw new NotImplementedException("Invalid command type");
}
}
internal CommandInfo FindCommand(string command, bool useLocalScope=true)
{
if (_runspace.ExecutionContext.SessionState.Alias.Exists(command))
{
var aliasInfo = _runspace.ExecutionContext.SessionState.Alias.Get(command);
if (aliasInfo.ReferencedCommand == null)
{
throw new CommandNotFoundException(string.Format("Command '{0}' not found.", aliasInfo.Definition));
}
return aliasInfo.ReferencedCommand;
}
CommandInfo function = _runspace.ExecutionContext.SessionState.Function.Get(command);
if (function != null)
{
return function;
}
CmdletInfo cmdlet = _runspace.ExecutionContext.SessionState.Cmdlet.Get(command);
if (cmdlet != null)
{
return cmdlet;
}
if (_scripts.ContainsKey(command))
{
return _scripts[command];
}
var path = ResolveExecutablePath(command);
if (path == null)
{
//This means it's neither a command name, nor there was a file that can be executed
throw new CommandNotFoundException(string.Format("Command '{0}' not found.", command));
}
if (Path.GetExtension(path) == ".ps1")
{
return new ExternalScriptInfo(path, useLocalScope ? ScopeUsages.NewScriptScope : ScopeUsages.CurrentScope);
}
//otherwise it's an application
return new ApplicationInfo(Path.GetFileName(path), path, Path.GetExtension(path));
}
/// <summary>
/// Resolves the path to the executable file.
/// </summary>
/// <param name="path">Relative path to the executable (with extension optionally omitted).</param>
/// <returns>Absolute path to the executable file.</returns>
private static string ResolveExecutablePath(string path)
{
// TODO: Forbid to run executables and scripts from the current directory without a leading slash.
// For example, if current directory contains a 'file.exe' file, a command 'file.exe' should not
// execute, but './file.exe' should.
if (File.Exists(path))
{
return Path.GetFullPath(path);
}
// TODO: If not, then try to search the relative path with known extensions.
// TODO: If path contains path separator (i.e. it pretends to be relative) and relative path not found, then
// give up.
return ResolveAbsolutePath(path);
}
/// <summary>
/// Searches for the executable through system-wide directories.
/// </summary>
/// <param name="fileName">
/// Absolute path to the executable (with extension optionally omitted). May be also from the PATH environment variable.
/// </param>
/// <returns>Absolute path to the executable file.</returns>
private static string ResolveAbsolutePath(string fileName)
{
var systemPath = Environment.GetEnvironmentVariable("PATH") ?? string.Empty;
var directories = SplitPaths(systemPath);
var extensions = new List<string>{ ".ps1" }; // TODO: Clarify the priority of the .ps1 extension.
bool isWindows = Environment.OSVersion.Platform == PlatformID.Win32NT;
if (isWindows)
{
var pathExt = Environment.GetEnvironmentVariable("PATHEXT") ?? string.Empty;
extensions.AddRange(SplitPaths(pathExt));
}
if (!isWindows || extensions.Contains(Path.GetExtension(fileName), StringComparer.OrdinalIgnoreCase))
{
// If file means to be executable without adding an extension, check it:
var path = directories.Select(directory => Path.Combine(directory, fileName)).FirstOrDefault(File.Exists);
if (path != null)
{
return path;
}
}
// Now search for file adding all extensions:
var finalPath = extensions.Select(extension => fileName + extension)
.SelectMany(
fileNameWithExtension => directories.Select(directory => Path.Combine(directory, fileNameWithExtension)))
.FirstOrDefault(File.Exists);
return finalPath;
}
/// <summary>
/// Splits the combined path string using the <see cref="Path.PathSeparator"/> character.
/// </summary>
/// <param name="pathString">Path string.</param>
/// <returns>Paths.</returns>
private static string[] SplitPaths(string pathString)
{
return pathString.Split(new[]
{
Path.PathSeparator
}, StringSplitOptions.RemoveEmptyEntries);
}
private static bool IsExecutable(string path)
{
return File.Exists(path)
&& (string.Equals(Path.GetExtension(path), ".ps1", StringComparison.OrdinalIgnoreCase)
|| IsUnixExecutable(path));
}
private static bool IsUnixExecutable(string path)
{
var platform = Environment.OSVersion.Platform;
if (platform != PlatformID.Unix && platform != PlatformID.MacOSX)
{
return false;
}
return Posix.access(path, Posix.X_OK) == 0;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DevTestLabs
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// SecretsOperations operations.
/// </summary>
internal partial class SecretsOperations : IServiceOperations<DevTestLabsClient>, ISecretsOperations
{
/// <summary>
/// Initializes a new instance of the SecretsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal SecretsOperations(DevTestLabsClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the DevTestLabsClient
/// </summary>
public DevTestLabsClient Client { get; private set; }
/// <summary>
/// List secrets in a given user profile.
/// </summary>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='userName'>
/// The name of the user profile.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Secret>>> ListWithHttpMessagesAsync(string labName, string userName, ODataQuery<Secret> odataQuery = default(ODataQuery<Secret>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (userName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "userName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("labName", labName);
tracingParameters.Add("userName", userName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{userName}/secrets").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{userName}", Uri.EscapeDataString(userName));
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Secret>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<Secret>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get secret.
/// </summary>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='userName'>
/// The name of the user profile.
/// </param>
/// <param name='name'>
/// The name of the secret.
/// </param>
/// <param name='expand'>
/// Specify the $expand query. Example: 'properties($select=value)'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Secret>> GetWithHttpMessagesAsync(string labName, string userName, string name, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (userName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "userName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("labName", labName);
tracingParameters.Add("userName", userName);
tracingParameters.Add("name", name);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{userName}/secrets/{name}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{userName}", Uri.EscapeDataString(userName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", Uri.EscapeDataString(expand)));
}
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Secret>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Secret>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Create or replace an existing secret.
/// </summary>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='userName'>
/// The name of the user profile.
/// </param>
/// <param name='name'>
/// The name of the secret.
/// </param>
/// <param name='secret'>
/// A secret.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Secret>> CreateOrUpdateWithHttpMessagesAsync(string labName, string userName, string name, Secret secret, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (userName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "userName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (secret == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "secret");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("labName", labName);
tracingParameters.Add("userName", userName);
tracingParameters.Add("name", name);
tracingParameters.Add("secret", secret);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{userName}/secrets/{name}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{userName}", Uri.EscapeDataString(userName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(secret != null)
{
_requestContent = SafeJsonConvert.SerializeObject(secret, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Secret>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Secret>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Secret>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Delete secret.
/// </summary>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='userName'>
/// The name of the user profile.
/// </param>
/// <param name='name'>
/// The name of the secret.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string labName, string userName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (userName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "userName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("labName", labName);
tracingParameters.Add("userName", userName);
tracingParameters.Add("name", name);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{userName}/secrets/{name}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{userName}", Uri.EscapeDataString(userName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// List secrets in a given user profile.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Secret>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Secret>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<Secret>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using Xunit;
namespace System.Threading.Tasks.Dataflow.Tests
{
public class DebugAttributeTests
{
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public void TestDebuggerDisplaysAndTypeProxies()
{
// Test both canceled and non-canceled
foreach (var ct in new[] { new CancellationToken(false), new CancellationToken(true) })
{
// Some blocks have different code paths for whether they're greedy or not.
// This helps with code-coverage.
var dboBuffering = new DataflowBlockOptions();
var dboNoBuffering = new DataflowBlockOptions() { BoundedCapacity = 1 };
var dboExBuffering = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 2, CancellationToken = ct };
var dboExSpsc = new ExecutionDataflowBlockOptions { SingleProducerConstrained = true };
var dboExNoBuffering = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 2, BoundedCapacity = 1, CancellationToken = ct };
var dboGroupGreedy = new GroupingDataflowBlockOptions();
var dboGroupNonGreedy = new GroupingDataflowBlockOptions { Greedy = false };
// Item1 == test DebuggerDisplay, Item2 == test DebuggerTypeProxy, Item3 == object
var objectsToTest = new Tuple<bool, bool, object>[]
{
// Primary Blocks
// (Don't test DebuggerTypeProxy on instances that may internally have async operations in progress)
Tuple.Create<bool,bool,object>(true, true, new ActionBlock<int>(i => {})),
Tuple.Create<bool,bool,object>(true, true, new ActionBlock<int>(i => {}, dboExBuffering)),
Tuple.Create<bool,bool,object>(true, true, new ActionBlock<int>(i => {}, dboExSpsc)),
Tuple.Create<bool,bool,object>(true, false, SendAsyncMessages(new ActionBlock<int>(i => {}, dboExNoBuffering), 2)),
Tuple.Create<bool,bool,object>(true, true, new TransformBlock<int,int>(i => i)),
Tuple.Create<bool,bool,object>(true, true, new TransformBlock<int,int>(i => i, dboExBuffering)),
Tuple.Create<bool,bool,object>(true, false, SendAsyncMessages(new TransformBlock<int,int>(i => i, dboExNoBuffering),2)),
Tuple.Create<bool,bool,object>(true, true, new TransformManyBlock<int,int>(i => new [] { i })),
Tuple.Create<bool,bool,object>(true, true, new TransformManyBlock<int,int>(i => new [] { i }, dboExBuffering)),
Tuple.Create<bool,bool,object>(true, false, SendAsyncMessages(new TransformManyBlock<int,int>(i => new [] { i }, dboExNoBuffering),2)),
Tuple.Create<bool,bool,object>(true, true, new BufferBlock<int>()),
Tuple.Create<bool,bool,object>(true, true, new BufferBlock<int>(new DataflowBlockOptions() { NameFormat = "none" })),
Tuple.Create<bool,bool,object>(true, true, new BufferBlock<int>(new DataflowBlockOptions() { NameFormat = "foo={0}, bar={1}" })),
Tuple.Create<bool,bool,object>(true, true, new BufferBlock<int>(new DataflowBlockOptions() { NameFormat = "foo={0}, bar={1}, kaboom={2}" })),
Tuple.Create<bool,bool,object>(true, true, new BufferBlock<int>(dboBuffering)),
Tuple.Create<bool,bool,object>(true, false, SendAsyncMessages(new BufferBlock<int>(new DataflowBlockOptions { BoundedCapacity = 10 }), 20)),
Tuple.Create<bool,bool,object>(true, true, new BroadcastBlock<int>(i => i)),
Tuple.Create<bool,bool,object>(true, true, new BroadcastBlock<int>(i => i, dboBuffering)),
Tuple.Create<bool,bool,object>(true, false, SendAsyncMessages(new BroadcastBlock<int>(i => i, dboNoBuffering), 20)),
Tuple.Create<bool,bool,object>(true, true, new WriteOnceBlock<int>(i => i)),
Tuple.Create<bool,bool,object>(true, false, SendAsyncMessages(new WriteOnceBlock<int>(i => i), 1)),
Tuple.Create<bool,bool,object>(true, true, new WriteOnceBlock<int>(i => i, dboBuffering)),
Tuple.Create<bool,bool,object>(true, true, new JoinBlock<int,int>()),
Tuple.Create<bool,bool,object>(true, true, new JoinBlock<int,int>(dboGroupGreedy)),
Tuple.Create<bool,bool,object>(true, true, new JoinBlock<int,int>(dboGroupNonGreedy)),
Tuple.Create<bool,bool,object>(true, true, new JoinBlock<int,int,int>()),
Tuple.Create<bool,bool,object>(true, true, new JoinBlock<int,int,int>(dboGroupGreedy)),
Tuple.Create<bool,bool,object>(true, true, new JoinBlock<int,int,int>(dboGroupNonGreedy)),
Tuple.Create<bool,bool,object>(true, true, new BatchedJoinBlock<int,int>(42)),
Tuple.Create<bool,bool,object>(true, true, new BatchedJoinBlock<int,int>(42, dboGroupGreedy)),
Tuple.Create<bool,bool,object>(true, true, new BatchedJoinBlock<int,int,int>(42, dboGroupGreedy)),
Tuple.Create<bool,bool,object>(true, true, new BatchBlock<int>(42)),
Tuple.Create<bool,bool,object>(true, true, new BatchBlock<int>(42, dboGroupGreedy)),
Tuple.Create<bool,bool,object>(true, true, new BatchBlock<int>(42, dboGroupNonGreedy)),
Tuple.Create<bool,bool,object>(true, true, DataflowBlock.Encapsulate<int,int>(new BufferBlock<int>(),new BufferBlock<int>())),
Tuple.Create<bool,bool,object>(true, true, new BufferBlock<int>().AsObservable()),
// Supporting and Internal Types
Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(new ActionBlock<int>(i => {}, dboExBuffering), "_defaultTarget")),
Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(new ActionBlock<int>(i => {}, dboExNoBuffering), "_defaultTarget")),
Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(DebuggerAttributes.GetFieldValue(new ActionBlock<int>(i => {}), "_defaultTarget"), "_messages")),
Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(new ActionBlock<int>(i => {}, dboExSpsc), "_spscTarget")),
Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(DebuggerAttributes.GetFieldValue(new ActionBlock<int>(i => {}, dboExSpsc), "_spscTarget"), "_messages")),
Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(new BufferBlock<int>(), "_source")),
Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(new BufferBlock<int>(new DataflowBlockOptions { BoundedCapacity = 10 }), "_source")),
Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(new TransformBlock<int,int>(i => i, dboExBuffering), "_source")),
Tuple.Create<bool,bool,object>(true, true, DebuggerAttributes.GetFieldValue(new TransformBlock<int,int>(i => i, dboExNoBuffering), "_reorderingBuffer")),
Tuple.Create<bool,bool,object>(true, true, DebuggerAttributes.GetFieldValue(DebuggerAttributes.GetFieldValue(new TransformBlock<int,int>(i => i, dboExBuffering), "_source"), "_targetRegistry")),
Tuple.Create<bool,bool,object>(true, true, DebuggerAttributes.GetFieldValue(DebuggerAttributes.GetFieldValue(WithLinkedTarget<TransformBlock<int,int>,int>(new TransformBlock<int,int>(i => i, dboExNoBuffering)), "_source"), "_targetRegistry")),
Tuple.Create<bool,bool,object>(true, true, new JoinBlock<int,int>().Target1),
Tuple.Create<bool,bool,object>(true, true, new JoinBlock<int,int>(dboGroupGreedy).Target1),
Tuple.Create<bool,bool,object>(true, true, new JoinBlock<int,int>(dboGroupNonGreedy).Target1),
Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(new JoinBlock<int,int>().Target1, "_sharedResources")),
Tuple.Create<bool,bool,object>(true, true, new BatchedJoinBlock<int,int>(42).Target1),
Tuple.Create<bool,bool,object>(true, true, new BatchedJoinBlock<int,int>(42, dboGroupGreedy).Target1),
Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(new BatchBlock<int>(42), "_target")),
Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(new BatchBlock<int>(42, dboGroupGreedy), "_target")),
Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(new BatchBlock<int>(42, dboGroupNonGreedy), "_target")),
Tuple.Create<bool,bool,object>(true, false, new BufferBlock<int>().LinkTo(new ActionBlock<int>(i => {}))), // ActionOnDispose
Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(new BroadcastBlock<int>(i => i), "_source")),
Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(new BroadcastBlock<int>(i => i, dboGroupGreedy), "_source")),
Tuple.Create<bool,bool,object>(true, false, DebuggerAttributes.GetFieldValue(new BroadcastBlock<int>(i => i, dboGroupNonGreedy), "_source")),
Tuple.Create<bool,bool,object>(true, true, CreateNopLinkSource<int>()),
Tuple.Create<bool,bool,object>(true, true, CreateFilteringSource<int>()),
Tuple.Create<bool,bool,object>(true, true, CreateSendSource<int>()),
Tuple.Create<bool,bool,object>(true, false, CreateReceiveTarget<int>()),
Tuple.Create<bool,bool,object>(true, false, CreateOutputAvailableTarget()),
Tuple.Create<bool,bool,object>(true, false, CreateChooseTarget<int>()),
Tuple.Create<bool,bool,object>(true, false, new BufferBlock<int>().AsObservable().Subscribe(DataflowBlock.NullTarget<int>().AsObserver())),
// Other
Tuple.Create<bool,bool,object>(true, false, new DataflowMessageHeader(1)),
};
// Test all DDAs and DTPAs
foreach (var obj in objectsToTest)
{
if (obj.Item1)
DebuggerAttributes.ValidateDebuggerDisplayReferences(obj.Item3);
if (obj.Item2)
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(obj.Item3);
}
}
}
private static object SendAsyncMessages<T>(ITargetBlock<T> target, int numMessages)
{
for (int i = 0; i < numMessages; i++) target.SendAsync(default(T));
return target;
}
private static TBlock WithLinkedTarget<TBlock, T>(TBlock block) where TBlock : ISourceBlock<T>
{
block.LinkTo(DataflowBlock.NullTarget<T>());
return block;
}
private static ISourceBlock<T> CreateNopLinkSource<T>()
{
var bb = new BufferBlock<T>();
var sos = new StoreOfferingSource<T>();
using (bb.LinkTo(sos)) bb.LinkTo(sos);
bb.Post(default(T));
return sos.GetOfferingSource();
}
private static ISourceBlock<T> CreateFilteringSource<T>()
{
var bb = new BufferBlock<T>();
var sos = new StoreOfferingSource<T>();
bb.LinkTo(sos, i => true);
bb.Post(default(T));
return sos.GetOfferingSource();
}
private static ITargetBlock<T> CreateReceiveTarget<T>()
{
var slt = new StoreLinkedTarget<T>();
slt.ReceiveAsync();
return slt.GetLinkedTarget();
}
private static ITargetBlock<bool> CreateOutputAvailableTarget()
{
var slt = new StoreLinkedTarget<bool>();
slt.OutputAvailableAsync();
return slt.GetLinkedTarget();
}
private static ISourceBlock<T> CreateSendSource<T>()
{
var sos = new StoreOfferingSource<T>();
sos.SendAsync(default(T));
return sos.GetOfferingSource();
}
private static ITargetBlock<T> CreateChooseTarget<T>()
{
var slt = new StoreLinkedTarget<T>();
DataflowBlock.Choose(slt, i => { }, new BufferBlock<T>(), i => { });
return slt.GetLinkedTarget();
}
private class StoreOfferingSource<T> : ITargetBlock<T>
{
private TaskCompletionSource<ISourceBlock<T>> _m_offeringSource = new TaskCompletionSource<ISourceBlock<T>>();
public ISourceBlock<T> GetOfferingSource() { return _m_offeringSource.Task.Result; }
public DataflowMessageStatus OfferMessage(DataflowMessageHeader messageHeader, T messageValue, ISourceBlock<T> source, bool consumeToAccept)
{
if (source != null)
{
_m_offeringSource.TrySetResult(source);
return DataflowMessageStatus.Postponed;
}
return DataflowMessageStatus.Declined;
}
public bool Post(T item) { return false; }
public Task Completion { get { return null; } }
public void Complete() { }
void IDataflowBlock.Fault(Exception exception) { throw new NotSupportedException(); }
}
private class StoreLinkedTarget<T> : IReceivableSourceBlock<T>
{
private TaskCompletionSource<ITargetBlock<T>> _m_linkedTarget = new TaskCompletionSource<ITargetBlock<T>>();
public ITargetBlock<T> GetLinkedTarget() { return _m_linkedTarget.Task.Result; }
public IDisposable LinkTo(ITargetBlock<T> target, DataflowLinkOptions linkOptions)
{
_m_linkedTarget.TrySetResult(target);
return new NopDisposable();
}
private class NopDisposable : IDisposable { public void Dispose() { } }
public bool TryReceive(Predicate<T> filter, out T item) { item = default(T); return false; }
public bool TryReceiveAll(out System.Collections.Generic.IList<T> items) { items = default(System.Collections.Generic.IList<T>); return false; }
public T ConsumeMessage(DataflowMessageHeader messageHeader, ITargetBlock<T> target, out bool messageConsumed) { messageConsumed = true; return default(T); }
public bool ReserveMessage(DataflowMessageHeader messageHeader, ITargetBlock<T> target) { return false; }
public void ReleaseReservation(DataflowMessageHeader messageHeader, ITargetBlock<T> target) { }
public Task Completion { get { return null; } }
public void Complete() { }
void IDataflowBlock.Fault(Exception exception) { throw new NotSupportedException(); }
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections;
using UnityEngine.UI;
#if UNITY_5_3_OR_NEWER
using UnityEditor.SceneManagement;
#endif
[CustomEditor(typeof(ETCDPad))]
public class ETCDPadInspector : Editor {
public string[] unityAxes;
void OnEnable(){
var inputManager = AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/InputManager.asset")[0];
SerializedObject obj = new SerializedObject(inputManager);
SerializedProperty axisArray = obj.FindProperty("m_Axes");
if (axisArray.arraySize > 0){
unityAxes = new string[axisArray.arraySize];
for( int i = 0; i < axisArray.arraySize; ++i ){
var axis = axisArray.GetArrayElementAtIndex(i);
unityAxes[i] = axis.FindPropertyRelative("m_Name").stringValue;
}
}
}
public override void OnInspectorGUI(){
ETCDPad t = (ETCDPad)target;
EditorGUILayout.Space();
t.activated = ETCGuiTools.Toggle("Activated",t.activated,true);
t.visible = ETCGuiTools.Toggle("Visible",t.visible,true);
EditorGUILayout.Space();
t.useFixedUpdate = ETCGuiTools.Toggle("Use Fixed Updae",t.useFixedUpdate,true);
t.isUnregisterAtDisable = ETCGuiTools.Toggle("Unregister at disabling time",t.isUnregisterAtDisable,true);
#region Position & Size
t.showPSInspector = ETCGuiTools.BeginFoldOut( "Position & Size",t.showPSInspector);
if (t.showPSInspector){
ETCGuiTools.BeginGroup();{
// Anchor
t.anchor = (ETCBase.RectAnchor)EditorGUILayout.EnumPopup( "Anchor",t.anchor);
if (t.anchor != ETCBase.RectAnchor.UserDefined){
t.anchorOffet = EditorGUILayout.Vector2Field("Offset",t.anchorOffet);
}
EditorGUILayout.Space();
// Area sprite ratio
Rect rect = t.GetComponent<Image>().sprite.rect;
float ratio = rect.width / rect.height;
// Area Size
if (ratio>=1){
float s = EditorGUILayout.FloatField("Size", t.rectTransform().rect.width);
t.rectTransform().SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal,s);
t.rectTransform().SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical,s/ratio);
}
else{
float s = EditorGUILayout.FloatField("Size", t.rectTransform().rect.height);
t.rectTransform().SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical,s);
t.rectTransform().SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal,s*ratio);
}
t.buttonSizeCoef = EditorGUILayout.FloatField("Button size coef",t.buttonSizeCoef);
}ETCGuiTools.EndGroup();
}
#endregion
#region Axes properties
t.showBehaviourInspector = ETCGuiTools.BeginFoldOut( "Axes properties",t.showBehaviourInspector);
if (t.showBehaviourInspector){
ETCGuiTools.BeginGroup();{
EditorGUILayout.Space();
t.enableKeySimulation = ETCGuiTools.Toggle("Enable key simulation",t.enableKeySimulation,true);
if (t.enableKeySimulation){
t.allowSimulationStandalone = ETCGuiTools.Toggle("Allow simulation on standalone",t.allowSimulationStandalone,true);
t.visibleOnStandalone = ETCGuiTools.Toggle("Force visible",t.visibleOnStandalone,true);
}
EditorGUILayout.Space();
t.dPadAxisCount = (ETCDPad.DPadAxis)EditorGUILayout.EnumPopup("Axes count",t.dPadAxisCount);
EditorGUILayout.Space();
ETCGuiTools.BeginGroup(5);{
ETCAxisInspector.AxisInspector( t.axisX,"Horizontal", ETCBase.ControlType.DPad,false,unityAxes);
}ETCGuiTools.EndGroup();
ETCGuiTools.BeginGroup(5);{
ETCAxisInspector.AxisInspector( t.axisY,"Vertical" ,ETCBase.ControlType.DPad,false,unityAxes);
}ETCGuiTools.EndGroup();
}ETCGuiTools.EndGroup();
}
#endregion
#region Sprite
t.showSpriteInspector = ETCGuiTools.BeginFoldOut( "Sprites",t.showSpriteInspector);
if (t.showSpriteInspector){
ETCGuiTools.BeginGroup();{
Sprite frameSprite = t.GetComponent<Image>().sprite;
EditorGUILayout.BeginHorizontal();
t.GetComponent<Image>().sprite = (Sprite)EditorGUILayout.ObjectField("Frame",t.GetComponent<Image>().sprite,typeof(Sprite),true,GUILayout.MinWidth(100));
t.GetComponent<Image>().color = EditorGUILayout.ColorField("",t.GetComponent<Image>().color,GUILayout.Width(50));
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
Rect spriteRect = new Rect( frameSprite.rect.x/ frameSprite.texture.width,
frameSprite.rect.y/ frameSprite.texture.height,
frameSprite.rect.width/ frameSprite.texture.width,
frameSprite.rect.height/ frameSprite.texture.height);
GUILayout.Space(8);
Rect lastRect = GUILayoutUtility.GetLastRect();
lastRect.x = 20;
lastRect.width = 100;
lastRect.height = 100;
GUILayout.Space(100);
ETCGuiTools.DrawTextureRectPreview( lastRect,spriteRect,t.GetComponent<Image>().sprite.texture,Color.white);
}ETCGuiTools.EndGroup();
}
#endregion
#region Events
t.showEventInspector = ETCGuiTools.BeginFoldOut( "Move Events",t.showEventInspector);
if (t.showEventInspector){
ETCGuiTools.BeginGroup();{
serializedObject.Update();
SerializedProperty movestartEvent = serializedObject.FindProperty("onMoveStart");
EditorGUILayout.PropertyField(movestartEvent, true, null);
serializedObject.ApplyModifiedProperties();
serializedObject.Update();
SerializedProperty moveEvent = serializedObject.FindProperty("onMove");
EditorGUILayout.PropertyField(moveEvent, true, null);
serializedObject.ApplyModifiedProperties();
serializedObject.Update();
SerializedProperty moveSpeedEvent = serializedObject.FindProperty("onMoveSpeed");
EditorGUILayout.PropertyField(moveSpeedEvent, true, null);
serializedObject.ApplyModifiedProperties();
serializedObject.Update();
SerializedProperty moveEndEvent = serializedObject.FindProperty("onMoveEnd");
EditorGUILayout.PropertyField(moveEndEvent, true, null);
serializedObject.ApplyModifiedProperties();
}ETCGuiTools.EndGroup();
}
t.showTouchEventInspector = ETCGuiTools.BeginFoldOut( "Touch Events",t.showTouchEventInspector);
if (t.showTouchEventInspector){
ETCGuiTools.BeginGroup();{
serializedObject.Update();
SerializedProperty touchStartEvent = serializedObject.FindProperty("onTouchStart");
EditorGUILayout.PropertyField(touchStartEvent, true, null);
serializedObject.ApplyModifiedProperties();
serializedObject.Update();
SerializedProperty touchUpEvent = serializedObject.FindProperty("onTouchUp");
EditorGUILayout.PropertyField(touchUpEvent, true, null);
serializedObject.ApplyModifiedProperties();
}ETCGuiTools.EndGroup();
}
t.showDownEventInspector = ETCGuiTools.BeginFoldOut( "Down Events",t.showDownEventInspector);
if (t.showDownEventInspector){
ETCGuiTools.BeginGroup();{
serializedObject.Update();
SerializedProperty downUpEvent = serializedObject.FindProperty("OnDownUp");
EditorGUILayout.PropertyField(downUpEvent, true, null);
serializedObject.ApplyModifiedProperties();
serializedObject.Update();
SerializedProperty downRightEvent = serializedObject.FindProperty("OnDownRight");
EditorGUILayout.PropertyField(downRightEvent, true, null);
serializedObject.ApplyModifiedProperties();
serializedObject.Update();
SerializedProperty downDownEvent = serializedObject.FindProperty("OnDownDown");
EditorGUILayout.PropertyField(downDownEvent, true, null);
serializedObject.ApplyModifiedProperties();
serializedObject.Update();
SerializedProperty downLeftEvent = serializedObject.FindProperty("OnDownLeft");
EditorGUILayout.PropertyField(downLeftEvent, true, null);
serializedObject.ApplyModifiedProperties();
}ETCGuiTools.EndGroup();
}
t.showPressEventInspector = ETCGuiTools.BeginFoldOut( "Press Events",t.showPressEventInspector);
if (t.showPressEventInspector){
ETCGuiTools.BeginGroup();{
serializedObject.Update();
SerializedProperty pressUpEvent = serializedObject.FindProperty("OnPressUp");
EditorGUILayout.PropertyField(pressUpEvent, true, null);
serializedObject.ApplyModifiedProperties();
serializedObject.Update();
SerializedProperty pressRightEvent = serializedObject.FindProperty("OnPressRight");
EditorGUILayout.PropertyField(pressRightEvent, true, null);
serializedObject.ApplyModifiedProperties();
serializedObject.Update();
SerializedProperty pressDownEvent = serializedObject.FindProperty("OnPressDown");
EditorGUILayout.PropertyField(pressDownEvent, true, null);
serializedObject.ApplyModifiedProperties();
serializedObject.Update();
SerializedProperty pressLeftEvent = serializedObject.FindProperty("OnPressLeft");
EditorGUILayout.PropertyField(pressLeftEvent, true, null);
serializedObject.ApplyModifiedProperties();
}ETCGuiTools.EndGroup();
}
#endregion
t.SetAnchorPosition();
if (GUI.changed){
EditorUtility.SetDirty(t);
#if UNITY_5_3_OR_NEWER
EditorSceneManager.MarkSceneDirty( EditorSceneManager.GetActiveScene());
#endif
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using UnityEditor;
using UnityEngine;
namespace PlayFab.PfEditor
{
public class PlayFabEditorSDKTools : UnityEditor.Editor
{
private const int buttonWidth = 150;
public static bool IsInstalled { get { return GetPlayFabSettings() != null; } }
private static Type playFabSettingsType = null;
private static string installedSdkVersion = string.Empty;
private static string latestSdkVersion = string.Empty;
private static UnityEngine.Object sdkFolder;
private static UnityEngine.Object _previousSdkFolderPath;
private static bool isObjectFieldActive;
private static bool isInitialized; //used to check once, gets reset after each compile;
public static bool isSdkSupported = true;
public static void DrawSdkPanel()
{
if (!isInitialized)
{
//SDK is installed.
CheckSdkVersion();
isInitialized = true;
GetLatestSdkVersion();
sdkFolder = FindSdkAsset();
if (sdkFolder != null)
{
PlayFabEditorPrefsSO.Instance.SdkPath = AssetDatabase.GetAssetPath(sdkFolder);
PlayFabEditorDataService.SaveEnvDetails();
}
}
if (IsInstalled)
ShowSdkInstalledMenu();
else
ShowSdkNotInstalledMenu();
}
private static void ShowSdkInstalledMenu()
{
isObjectFieldActive = sdkFolder == null;
if (_previousSdkFolderPath != sdkFolder)
{
// something changed, better save the result.
_previousSdkFolderPath = sdkFolder;
PlayFabEditorPrefsSO.Instance.SdkPath = (AssetDatabase.GetAssetPath(sdkFolder));
PlayFabEditorDataService.SaveEnvDetails();
isObjectFieldActive = false;
}
var labelStyle = new GUIStyle(PlayFabEditorHelper.uiStyle.GetStyle("titleLabel"));
using (new UnityVertical(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1")))
{
EditorGUILayout.LabelField(string.Format("SDK {0} is installed", string.IsNullOrEmpty(installedSdkVersion) ? "Unknown" : installedSdkVersion),
labelStyle, GUILayout.MinWidth(EditorGUIUtility.currentViewWidth));
if (!isObjectFieldActive)
{
GUI.enabled = false;
}
else
{
EditorGUILayout.LabelField(
"An SDK was detected, but we were unable to find the directory. Drag-and-drop the top-level PlayFab SDK folder below.",
PlayFabEditorHelper.uiStyle.GetStyle("orTxt"));
}
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
GUILayout.FlexibleSpace();
sdkFolder = EditorGUILayout.ObjectField(sdkFolder, typeof(UnityEngine.Object), false, GUILayout.MaxWidth(200));
GUILayout.FlexibleSpace();
}
if (!isObjectFieldActive)
{
// this is a hack to prevent our "block while loading technique" from breaking up at this point.
GUI.enabled = !EditorApplication.isCompiling && PlayFabEditor.blockingRequests.Count == 0;
}
if (isSdkSupported && sdkFolder != null)
{
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("REMOVE SDK", PlayFabEditorHelper.uiStyle.GetStyle("textButton"), GUILayout.MinHeight(32), GUILayout.MinWidth(200)))
{
RemoveSdk();
}
GUILayout.FlexibleSpace();
}
}
}
if (sdkFolder != null)
{
using (new UnityVertical(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1")))
{
isSdkSupported = false;
string[] versionNumber = !string.IsNullOrEmpty(installedSdkVersion) ? installedSdkVersion.Split('.') : new string[0];
var numerical = 0;
if (string.IsNullOrEmpty(installedSdkVersion) || versionNumber == null || versionNumber.Length == 0 ||
(versionNumber.Length > 0 && int.TryParse(versionNumber[0], out numerical) && numerical < 2))
{
//older version of the SDK
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
EditorGUILayout.LabelField("Most of the Editor Extensions depend on SDK versions >2.0. Consider upgrading to the get most features.", PlayFabEditorHelper.uiStyle.GetStyle("orTxt"));
}
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("READ THE UPGRADE GUIDE", PlayFabEditorHelper.uiStyle.GetStyle("textButton"), GUILayout.MinHeight(32)))
{
Application.OpenURL("https://github.com/PlayFab/UnitySDK/blob/master/UPGRADE.md");
}
GUILayout.FlexibleSpace();
}
}
else if (numerical >= 2)
{
isSdkSupported = true;
}
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
if (ShowSDKUpgrade() && isSdkSupported)
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("Upgrade to " + latestSdkVersion, PlayFabEditorHelper.uiStyle.GetStyle("Button"), GUILayout.MinHeight(32)))
{
UpgradeSdk();
}
GUILayout.FlexibleSpace();
}
else if (isSdkSupported)
{
GUILayout.FlexibleSpace();
EditorGUILayout.LabelField("You have the latest SDK!", labelStyle, GUILayout.MinHeight(32));
GUILayout.FlexibleSpace();
}
}
}
}
if (isSdkSupported && string.IsNullOrEmpty(PlayFabEditorDataService.SharedSettings.TitleId))
{
using (new UnityVertical(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1")))
{
EditorGUILayout.LabelField("Before making PlayFab API calls, the SDK must be configured to your PlayFab Title.", PlayFabEditorHelper.uiStyle.GetStyle("orTxt"));
using (new UnityHorizontal())
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("SET MY TITLE", PlayFabEditorHelper.uiStyle.GetStyle("textButton")))
{
PlayFabEditorMenu.OnSettingsClicked();
}
GUILayout.FlexibleSpace();
}
}
}
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1")))
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("VIEW RELEASE NOTES", PlayFabEditorHelper.uiStyle.GetStyle("textButton"), GUILayout.MinHeight(32), GUILayout.MinWidth(200)))
{
Application.OpenURL("https://api.playfab.com/releaseNotes/");
}
GUILayout.FlexibleSpace();
}
}
private static void ShowSdkNotInstalledMenu()
{
using (new UnityVertical(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1")))
{
var labelStyle = new GUIStyle(PlayFabEditorHelper.uiStyle.GetStyle("titleLabel"));
EditorGUILayout.LabelField("No SDK is installed.", labelStyle, GUILayout.MinWidth(EditorGUIUtility.currentViewWidth));
GUILayout.Space(20);
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1")))
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("Refresh", PlayFabEditorHelper.uiStyle.GetStyle("Button"), GUILayout.MaxWidth(buttonWidth), GUILayout.MinHeight(32)))
playFabSettingsType = null;
GUILayout.FlexibleSpace();
if (GUILayout.Button("Install PlayFab SDK", PlayFabEditorHelper.uiStyle.GetStyle("Button"), GUILayout.MaxWidth(buttonWidth), GUILayout.MinHeight(32)))
ImportLatestSDK();
GUILayout.FlexibleSpace();
}
}
}
public static void ImportLatestSDK()
{
PlayFabEditorHttp.MakeDownloadCall("https://api.playfab.com/sdks/download/unity-via-edex", (fileName) =>
{
Debug.Log("PlayFab SDK Install: Complete");
AssetDatabase.ImportPackage(fileName, false);
// attempts to re-import any changed assets (which ImportPackage doesn't implicitly do)
AssetDatabase.Refresh();
PlayFabEditorPrefsSO.Instance.SdkPath = PlayFabEditorHelper.DEFAULT_SDK_LOCATION;
PlayFabEditorDataService.SaveEnvDetails();
});
}
public static Type GetPlayFabSettings()
{
if (playFabSettingsType == typeof(object))
return null; // Sentinel value to indicate that PlayFabSettings doesn't exist
if (playFabSettingsType != null)
return playFabSettingsType;
playFabSettingsType = typeof(object); // Sentinel value to indicate that PlayFabSettings doesn't exist
var allAssemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (var assembly in allAssemblies)
{
Type[] assemblyTypes;
try
{
assemblyTypes = assembly.GetTypes();
}
catch (ReflectionTypeLoadException e)
{
assemblyTypes = e.Types;
}
foreach (var eachType in assemblyTypes)
if (eachType != null)
if (eachType.Name == PlayFabEditorHelper.PLAYFAB_SETTINGS_TYPENAME)
playFabSettingsType = eachType;
}
//if (playFabSettingsType == typeof(object))
// Debug.LogWarning("Should not have gotten here: " + allAssemblies.Length);
//else
// Debug.Log("Found Settings: " + allAssemblies.Length + ", " + playFabSettingsType.Assembly.FullName);
return playFabSettingsType == typeof(object) ? null : playFabSettingsType;
}
private static void CheckSdkVersion()
{
if (!string.IsNullOrEmpty(installedSdkVersion))
return;
var types = new List<Type>();
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
try
{
foreach (var type in assembly.GetTypes())
if (type.Name == "PlayFabVersion" || type.Name == PlayFabEditorHelper.PLAYFAB_SETTINGS_TYPENAME)
types.Add(type);
}
catch (ReflectionTypeLoadException)
{
// For this failure, silently skip this assembly unless we have some expectation that it contains PlayFab
if (assembly.FullName.StartsWith("Assembly-CSharp")) // The standard "source-code in unity proj" assembly name
Debug.LogWarning("PlayFab EdEx Error, failed to access the main CSharp assembly that probably contains PlayFab. Please report this on the PlayFab Forums");
continue;
}
}
foreach (var type in types)
{
foreach (var property in type.GetProperties())
if (property.Name == "SdkVersion" || property.Name == "SdkRevision")
installedSdkVersion += property.GetValue(property, null).ToString();
foreach (var field in type.GetFields())
if (field.Name == "SdkVersion" || field.Name == "SdkRevision")
installedSdkVersion += field.GetValue(field).ToString();
}
}
private static UnityEngine.Object FindSdkAsset()
{
UnityEngine.Object sdkAsset = null;
// look in editor prefs
if (PlayFabEditorPrefsSO.Instance.SdkPath != null)
{
sdkAsset = AssetDatabase.LoadAssetAtPath(PlayFabEditorPrefsSO.Instance.SdkPath, typeof(UnityEngine.Object));
}
if (sdkAsset != null)
return sdkAsset;
sdkAsset = AssetDatabase.LoadAssetAtPath(PlayFabEditorHelper.DEFAULT_SDK_LOCATION, typeof(UnityEngine.Object));
if (sdkAsset != null)
return sdkAsset;
var fileList = Directory.GetDirectories(Application.dataPath, "*PlayFabSdk", SearchOption.AllDirectories);
if (fileList.Length == 0)
return null;
var relPath = fileList[0].Substring(fileList[0].LastIndexOf("Assets"));
return AssetDatabase.LoadAssetAtPath(relPath, typeof(UnityEngine.Object));
}
private static bool ShowSDKUpgrade()
{
if (string.IsNullOrEmpty(latestSdkVersion) || latestSdkVersion == "Unknown")
{
return false;
}
if (string.IsNullOrEmpty(installedSdkVersion) || installedSdkVersion == "Unknown")
{
return true;
}
string[] currrent = installedSdkVersion.Split('.');
string[] latest = latestSdkVersion.Split('.');
if (int.Parse(currrent[0]) < 2)
{
return false;
}
return int.Parse(latest[0]) > int.Parse(currrent[0])
|| int.Parse(latest[1]) > int.Parse(currrent[1])
|| int.Parse(latest[2]) > int.Parse(currrent[2]);
}
private static void UpgradeSdk()
{
if (EditorUtility.DisplayDialog("Confirm SDK Upgrade", "This action will remove the current PlayFab SDK and install the lastet version. Related plug-ins will need to be manually upgraded.", "Confirm", "Cancel"))
{
RemoveSdk(false);
ImportLatestSDK();
}
}
private static void RemoveSdk(bool prompt = true)
{
if (prompt && !EditorUtility.DisplayDialog("Confirm SDK Removal", "This action will remove the current PlayFab SDK. Related plug-ins will need to be manually removed.", "Confirm", "Cancel"))
return;
//try to clean-up the plugin dirs
if (Directory.Exists(Application.dataPath + "/Plugins"))
{
var folders = Directory.GetDirectories(Application.dataPath + "/Plugins", "PlayFabShared", SearchOption.AllDirectories);
foreach (var folder in folders)
FileUtil.DeleteFileOrDirectory(folder);
//try to clean-up the plugin files (if anything is left)
var files = Directory.GetFiles(Application.dataPath + "/Plugins", "PlayFabErrors.cs", SearchOption.AllDirectories);
foreach (var file in files)
FileUtil.DeleteFileOrDirectory(file);
}
if (FileUtil.DeleteFileOrDirectory(PlayFabEditorPrefsSO.Instance.SdkPath))
{
PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnSuccess, "PlayFab SDK Removed!");
// HACK for 5.4, AssetDatabase.Refresh(); seems to cause the install to fail.
if (prompt)
{
AssetDatabase.Refresh();
}
}
else
{
PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnError, "An unknown error occured and the PlayFab SDK could not be removed.");
}
}
private static void GetLatestSdkVersion()
{
var threshold = PlayFabEditorPrefsSO.Instance.EdSet_lastSdkVersionCheck != DateTime.MinValue ? PlayFabEditorPrefsSO.Instance.EdSet_lastSdkVersionCheck.AddHours(1) : DateTime.MinValue;
if (DateTime.Today > threshold)
{
PlayFabEditorHttp.MakeGitHubApiCall("https://api.github.com/repos/PlayFab/UnitySDK/git/refs/tags", (version) =>
{
latestSdkVersion = version ?? "Unknown";
PlayFabEditorPrefsSO.Instance.EdSet_latestSdkVersion = latestSdkVersion;
});
}
else
{
latestSdkVersion = PlayFabEditorPrefsSO.Instance.EdSet_latestSdkVersion;
}
}
}
}
| |
using Neo.Compiler.Optimizer;
using Neo.IO.Json;
using System;
using System.Collections.Generic;
using System.IO;
namespace Neo.Compiler.MSIL.UnitTests.Utils
{
public class BuildScript
{
public bool IsBuild { get; protected set; }
public bool UseOptimizer { get; protected set; }
public Exception Error { get; protected set; }
public ILModule modIL { get; private set; }
public ModuleConverter converterIL { get; private set; }
public byte[] finalNEF { get; protected set; }
public JObject finalABI { get; protected set; }
public string finalManifest { get; protected set; }
public JObject debugInfo { get; private set; }
public BuildScript()
{
}
public void Build(Stream fs, Stream fspdb, bool optimizer)
{
this.IsBuild = false;
this.Error = null;
this.UseOptimizer = optimizer;
var log = new DefLogger();
this.modIL = new ILModule(log);
try
{
modIL.LoadModule(fs, fspdb);
}
catch (Exception err)
{
log.Log("LoadModule Error:" + err.ToString());
this.Error = err;
return;
}
converterIL = new ModuleConverter(log);
Dictionary<int, int> addrConvTable = null;
ConvOption option = new ConvOption();
#if NDEBUG
try
#endif
{
converterIL.Convert(modIL, option);
finalNEF = converterIL.outModule.Build();
if (optimizer)
{
List<int> entryPoints = new List<int>();
foreach (var f in converterIL.outModule.mapMethods.Values)
{
if (!entryPoints.Contains(f.funcaddr))
entryPoints.Add(f.funcaddr);
}
var opbytes = NefOptimizeTool.Optimize(finalNEF, entryPoints.ToArray(), out addrConvTable);
float ratio = (opbytes.Length * 100.0f) / (float)finalNEF.Length;
log.Log("optimization ratio = " + ratio + "%");
finalNEF = opbytes;
}
IsBuild = true;
}
#if NDEBUG
catch (Exception err)
{
this.Error = err;
log.Log("Convert IL->ASM Error:" + err.ToString());
return;
}
#endif
try
{
finalABI = FuncExport.Export(converterIL.outModule, finalNEF, addrConvTable);
}
catch (Exception err)
{
log.Log("Gen Abi Error:" + err.ToString());
this.Error = err;
return;
}
try
{
debugInfo = DebugExport.Export(converterIL.outModule, finalNEF, addrConvTable);
}
catch (Exception err)
{
log.Log("Gen debugInfo Error:" + err.ToString());
this.Error = err;
return;
}
try
{
finalManifest = FuncExport.GenerateManifest(finalABI, converterIL.outModule);
}
catch (Exception err)
{
log.Log("Gen Manifest Error:" + err.ToString());
this.Error = err;
return;
}
}
public string[] GetAllILFunction()
{
List<string> lists = new List<string>();
foreach (var _class in modIL.mapType)
{
foreach (var method in _class.Value.methods)
{
var name = method.Key;
lists.Add(name);
}
}
return lists.ToArray();
}
public ILMethod FindMethod(string fromclass, string method)
{
foreach (var _class in modIL.mapType)
{
var indexbegin = _class.Key.LastIndexOf(".");
var classname = _class.Key;
if (indexbegin > 0)
classname = classname.Substring(indexbegin + 1);
if (classname == fromclass)
{
foreach (var _method in _class.Value.methods)
{
var indexmethodname = _method.Key.LastIndexOf("::");
var methodname = _method.Key.Substring(indexmethodname + 2);
var indexparams = methodname.IndexOf("(");
if (indexparams > 0)
{
methodname = methodname.Substring(0, indexparams);
}
if (methodname == method)
return _method.Value;
}
}
}
return null;
}
public string GetFullMethodName(string fromclass, string method)
{
foreach (var _class in modIL.mapType)
{
var indexbegin = _class.Key.LastIndexOf("::");
var classname = _class.Key.Substring(indexbegin + 2);
if (classname == fromclass)
{
foreach (var _method in _class.Value.methods)
{
var indexmethodname = _method.Key.LastIndexOf("::");
var methodname = _method.Key.Substring(indexmethodname + 2);
if (methodname == method)
return _method.Key;
}
}
}
return null;
}
public NeoMethod GetNEOVMMethod(ILMethod method)
{
var neomethod = this.converterIL.methodLink[method];
return neomethod;
}
public NeoMethod[] GetAllNEOVMMethod()
{
return new List<NeoMethod>(this.converterIL.methodLink.Values).ToArray();
}
public void DumpNEF()
{
{
Console.WriteLine("dump:");
foreach (var c in this.converterIL.outModule.totalCodes)
{
var line = c.Key.ToString("X04") + "=>" + c.Value.ToString();
if (c.Value.bytes != null && c.Value.bytes.Length > 0)
{
line += " HEX:";
foreach (var b in c.Value.bytes)
{
line += b.ToString("X02");
}
}
Console.WriteLine(line);
}
}
}
public byte[] NeoMethodToBytes(NeoMethod method)
{
List<byte> bytes = new List<byte>();
foreach (var c in method.body_Codes.Values)
{
bytes.Add((byte)c.code);
if (c.bytes != null)
for (var i = 0; i < c.bytes.Length; i++)
{
bytes.Add(c.bytes[i]);
}
}
return bytes.ToArray();
}
}
}
| |
// 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.Reflection;
using Xunit;
namespace System.Tests
{
public static class ActivatorTests
{
[Fact]
public static void CreateInstance()
{
// Passing null args is equivalent to an empty array of args.
Choice1 c = (Choice1)(Activator.CreateInstance(typeof(Choice1), null));
Assert.Equal(1, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { }));
Assert.Equal(1, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { 42 }));
Assert.Equal(2, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { "Hello" }));
Assert.Equal(3, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { 5.1, "Hello" }));
Assert.Equal(4, c.I);
Activator.CreateInstance(typeof(StructTypeWithoutReflectionMetadata));
}
[Fact]
public static void CreateInstance_ConstructorWithPrimitive_PerformsPrimitiveWidening()
{
// Primitive widening is allowed by the binder, but not by Dynamic.DelegateInvoke().
Choice1 c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { (short)-2 }));
Assert.Equal(2, c.I);
}
[Fact]
public static void CreateInstance_ConstructorWithParamsParameter()
{
// C# params arguments are honored by Activator.CreateInstance()
Choice1 c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarArgs() }));
Assert.Equal(5, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarArgs(), "P1" }));
Assert.Equal(5, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarArgs(), "P1", "P2" }));
Assert.Equal(5, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarStringArgs() }));
Assert.Equal(6, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarStringArgs(), "P1" }));
Assert.Equal(6, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarStringArgs(), "P1", "P2" }));
Assert.Equal(6, c.I);
}
[Fact]
public static void CreateInstance_Invalid()
{
Assert.Throws<ArgumentNullException>("type", () => Activator.CreateInstance(null)); // Type is null
Assert.Throws<ArgumentNullException>("type", () => Activator.CreateInstance(null, new object[0])); // Type is null
Assert.Throws<AmbiguousMatchException>(() => Activator.CreateInstance(typeof(Choice1), new object[] { null }));
// C# designated optional parameters are not optional as far as Activator.CreateInstance() is concerned.
Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance(typeof(Choice1), new object[] { 5.1 }));
Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance(typeof(Choice1), new object[] { 5.1, Type.Missing }));
// Invalid params args
Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance(typeof(Choice1), new object[] { new VarStringArgs(), 5, 6 }));
// Primitive widening not supported for "params" arguments.
//
// (This is probably an accidental behavior on the desktop as the default binder specifically checks to see if the params arguments are widenable to the
// params array element type and gives it the go-ahead if it is. Unfortunately, the binder then bollixes itself by using Array.Copy() to copy
// the params arguments. Since Array.Copy() doesn't tolerate this sort of type mismatch, it throws an InvalidCastException which bubbles out
// out of Activator.CreateInstance. Accidental or not, we'll inherit that behavior on .NET Native.)
Assert.Throws<InvalidCastException>(() => Activator.CreateInstance(typeof(Choice1), new object[] { new VarIntArgs(), 1, (short)2 }));
Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance(typeof(TypeWithoutDefaultCtor))); // Type has no default constructor
Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(typeof(TypeWithDefaultCtorThatThrows))); // Type has a default constructor throws an exception
Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance(typeof(AbstractTypeWithDefaultCtor))); // Type is abstract
Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance(typeof(IInterfaceType))); // Type is an interface
#if netcoreapp
// Type is not a valid RuntimeType
Assert.Throws<ArgumentException>("type", () => Activator.CreateInstance(Helpers.NonRuntimeType()));
#endif // netcoreapp
}
[Fact]
public static void CreateInstance_Generic()
{
Choice1 c = Activator.CreateInstance<Choice1>();
Assert.Equal(1, c.I);
Activator.CreateInstance<DateTime>();
Activator.CreateInstance<StructTypeWithoutReflectionMetadata>();
}
[Fact]
public static void CreateInstance_Generic_Invalid()
{
Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance<int[]>()); // Cannot create array type
Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance<TypeWithoutDefaultCtor>()); // Type has no default constructor
Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance<TypeWithDefaultCtorThatThrows>()); // Type has a default constructor that throws
Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance<AbstractTypeWithDefaultCtor>()); // Type is abstract
Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance<IInterfaceType>()); // Type is an interface
}
[Fact]
public static void TestActivatorOnNonActivatableFinalizableTypes()
{
// On runtimes where the generic Activator is implemented with special codegen intrinsics, we might allocate
// an uninitialized instance of the object before we realize there's no default constructor to run.
// Make sure this has no observable side effects.
Assert.ThrowsAny<MissingMemberException>(() => { Activator.CreateInstance<TypeWithPrivateDefaultCtorAndFinalizer>(); });
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Assert.False(TypeWithPrivateDefaultCtorAndFinalizer.WasCreated);
}
class PrivateType
{
public PrivateType() { }
}
class PrivateTypeWithDefaultCtor
{
private PrivateTypeWithDefaultCtor() { }
}
class PrivateTypeWithoutDefaultCtor
{
private PrivateTypeWithoutDefaultCtor(int x) { }
}
class PrivateTypeWithDefaultCtorThatThrows
{
public PrivateTypeWithDefaultCtorThatThrows() { throw new Exception(); }
}
[Fact]
public static void CreateInstance_Type_Bool()
{
Assert.Equal(typeof(PrivateType), Activator.CreateInstance(typeof(PrivateType), true).GetType());
Assert.Equal(typeof(PrivateType), Activator.CreateInstance(typeof(PrivateType), false).GetType());
Assert.Equal(typeof(PrivateTypeWithDefaultCtor), Activator.CreateInstance(typeof(PrivateTypeWithDefaultCtor), true).GetType());
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(PrivateTypeWithDefaultCtor), false).GetType());
Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(typeof(PrivateTypeWithDefaultCtorThatThrows), true).GetType());
Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(typeof(PrivateTypeWithDefaultCtorThatThrows), false).GetType());
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(PrivateTypeWithoutDefaultCtor), true).GetType());
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(PrivateTypeWithoutDefaultCtor), false).GetType());
}
public class Choice1 : Attribute
{
public Choice1()
{
I = 1;
}
public Choice1(int i)
{
I = 2;
}
public Choice1(string s)
{
I = 3;
}
public Choice1(double d, string optionalS = "Hey")
{
I = 4;
}
public Choice1(VarArgs varArgs, params object[] parameters)
{
I = 5;
}
public Choice1(VarStringArgs varArgs, params string[] parameters)
{
I = 6;
}
public Choice1(VarIntArgs varArgs, params int[] parameters)
{
I = 7;
}
public int I;
}
public class VarArgs { }
public class VarStringArgs { }
public class VarIntArgs { }
public class TypeWithPrivateDefaultCtorAndFinalizer
{
public static bool WasCreated { get; private set; }
private TypeWithPrivateDefaultCtorAndFinalizer() { }
~TypeWithPrivateDefaultCtorAndFinalizer()
{
WasCreated = true;
}
}
private interface IInterfaceType
{
}
public abstract class AbstractTypeWithDefaultCtor
{
public AbstractTypeWithDefaultCtor() { }
}
public struct StructTypeWithoutReflectionMetadata { }
public class TypeWithoutDefaultCtor
{
private TypeWithoutDefaultCtor(int x) { }
}
public class TypeWithDefaultCtorThatThrows
{
public TypeWithDefaultCtorThatThrows() { throw new Exception(); }
}
}
}
| |
// 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 Xunit;
namespace System.Linq.Expressions.Tests
{
public static class LambdaDivideNullableTests
{
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaDivideNullableDecimalTest(bool useInterpreter)
{
decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyDivideNullableDecimal(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaDivideNullableDoubleTest(bool useInterpreter)
{
double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyDivideNullableDouble(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaDivideNullableFloatTest(bool useInterpreter)
{
float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyDivideNullableFloat(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaDivideNullableIntTest(bool useInterpreter)
{
int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyDivideNullableInt(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaDivideNullableLongTest(bool useInterpreter)
{
long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyDivideNullableLong(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaDivideNullableShortTest(bool useInterpreter)
{
short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyDivideNullableShort(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaDivideNullableUIntTest(bool useInterpreter)
{
uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyDivideNullableUInt(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaDivideNullableULongTest(bool useInterpreter)
{
ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyDivideNullableULong(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaDivideNullableUShortTest(bool useInterpreter)
{
ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyDivideNullableUShort(values[i], values[j], useInterpreter);
}
}
}
#endregion
#region Test verifiers
private enum ResultType
{
Success,
DivideByZero,
Overflow
}
#region Verify decimal?
private static void VerifyDivideNullableDecimal(decimal? a, decimal? b, bool useInterpreter)
{
bool divideByZero;
decimal? expected;
if (a.HasValue && b == 0)
{
divideByZero = true;
expected = null;
}
else
{
divideByZero = false;
expected = a / b;
}
ParameterExpression p0 = Expression.Parameter(typeof(decimal?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(decimal?), "p1");
// verify with parameters supplied
Expression<Func<decimal?>> e1 =
Expression.Lambda<Func<decimal?>>(
Expression.Invoke(
Expression.Lambda<Func<decimal?, decimal?, decimal?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(decimal?)),
Expression.Constant(b, typeof(decimal?))
}),
Enumerable.Empty<ParameterExpression>());
Func<decimal?> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<decimal?, decimal?, Func<decimal?>>> e2 =
Expression.Lambda<Func<decimal?, decimal?, Func<decimal?>>>(
Expression.Lambda<Func<decimal?>>(
Expression.Divide(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<decimal?, decimal?, Func<decimal?>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<decimal?, decimal?, decimal?>>> e3 =
Expression.Lambda<Func<Func<decimal?, decimal?, decimal?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<decimal?, decimal?, decimal?>>>(
Expression.Lambda<Func<decimal?, decimal?, decimal?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<decimal?, decimal?, decimal?> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<decimal?, decimal?, decimal?>>> e4 =
Expression.Lambda<Func<Func<decimal?, decimal?, decimal?>>>(
Expression.Lambda<Func<decimal?, decimal?, decimal?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<decimal?, decimal?, decimal?>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<decimal?, Func<decimal?, decimal?>>> e5 =
Expression.Lambda<Func<decimal?, Func<decimal?, decimal?>>>(
Expression.Lambda<Func<decimal?, decimal?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<decimal?, Func<decimal?, decimal?>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<decimal?, decimal?>>> e6 =
Expression.Lambda<Func<Func<decimal?, decimal?>>>(
Expression.Invoke(
Expression.Lambda<Func<decimal?, Func<decimal?, decimal?>>>(
Expression.Lambda<Func<decimal?, decimal?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(decimal?)) }),
Enumerable.Empty<ParameterExpression>());
Func<decimal?, decimal?> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#region Verify double?
private static void VerifyDivideNullableDouble(double? a, double? b, bool useInterpreter)
{
double? expected = a / b;
ParameterExpression p0 = Expression.Parameter(typeof(double?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(double?), "p1");
// verify with parameters supplied
Expression<Func<double?>> e1 =
Expression.Lambda<Func<double?>>(
Expression.Invoke(
Expression.Lambda<Func<double?, double?, double?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(double?)),
Expression.Constant(b, typeof(double?))
}),
Enumerable.Empty<ParameterExpression>());
Func<double?> f1 = e1.Compile(useInterpreter);
Assert.Equal(expected, f1());
// verify with values passed to make parameters
Expression<Func<double?, double?, Func<double?>>> e2 =
Expression.Lambda<Func<double?, double?, Func<double?>>>(
Expression.Lambda<Func<double?>>(
Expression.Divide(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<double?, double?, Func<double?>> f2 = e2.Compile(useInterpreter);
Assert.Equal(expected, f2(a, b)());
// verify with values directly passed
Expression<Func<Func<double?, double?, double?>>> e3 =
Expression.Lambda<Func<Func<double?, double?, double?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<double?, double?, double?>>>(
Expression.Lambda<Func<double?, double?, double?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<double?, double?, double?> f3 = e3.Compile(useInterpreter)();
Assert.Equal(expected, f3(a, b));
// verify as a function generator
Expression<Func<Func<double?, double?, double?>>> e4 =
Expression.Lambda<Func<Func<double?, double?, double?>>>(
Expression.Lambda<Func<double?, double?, double?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<double?, double?, double?>> f4 = e4.Compile(useInterpreter);
Assert.Equal(expected, f4()(a, b));
// verify with currying
Expression<Func<double?, Func<double?, double?>>> e5 =
Expression.Lambda<Func<double?, Func<double?, double?>>>(
Expression.Lambda<Func<double?, double?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<double?, Func<double?, double?>> f5 = e5.Compile(useInterpreter);
Assert.Equal(expected, f5(a)(b));
// verify with one parameter
Expression<Func<Func<double?, double?>>> e6 =
Expression.Lambda<Func<Func<double?, double?>>>(
Expression.Invoke(
Expression.Lambda<Func<double?, Func<double?, double?>>>(
Expression.Lambda<Func<double?, double?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(double?)) }),
Enumerable.Empty<ParameterExpression>());
Func<double?, double?> f6 = e6.Compile(useInterpreter)();
Assert.Equal(expected, f6(b));
}
#endregion
#region Verify float?
private static void VerifyDivideNullableFloat(float? a, float? b, bool useInterpreter)
{
float? expected = a / b;
ParameterExpression p0 = Expression.Parameter(typeof(float?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(float?), "p1");
// verify with parameters supplied
Expression<Func<float?>> e1 =
Expression.Lambda<Func<float?>>(
Expression.Invoke(
Expression.Lambda<Func<float?, float?, float?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(float?)),
Expression.Constant(b, typeof(float?))
}),
Enumerable.Empty<ParameterExpression>());
Func<float?> f1 = e1.Compile(useInterpreter);
Assert.Equal(expected, f1());
// verify with values passed to make parameters
Expression<Func<float?, float?, Func<float?>>> e2 =
Expression.Lambda<Func<float?, float?, Func<float?>>>(
Expression.Lambda<Func<float?>>(
Expression.Divide(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<float?, float?, Func<float?>> f2 = e2.Compile(useInterpreter);
Assert.Equal(expected, f2(a, b)());
// verify with values directly passed
Expression<Func<Func<float?, float?, float?>>> e3 =
Expression.Lambda<Func<Func<float?, float?, float?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<float?, float?, float?>>>(
Expression.Lambda<Func<float?, float?, float?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<float?, float?, float?> f3 = e3.Compile(useInterpreter)();
Assert.Equal(expected, f3(a, b));
// verify as a function generator
Expression<Func<Func<float?, float?, float?>>> e4 =
Expression.Lambda<Func<Func<float?, float?, float?>>>(
Expression.Lambda<Func<float?, float?, float?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<float?, float?, float?>> f4 = e4.Compile(useInterpreter);
Assert.Equal(expected, f4()(a, b));
// verify with currying
Expression<Func<float?, Func<float?, float?>>> e5 =
Expression.Lambda<Func<float?, Func<float?, float?>>>(
Expression.Lambda<Func<float?, float?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<float?, Func<float?, float?>> f5 = e5.Compile(useInterpreter);
Assert.Equal(expected, f5(a)(b));
// verify with one parameter
Expression<Func<Func<float?, float?>>> e6 =
Expression.Lambda<Func<Func<float?, float?>>>(
Expression.Invoke(
Expression.Lambda<Func<float?, Func<float?, float?>>>(
Expression.Lambda<Func<float?, float?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(float?)) }),
Enumerable.Empty<ParameterExpression>());
Func<float?, float?> f6 = e6.Compile(useInterpreter)();
Assert.Equal(expected, f6(b));
}
#endregion
#region Verify int?
private static void VerifyDivideNullableInt(int? a, int? b, bool useInterpreter)
{
ResultType outcome;
int? expected = null;
if (a.HasValue && b == 0)
{
outcome = ResultType.DivideByZero;
}
else if (a == int.MinValue && b == -1)
{
outcome = ResultType.Overflow;
}
else
{
expected = a / b;
outcome = ResultType.Success;
}
ParameterExpression p0 = Expression.Parameter(typeof(int?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(int?), "p1");
// verify with parameters supplied
Expression<Func<int?>> e1 =
Expression.Lambda<Func<int?>>(
Expression.Invoke(
Expression.Lambda<Func<int?, int?, int?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?))
}),
Enumerable.Empty<ParameterExpression>());
Func<int?> f1 = e1.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f1());
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f1());
break;
default:
Assert.Equal(expected, f1());
break;
}
// verify with values passed to make parameters
Expression<Func<int?, int?, Func<int?>>> e2 =
Expression.Lambda<Func<int?, int?, Func<int?>>>(
Expression.Lambda<Func<int?>>(
Expression.Divide(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<int?, int?, Func<int?>> f2 = e2.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f2(a, b)());
break;
default:
Assert.Equal(expected, f2(a, b)());
break;
}
// verify with values directly passed
Expression<Func<Func<int?, int?, int?>>> e3 =
Expression.Lambda<Func<Func<int?, int?, int?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<int?, int?, int?>>>(
Expression.Lambda<Func<int?, int?, int?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<int?, int?, int?> f3 = e3.Compile(useInterpreter)();
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f3(a, b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f3(a, b));
break;
default:
Assert.Equal(expected, f3(a, b));
break;
}
// verify as a function generator
Expression<Func<Func<int?, int?, int?>>> e4 =
Expression.Lambda<Func<Func<int?, int?, int?>>>(
Expression.Lambda<Func<int?, int?, int?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<int?, int?, int?>> f4 = e4.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f4()(a, b));
break;
default:
Assert.Equal(expected, f4()(a, b));
break;
}
// verify with currying
Expression<Func<int?, Func<int?, int?>>> e5 =
Expression.Lambda<Func<int?, Func<int?, int?>>>(
Expression.Lambda<Func<int?, int?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<int?, Func<int?, int?>> f5 = e5.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f5(a)(b));
break;
default:
Assert.Equal(expected, f5(a)(b));
break;
}
// verify with one parameter
Expression<Func<Func<int?, int?>>> e6 =
Expression.Lambda<Func<Func<int?, int?>>>(
Expression.Invoke(
Expression.Lambda<Func<int?, Func<int?, int?>>>(
Expression.Lambda<Func<int?, int?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(int?)) }),
Enumerable.Empty<ParameterExpression>());
Func<int?, int?> f6 = e6.Compile(useInterpreter)();
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f6(b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f6(b));
break;
default:
Assert.Equal(expected, f6(b));
break;
}
}
#endregion
#region Verify long?
private static void VerifyDivideNullableLong(long? a, long? b, bool useInterpreter)
{
ResultType outcome;
long? expected = null;
if (a.HasValue && b == 0)
{
outcome = ResultType.DivideByZero;
}
else if (a == long.MinValue && b == -1)
{
outcome = ResultType.Overflow;
}
else
{
expected = a / b;
outcome = ResultType.Success;
}
ParameterExpression p0 = Expression.Parameter(typeof(long?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(long?), "p1");
// verify with parameters supplied
Expression<Func<long?>> e1 =
Expression.Lambda<Func<long?>>(
Expression.Invoke(
Expression.Lambda<Func<long?, long?, long?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(long?))
}),
Enumerable.Empty<ParameterExpression>());
Func<long?> f1 = e1.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f1());
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f1());
break;
default:
Assert.Equal(expected, f1());
break;
}
// verify with values passed to make parameters
Expression<Func<long?, long?, Func<long?>>> e2 =
Expression.Lambda<Func<long?, long?, Func<long?>>>(
Expression.Lambda<Func<long?>>(
Expression.Divide(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<long?, long?, Func<long?>> f2 = e2.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f2(a, b)());
break;
default:
Assert.Equal(expected, f2(a, b)());
break;
}
// verify with values directly passed
Expression<Func<Func<long?, long?, long?>>> e3 =
Expression.Lambda<Func<Func<long?, long?, long?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<long?, long?, long?>>>(
Expression.Lambda<Func<long?, long?, long?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<long?, long?, long?> f3 = e3.Compile(useInterpreter)();
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f3(a, b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f3(a, b));
break;
default:
Assert.Equal(expected, f3(a, b));
break;
}
// verify as a function generator
Expression<Func<Func<long?, long?, long?>>> e4 =
Expression.Lambda<Func<Func<long?, long?, long?>>>(
Expression.Lambda<Func<long?, long?, long?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<long?, long?, long?>> f4 = e4.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f4()(a, b));
break;
default:
Assert.Equal(expected, f4()(a, b));
break;
}
// verify with currying
Expression<Func<long?, Func<long?, long?>>> e5 =
Expression.Lambda<Func<long?, Func<long?, long?>>>(
Expression.Lambda<Func<long?, long?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<long?, Func<long?, long?>> f5 = e5.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f5(a)(b));
break;
default:
Assert.Equal(expected, f5(a)(b));
break;
}
// verify with one parameter
Expression<Func<Func<long?, long?>>> e6 =
Expression.Lambda<Func<Func<long?, long?>>>(
Expression.Invoke(
Expression.Lambda<Func<long?, Func<long?, long?>>>(
Expression.Lambda<Func<long?, long?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(long?)) }),
Enumerable.Empty<ParameterExpression>());
Func<long?, long?> f6 = e6.Compile(useInterpreter)();
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f6(b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f6(b));
break;
default:
Assert.Equal(expected, f6(b));
break;
}
}
#endregion
#region Verify short?
private static void VerifyDivideNullableShort(short? a, short? b, bool useInterpreter)
{
bool divideByZero;
short? expected;
if (a.HasValue && b == 0)
{
divideByZero = true;
expected = null;
}
else
{
divideByZero = false;
expected = (short?)(a / b);
}
ParameterExpression p0 = Expression.Parameter(typeof(short?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(short?), "p1");
// verify with parameters supplied
Expression<Func<short?>> e1 =
Expression.Lambda<Func<short?>>(
Expression.Invoke(
Expression.Lambda<Func<short?, short?, short?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(short?))
}),
Enumerable.Empty<ParameterExpression>());
Func<short?> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<short?, short?, Func<short?>>> e2 =
Expression.Lambda<Func<short?, short?, Func<short?>>>(
Expression.Lambda<Func<short?>>(
Expression.Divide(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<short?, short?, Func<short?>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<short?, short?, short?>>> e3 =
Expression.Lambda<Func<Func<short?, short?, short?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<short?, short?, short?>>>(
Expression.Lambda<Func<short?, short?, short?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<short?, short?, short?> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<short?, short?, short?>>> e4 =
Expression.Lambda<Func<Func<short?, short?, short?>>>(
Expression.Lambda<Func<short?, short?, short?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<short?, short?, short?>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<short?, Func<short?, short?>>> e5 =
Expression.Lambda<Func<short?, Func<short?, short?>>>(
Expression.Lambda<Func<short?, short?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<short?, Func<short?, short?>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<short?, short?>>> e6 =
Expression.Lambda<Func<Func<short?, short?>>>(
Expression.Invoke(
Expression.Lambda<Func<short?, Func<short?, short?>>>(
Expression.Lambda<Func<short?, short?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(short?)) }),
Enumerable.Empty<ParameterExpression>());
Func<short?, short?> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#region Verify uint?
private static void VerifyDivideNullableUInt(uint? a, uint? b, bool useInterpreter)
{
bool divideByZero;
uint? expected;
if (a.HasValue && b == 0)
{
divideByZero = true;
expected = null;
}
else
{
divideByZero = false;
expected = a / b;
}
ParameterExpression p0 = Expression.Parameter(typeof(uint?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(uint?), "p1");
// verify with parameters supplied
Expression<Func<uint?>> e1 =
Expression.Lambda<Func<uint?>>(
Expression.Invoke(
Expression.Lambda<Func<uint?, uint?, uint?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(uint?))
}),
Enumerable.Empty<ParameterExpression>());
Func<uint?> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<uint?, uint?, Func<uint?>>> e2 =
Expression.Lambda<Func<uint?, uint?, Func<uint?>>>(
Expression.Lambda<Func<uint?>>(
Expression.Divide(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<uint?, uint?, Func<uint?>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<uint?, uint?, uint?>>> e3 =
Expression.Lambda<Func<Func<uint?, uint?, uint?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<uint?, uint?, uint?>>>(
Expression.Lambda<Func<uint?, uint?, uint?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<uint?, uint?, uint?> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<uint?, uint?, uint?>>> e4 =
Expression.Lambda<Func<Func<uint?, uint?, uint?>>>(
Expression.Lambda<Func<uint?, uint?, uint?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<uint?, uint?, uint?>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<uint?, Func<uint?, uint?>>> e5 =
Expression.Lambda<Func<uint?, Func<uint?, uint?>>>(
Expression.Lambda<Func<uint?, uint?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<uint?, Func<uint?, uint?>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<uint?, uint?>>> e6 =
Expression.Lambda<Func<Func<uint?, uint?>>>(
Expression.Invoke(
Expression.Lambda<Func<uint?, Func<uint?, uint?>>>(
Expression.Lambda<Func<uint?, uint?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(uint?)) }),
Enumerable.Empty<ParameterExpression>());
Func<uint?, uint?> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#region Verify ulong?
private static void VerifyDivideNullableULong(ulong? a, ulong? b, bool useInterpreter)
{
bool divideByZero;
ulong? expected;
if (a.HasValue && b == 0)
{
divideByZero = true;
expected = null;
}
else
{
divideByZero = false;
expected = a / b;
}
ParameterExpression p0 = Expression.Parameter(typeof(ulong?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(ulong?), "p1");
// verify with parameters supplied
Expression<Func<ulong?>> e1 =
Expression.Lambda<Func<ulong?>>(
Expression.Invoke(
Expression.Lambda<Func<ulong?, ulong?, ulong?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(ulong?))
}),
Enumerable.Empty<ParameterExpression>());
Func<ulong?> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<ulong?, ulong?, Func<ulong?>>> e2 =
Expression.Lambda<Func<ulong?, ulong?, Func<ulong?>>>(
Expression.Lambda<Func<ulong?>>(
Expression.Divide(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<ulong?, ulong?, Func<ulong?>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<ulong?, ulong?, ulong?>>> e3 =
Expression.Lambda<Func<Func<ulong?, ulong?, ulong?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<ulong?, ulong?, ulong?>>>(
Expression.Lambda<Func<ulong?, ulong?, ulong?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<ulong?, ulong?, ulong?> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<ulong?, ulong?, ulong?>>> e4 =
Expression.Lambda<Func<Func<ulong?, ulong?, ulong?>>>(
Expression.Lambda<Func<ulong?, ulong?, ulong?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<ulong?, ulong?, ulong?>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<ulong?, Func<ulong?, ulong?>>> e5 =
Expression.Lambda<Func<ulong?, Func<ulong?, ulong?>>>(
Expression.Lambda<Func<ulong?, ulong?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<ulong?, Func<ulong?, ulong?>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<ulong?, ulong?>>> e6 =
Expression.Lambda<Func<Func<ulong?, ulong?>>>(
Expression.Invoke(
Expression.Lambda<Func<ulong?, Func<ulong?, ulong?>>>(
Expression.Lambda<Func<ulong?, ulong?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(ulong?)) }),
Enumerable.Empty<ParameterExpression>());
Func<ulong?, ulong?> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#region Verify ushort?
private static void VerifyDivideNullableUShort(ushort? a, ushort? b, bool useInterpreter)
{
bool divideByZero;
ushort? expected;
if (a.HasValue && b == 0)
{
divideByZero = true;
expected = null;
}
else
{
divideByZero = false;
expected = (ushort?)(a / b);
}
ParameterExpression p0 = Expression.Parameter(typeof(ushort?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(ushort?), "p1");
// verify with parameters supplied
Expression<Func<ushort?>> e1 =
Expression.Lambda<Func<ushort?>>(
Expression.Invoke(
Expression.Lambda<Func<ushort?, ushort?, ushort?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(ushort?))
}),
Enumerable.Empty<ParameterExpression>());
Func<ushort?> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<ushort?, ushort?, Func<ushort?>>> e2 =
Expression.Lambda<Func<ushort?, ushort?, Func<ushort?>>>(
Expression.Lambda<Func<ushort?>>(
Expression.Divide(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<ushort?, ushort?, Func<ushort?>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<ushort?, ushort?, ushort?>>> e3 =
Expression.Lambda<Func<Func<ushort?, ushort?, ushort?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<ushort?, ushort?, ushort?>>>(
Expression.Lambda<Func<ushort?, ushort?, ushort?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<ushort?, ushort?, ushort?> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<ushort?, ushort?, ushort?>>> e4 =
Expression.Lambda<Func<Func<ushort?, ushort?, ushort?>>>(
Expression.Lambda<Func<ushort?, ushort?, ushort?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<ushort?, ushort?, ushort?>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<ushort?, Func<ushort?, ushort?>>> e5 =
Expression.Lambda<Func<ushort?, Func<ushort?, ushort?>>>(
Expression.Lambda<Func<ushort?, ushort?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<ushort?, Func<ushort?, ushort?>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<ushort?, ushort?>>> e6 =
Expression.Lambda<Func<Func<ushort?, ushort?>>>(
Expression.Invoke(
Expression.Lambda<Func<ushort?, Func<ushort?, ushort?>>>(
Expression.Lambda<Func<ushort?, ushort?>>(
Expression.Divide(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(ushort?)) }),
Enumerable.Empty<ParameterExpression>());
Func<ushort?, ushort?> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#endregion
}
}
| |
using System;
using NServiceKit.DesignPatterns.Model;
namespace NServiceKit.OrmLite.TestsPerf.Model
{
/// <summary>A sample order line.</summary>
public class SampleOrderLine
: IHasStringId
{
/// <summary>Gets or sets the identifier.</summary>
/// <value>The identifier.</value>
public string Id { get; set; }
/// <summary>Gets the order URN.</summary>
/// <value>The order URN.</value>
public string OrderUrn
{
get
{
return CreateUrn(this.UserId, this.OrderId, this.OrderLineId);
}
}
/// <summary>Gets or sets the identifier of the order.</summary>
/// <value>The identifier of the order.</value>
public long OrderId { get; set; }
/// <summary>Gets or sets the identifier of the order line.</summary>
/// <value>The identifier of the order line.</value>
public long OrderLineId { get; set; }
/// <summary>Gets or sets the created date.</summary>
/// <value>The created date.</value>
public DateTime CreatedDate { get; set; }
/// <summary>Gets or sets the identifier of the user.</summary>
/// <value>The identifier of the user.</value>
public Guid UserId { get; set; }
/// <summary>Gets or sets the name of the user.</summary>
/// <value>The name of the user.</value>
public string UserName { get; set; }
/// <summary>Gets or sets the identifier of the product.</summary>
/// <value>The identifier of the product.</value>
public Guid ProductId { get; set; }
/// <summary>Gets or sets the mflow URN.</summary>
/// <value>The mflow URN.</value>
public string MflowUrn { get; set; }
/// <summary>Gets or sets the type of the product.</summary>
/// <value>The type of the product.</value>
public string ProductType { get; set; }
/// <summary>Gets or sets the description.</summary>
/// <value>The description.</value>
public string Description { get; set; }
/// <summary>Gets or sets the upc ean.</summary>
/// <value>The upc ean.</value>
public string UpcEan { get; set; }
/// <summary>Gets or sets the isrc.</summary>
/// <value>The isrc.</value>
public string Isrc { get; set; }
/// <summary>Gets or sets the identifier of the recommendation user.</summary>
/// <value>The identifier of the recommendation user.</value>
public Guid? RecommendationUserId { get; set; }
/// <summary>Gets or sets the name of the recommendation user.</summary>
/// <value>The name of the recommendation user.</value>
public string RecommendationUserName { get; set; }
/// <summary>Gets or sets the name of the supplier key.</summary>
/// <value>The name of the supplier key.</value>
public string SupplierKeyName { get; set; }
/// <summary>Gets or sets the name of the cost tier key.</summary>
/// <value>The name of the cost tier key.</value>
public string CostTierKeyName { get; set; }
/// <summary>Gets or sets the name of the price tier key.</summary>
/// <value>The name of the price tier key.</value>
public string PriceTierKeyName { get; set; }
/// <summary>Gets or sets the vat rate.</summary>
/// <value>The vat rate.</value>
public decimal VatRate { get; set; }
/// <summary>Gets or sets the product price increment vat.</summary>
/// <value>The product price increment vat.</value>
public int ProductPriceIncVat { get; set; }
/// <summary>Gets or sets the quantity.</summary>
/// <value>The quantity.</value>
public int Quantity { get; set; }
/// <summary>Gets or sets the transaction value ex vat.</summary>
/// <value>The transaction value ex vat.</value>
public decimal TransactionValueExVat { get; set; }
/// <summary>Gets or sets the transaction value increment vat.</summary>
/// <value>The transaction value increment vat.</value>
public decimal TransactionValueIncVat { get; set; }
/// <summary>Gets or sets the recommendation discount rate.</summary>
/// <value>The recommendation discount rate.</value>
public decimal RecommendationDiscountRate { get; set; }
/// <summary>Gets or sets the distribution discount rate.</summary>
/// <value>The distribution discount rate.</value>
public decimal DistributionDiscountRate { get; set; }
/// <summary>Gets or sets the recommendation discount accrued ex vat.</summary>
/// <value>The recommendation discount accrued ex vat.</value>
public decimal RecommendationDiscountAccruedExVat { get; set; }
/// <summary>Gets or sets the distribution discount accrued ex vat.</summary>
/// <value>The distribution discount accrued ex vat.</value>
public decimal DistributionDiscountAccruedExVat { get; set; }
/// <summary>Gets or sets the promo mix.</summary>
/// <value>The promo mix.</value>
public decimal PromoMix { get; set; }
/// <summary>Gets or sets the discount mix.</summary>
/// <value>The discount mix.</value>
public decimal DiscountMix { get; set; }
/// <summary>Gets or sets the cash mix.</summary>
/// <value>The cash mix.</value>
public decimal CashMix { get; set; }
/// <summary>Gets or sets the promo mix value ex vat.</summary>
/// <value>The promo mix value ex vat.</value>
public decimal PromoMixValueExVat { get; set; }
/// <summary>Gets or sets the discount mix value ex vat.</summary>
/// <value>The discount mix value ex vat.</value>
public decimal DiscountMixValueExVat { get; set; }
/// <summary>Gets or sets the cash mix value increment vat.</summary>
/// <value>The cash mix value increment vat.</value>
public decimal CashMixValueIncVat { get; set; }
/// <summary>Gets or sets the content URN.</summary>
/// <value>The content URN.</value>
public string ContentUrn
{
get { return this.MflowUrn; }
set { this.MflowUrn = value; }
}
/// <summary>Gets or sets the track URN.</summary>
/// <value>The track URN.</value>
public string TrackUrn
{
get;
set;
}
/// <summary>Gets or sets the title.</summary>
/// <value>The title.</value>
public string Title
{
get;
set;
}
/// <summary>Gets or sets the artist URN.</summary>
/// <value>The artist URN.</value>
public string ArtistUrn
{
get;
set;
}
/// <summary>Gets or sets the name of the artist.</summary>
/// <value>The name of the artist.</value>
public string ArtistName
{
get;
set;
}
/// <summary>Gets or sets the album URN.</summary>
/// <value>The album URN.</value>
public string AlbumUrn
{
get;
set;
}
/// <summary>Gets or sets the name of the album.</summary>
/// <value>The name of the album.</value>
public string AlbumName
{
get;
set;
}
/// <summary>Creates an URN.</summary>
/// <param name="userId"> Identifier for the user.</param>
/// <param name="orderId"> Identifier for the order.</param>
/// <param name="orderLineId">Identifier for the order line.</param>
/// <returns>The new URN.</returns>
public static string CreateUrn(Guid userId, long orderId, long orderLineId)
{
return string.Format("urn:orderline:{0}/{1}/{2}",
userId.ToString("N"), orderId, orderLineId);
}
/// <summary>Creates a new SampleOrderLine.</summary>
/// <param name="userId">Identifier for the user.</param>
/// <returns>A SampleOrderLine.</returns>
public static SampleOrderLine Create(Guid userId)
{
return Create(userId, 1, 1);
}
/// <summary>Creates a new SampleOrderLine.</summary>
/// <param name="userId"> Identifier for the user.</param>
/// <param name="orderId"> Identifier for the order.</param>
/// <param name="orderLineId">Identifier for the order line.</param>
/// <returns>A SampleOrderLine.</returns>
public static SampleOrderLine Create(Guid userId, int orderId, int orderLineId)
{
return new SampleOrderLine {
Id = CreateUrn(userId, orderId, orderLineId),
OrderId = orderId,
OrderLineId = orderLineId,
AlbumName = "AlbumName",
CashMixValueIncVat = 0.79m / 1.15m,
TransactionValueExVat = 0.79m,
ContentUrn = "urn:content:" + Guid.NewGuid().ToString("N"),
};
}
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using NUnit.Framework;
namespace Grpc.Core.Internal.Tests
{
/// <summary>
/// Uses fake native call to test interaction of <c>AsyncCall</c> wrapping code with C core in different situations.
/// </summary>
public class AsyncCallTest
{
Channel channel;
FakeNativeCall fakeCall;
AsyncCall<string, string> asyncCall;
[SetUp]
public void Init()
{
channel = new Channel("localhost", ChannelCredentials.Insecure);
fakeCall = new FakeNativeCall();
var callDetails = new CallInvocationDetails<string, string>(channel, "someMethod", null, Marshallers.StringMarshaller, Marshallers.StringMarshaller, new CallOptions());
asyncCall = new AsyncCall<string, string>(callDetails, fakeCall);
}
[TearDown]
public void Cleanup()
{
channel.ShutdownAsync().Wait();
}
[Test]
public void AsyncUnary_CanBeStartedOnlyOnce()
{
asyncCall.UnaryCallAsync("request1");
Assert.Throws(typeof(InvalidOperationException),
() => asyncCall.UnaryCallAsync("abc"));
}
[Test]
public void AsyncUnary_StreamingOperationsNotAllowed()
{
asyncCall.UnaryCallAsync("request1");
Assert.ThrowsAsync(typeof(InvalidOperationException),
async () => await asyncCall.ReadMessageAsync());
Assert.Throws(typeof(InvalidOperationException),
() => asyncCall.StartSendMessage("abc", new WriteFlags(), (x,y) => {}));
}
[Test]
public void AsyncUnary_Success()
{
var resultTask = asyncCall.UnaryCallAsync("request1");
fakeCall.UnaryResponseClientHandler(true,
new ClientSideStatus(Status.DefaultSuccess, new Metadata()),
CreateResponsePayload(),
new Metadata());
AssertUnaryResponseSuccess(asyncCall, fakeCall, resultTask);
}
[Test]
public void AsyncUnary_NonSuccessStatusCode()
{
var resultTask = asyncCall.UnaryCallAsync("request1");
fakeCall.UnaryResponseClientHandler(true,
CreateClientSideStatus(StatusCode.InvalidArgument),
CreateResponsePayload(),
new Metadata());
AssertUnaryResponseError(asyncCall, fakeCall, resultTask, StatusCode.InvalidArgument);
}
[Test]
public void AsyncUnary_NullResponsePayload()
{
var resultTask = asyncCall.UnaryCallAsync("request1");
fakeCall.UnaryResponseClientHandler(true,
new ClientSideStatus(Status.DefaultSuccess, new Metadata()),
null,
new Metadata());
// failure to deserialize will result in InvalidArgument status.
AssertUnaryResponseError(asyncCall, fakeCall, resultTask, StatusCode.Internal);
}
[Test]
public void ClientStreaming_StreamingReadNotAllowed()
{
asyncCall.ClientStreamingCallAsync();
Assert.ThrowsAsync(typeof(InvalidOperationException),
async () => await asyncCall.ReadMessageAsync());
}
[Test]
public void ClientStreaming_NoRequest_Success()
{
var resultTask = asyncCall.ClientStreamingCallAsync();
fakeCall.UnaryResponseClientHandler(true,
new ClientSideStatus(Status.DefaultSuccess, new Metadata()),
CreateResponsePayload(),
new Metadata());
AssertUnaryResponseSuccess(asyncCall, fakeCall, resultTask);
}
[Test]
public void ClientStreaming_NoRequest_NonSuccessStatusCode()
{
var resultTask = asyncCall.ClientStreamingCallAsync();
fakeCall.UnaryResponseClientHandler(true,
CreateClientSideStatus(StatusCode.InvalidArgument),
CreateResponsePayload(),
new Metadata());
AssertUnaryResponseError(asyncCall, fakeCall, resultTask, StatusCode.InvalidArgument);
}
[Test]
public void ClientStreaming_MoreRequests_Success()
{
var resultTask = asyncCall.ClientStreamingCallAsync();
var requestStream = new ClientRequestStream<string, string>(asyncCall);
var writeTask = requestStream.WriteAsync("request1");
fakeCall.SendCompletionHandler(true);
writeTask.Wait();
var writeTask2 = requestStream.WriteAsync("request2");
fakeCall.SendCompletionHandler(true);
writeTask2.Wait();
var completeTask = requestStream.CompleteAsync();
fakeCall.SendCompletionHandler(true);
completeTask.Wait();
fakeCall.UnaryResponseClientHandler(true,
new ClientSideStatus(Status.DefaultSuccess, new Metadata()),
CreateResponsePayload(),
new Metadata());
AssertUnaryResponseSuccess(asyncCall, fakeCall, resultTask);
}
[Test]
public void ClientStreaming_WriteCompletionFailure()
{
var resultTask = asyncCall.ClientStreamingCallAsync();
var requestStream = new ClientRequestStream<string, string>(asyncCall);
var writeTask = requestStream.WriteAsync("request1");
fakeCall.SendCompletionHandler(false);
// TODO: maybe IOException or waiting for RPCException is more appropriate here.
Assert.ThrowsAsync(typeof(InvalidOperationException), async () => await writeTask);
fakeCall.UnaryResponseClientHandler(true,
CreateClientSideStatus(StatusCode.Internal),
CreateResponsePayload(),
new Metadata());
AssertUnaryResponseError(asyncCall, fakeCall, resultTask, StatusCode.Internal);
}
[Test]
public void ClientStreaming_WriteAfterReceivingStatusThrowsRpcException()
{
var resultTask = asyncCall.ClientStreamingCallAsync();
var requestStream = new ClientRequestStream<string, string>(asyncCall);
fakeCall.UnaryResponseClientHandler(true,
new ClientSideStatus(Status.DefaultSuccess, new Metadata()),
CreateResponsePayload(),
new Metadata());
AssertUnaryResponseSuccess(asyncCall, fakeCall, resultTask);
var ex = Assert.Throws<RpcException>(() => requestStream.WriteAsync("request1"));
Assert.AreEqual(Status.DefaultSuccess, ex.Status);
}
[Test]
public void ClientStreaming_WriteAfterReceivingStatusThrowsRpcException2()
{
var resultTask = asyncCall.ClientStreamingCallAsync();
var requestStream = new ClientRequestStream<string, string>(asyncCall);
fakeCall.UnaryResponseClientHandler(true,
new ClientSideStatus(new Status(StatusCode.OutOfRange, ""), new Metadata()),
CreateResponsePayload(),
new Metadata());
AssertUnaryResponseError(asyncCall, fakeCall, resultTask, StatusCode.OutOfRange);
var ex = Assert.Throws<RpcException>(() => requestStream.WriteAsync("request1"));
Assert.AreEqual(StatusCode.OutOfRange, ex.Status.StatusCode);
}
[Test]
public void ClientStreaming_WriteAfterCompleteThrowsInvalidOperationException()
{
var resultTask = asyncCall.ClientStreamingCallAsync();
var requestStream = new ClientRequestStream<string, string>(asyncCall);
requestStream.CompleteAsync();
Assert.Throws(typeof(InvalidOperationException), () => requestStream.WriteAsync("request1"));
fakeCall.SendCompletionHandler(true);
fakeCall.UnaryResponseClientHandler(true,
new ClientSideStatus(Status.DefaultSuccess, new Metadata()),
CreateResponsePayload(),
new Metadata());
AssertUnaryResponseSuccess(asyncCall, fakeCall, resultTask);
}
[Test]
public void ClientStreaming_CompleteAfterReceivingStatusSucceeds()
{
var resultTask = asyncCall.ClientStreamingCallAsync();
var requestStream = new ClientRequestStream<string, string>(asyncCall);
fakeCall.UnaryResponseClientHandler(true,
new ClientSideStatus(Status.DefaultSuccess, new Metadata()),
CreateResponsePayload(),
new Metadata());
AssertUnaryResponseSuccess(asyncCall, fakeCall, resultTask);
Assert.DoesNotThrowAsync(async () => await requestStream.CompleteAsync());
}
[Test]
public void ClientStreaming_WriteAfterCancellationRequestThrowsOperationCancelledException()
{
var resultTask = asyncCall.ClientStreamingCallAsync();
var requestStream = new ClientRequestStream<string, string>(asyncCall);
asyncCall.Cancel();
Assert.IsTrue(fakeCall.IsCancelled);
Assert.Throws(typeof(OperationCanceledException), () => requestStream.WriteAsync("request1"));
fakeCall.UnaryResponseClientHandler(true,
CreateClientSideStatus(StatusCode.Cancelled),
CreateResponsePayload(),
new Metadata());
AssertUnaryResponseError(asyncCall, fakeCall, resultTask, StatusCode.Cancelled);
}
[Test]
public void ServerStreaming_StreamingSendNotAllowed()
{
asyncCall.StartServerStreamingCall("request1");
Assert.Throws(typeof(InvalidOperationException),
() => asyncCall.StartSendMessage("abc", new WriteFlags(), (x,y) => {}));
}
[Test]
public void ServerStreaming_NoResponse_Success1()
{
asyncCall.StartServerStreamingCall("request1");
var responseStream = new ClientResponseStream<string, string>(asyncCall);
var readTask = responseStream.MoveNext();
fakeCall.ReceivedResponseHeadersHandler(true, new Metadata());
Assert.AreEqual(0, asyncCall.ResponseHeadersAsync.Result.Count);
fakeCall.ReceivedMessageHandler(true, null);
fakeCall.ReceivedStatusOnClientHandler(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata()));
AssertStreamingResponseSuccess(asyncCall, fakeCall, readTask);
}
[Test]
public void ServerStreaming_NoResponse_Success2()
{
asyncCall.StartServerStreamingCall("request1");
var responseStream = new ClientResponseStream<string, string>(asyncCall);
var readTask = responseStream.MoveNext();
// try alternative order of completions
fakeCall.ReceivedStatusOnClientHandler(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata()));
fakeCall.ReceivedMessageHandler(true, null);
AssertStreamingResponseSuccess(asyncCall, fakeCall, readTask);
}
[Test]
public void ServerStreaming_NoResponse_ReadFailure()
{
asyncCall.StartServerStreamingCall("request1");
var responseStream = new ClientResponseStream<string, string>(asyncCall);
var readTask = responseStream.MoveNext();
fakeCall.ReceivedMessageHandler(false, null); // after a failed read, we rely on C core to deliver appropriate status code.
fakeCall.ReceivedStatusOnClientHandler(true, CreateClientSideStatus(StatusCode.Internal));
AssertStreamingResponseError(asyncCall, fakeCall, readTask, StatusCode.Internal);
}
[Test]
public void ServerStreaming_MoreResponses_Success()
{
asyncCall.StartServerStreamingCall("request1");
var responseStream = new ClientResponseStream<string, string>(asyncCall);
var readTask1 = responseStream.MoveNext();
fakeCall.ReceivedMessageHandler(true, CreateResponsePayload());
Assert.IsTrue(readTask1.Result);
Assert.AreEqual("response1", responseStream.Current);
var readTask2 = responseStream.MoveNext();
fakeCall.ReceivedMessageHandler(true, CreateResponsePayload());
Assert.IsTrue(readTask2.Result);
Assert.AreEqual("response1", responseStream.Current);
var readTask3 = responseStream.MoveNext();
fakeCall.ReceivedStatusOnClientHandler(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata()));
fakeCall.ReceivedMessageHandler(true, null);
AssertStreamingResponseSuccess(asyncCall, fakeCall, readTask3);
}
[Test]
public void DuplexStreaming_NoRequestNoResponse_Success()
{
asyncCall.StartDuplexStreamingCall();
var requestStream = new ClientRequestStream<string, string>(asyncCall);
var responseStream = new ClientResponseStream<string, string>(asyncCall);
var writeTask1 = requestStream.CompleteAsync();
fakeCall.SendCompletionHandler(true);
Assert.DoesNotThrowAsync(async () => await writeTask1);
var readTask = responseStream.MoveNext();
fakeCall.ReceivedMessageHandler(true, null);
fakeCall.ReceivedStatusOnClientHandler(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata()));
AssertStreamingResponseSuccess(asyncCall, fakeCall, readTask);
}
[Test]
public void DuplexStreaming_WriteAfterReceivingStatusThrowsRpcException()
{
asyncCall.StartDuplexStreamingCall();
var requestStream = new ClientRequestStream<string, string>(asyncCall);
var responseStream = new ClientResponseStream<string, string>(asyncCall);
var readTask = responseStream.MoveNext();
fakeCall.ReceivedMessageHandler(true, null);
fakeCall.ReceivedStatusOnClientHandler(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata()));
AssertStreamingResponseSuccess(asyncCall, fakeCall, readTask);
var ex = Assert.ThrowsAsync<RpcException>(async () => await requestStream.WriteAsync("request1"));
Assert.AreEqual(Status.DefaultSuccess, ex.Status);
}
[Test]
public void DuplexStreaming_CompleteAfterReceivingStatusFails()
{
asyncCall.StartDuplexStreamingCall();
var requestStream = new ClientRequestStream<string, string>(asyncCall);
var responseStream = new ClientResponseStream<string, string>(asyncCall);
var readTask = responseStream.MoveNext();
fakeCall.ReceivedMessageHandler(true, null);
fakeCall.ReceivedStatusOnClientHandler(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata()));
AssertStreamingResponseSuccess(asyncCall, fakeCall, readTask);
Assert.DoesNotThrowAsync(async () => await requestStream.CompleteAsync());
}
[Test]
public void DuplexStreaming_WriteAfterCancellationRequestThrowsOperationCancelledException()
{
asyncCall.StartDuplexStreamingCall();
var requestStream = new ClientRequestStream<string, string>(asyncCall);
var responseStream = new ClientResponseStream<string, string>(asyncCall);
asyncCall.Cancel();
Assert.IsTrue(fakeCall.IsCancelled);
Assert.Throws(typeof(OperationCanceledException), () => requestStream.WriteAsync("request1"));
var readTask = responseStream.MoveNext();
fakeCall.ReceivedMessageHandler(true, null);
fakeCall.ReceivedStatusOnClientHandler(true, CreateClientSideStatus(StatusCode.Cancelled));
AssertStreamingResponseError(asyncCall, fakeCall, readTask, StatusCode.Cancelled);
}
[Test]
public void DuplexStreaming_ReadAfterCancellationRequestCanSucceed()
{
asyncCall.StartDuplexStreamingCall();
var responseStream = new ClientResponseStream<string, string>(asyncCall);
asyncCall.Cancel();
Assert.IsTrue(fakeCall.IsCancelled);
var readTask1 = responseStream.MoveNext();
fakeCall.ReceivedMessageHandler(true, CreateResponsePayload());
Assert.IsTrue(readTask1.Result);
Assert.AreEqual("response1", responseStream.Current);
var readTask2 = responseStream.MoveNext();
fakeCall.ReceivedMessageHandler(true, null);
fakeCall.ReceivedStatusOnClientHandler(true, CreateClientSideStatus(StatusCode.Cancelled));
AssertStreamingResponseError(asyncCall, fakeCall, readTask2, StatusCode.Cancelled);
}
[Test]
public void DuplexStreaming_ReadStartedBeforeCancellationRequestCanSucceed()
{
asyncCall.StartDuplexStreamingCall();
var responseStream = new ClientResponseStream<string, string>(asyncCall);
var readTask1 = responseStream.MoveNext(); // initiate the read before cancel request
asyncCall.Cancel();
Assert.IsTrue(fakeCall.IsCancelled);
fakeCall.ReceivedMessageHandler(true, CreateResponsePayload());
Assert.IsTrue(readTask1.Result);
Assert.AreEqual("response1", responseStream.Current);
var readTask2 = responseStream.MoveNext();
fakeCall.ReceivedMessageHandler(true, null);
fakeCall.ReceivedStatusOnClientHandler(true, CreateClientSideStatus(StatusCode.Cancelled));
AssertStreamingResponseError(asyncCall, fakeCall, readTask2, StatusCode.Cancelled);
}
ClientSideStatus CreateClientSideStatus(StatusCode statusCode)
{
return new ClientSideStatus(new Status(statusCode, ""), new Metadata());
}
byte[] CreateResponsePayload()
{
return Marshallers.StringMarshaller.Serializer("response1");
}
static void AssertUnaryResponseSuccess(AsyncCall<string, string> asyncCall, FakeNativeCall fakeCall, Task<string> resultTask)
{
Assert.IsTrue(resultTask.IsCompleted);
Assert.IsTrue(fakeCall.IsDisposed);
Assert.AreEqual(Status.DefaultSuccess, asyncCall.GetStatus());
Assert.AreEqual(0, asyncCall.ResponseHeadersAsync.Result.Count);
Assert.AreEqual(0, asyncCall.GetTrailers().Count);
Assert.AreEqual("response1", resultTask.Result);
}
static void AssertStreamingResponseSuccess(AsyncCall<string, string> asyncCall, FakeNativeCall fakeCall, Task<bool> moveNextTask)
{
Assert.IsTrue(moveNextTask.IsCompleted);
Assert.IsTrue(fakeCall.IsDisposed);
Assert.IsFalse(moveNextTask.Result);
Assert.AreEqual(Status.DefaultSuccess, asyncCall.GetStatus());
Assert.AreEqual(0, asyncCall.GetTrailers().Count);
}
static void AssertUnaryResponseError(AsyncCall<string, string> asyncCall, FakeNativeCall fakeCall, Task<string> resultTask, StatusCode expectedStatusCode)
{
Assert.IsTrue(resultTask.IsCompleted);
Assert.IsTrue(fakeCall.IsDisposed);
Assert.AreEqual(expectedStatusCode, asyncCall.GetStatus().StatusCode);
var ex = Assert.ThrowsAsync<RpcException>(async () => await resultTask);
Assert.AreEqual(expectedStatusCode, ex.Status.StatusCode);
Assert.AreEqual(0, asyncCall.ResponseHeadersAsync.Result.Count);
Assert.AreEqual(0, asyncCall.GetTrailers().Count);
}
static void AssertStreamingResponseError(AsyncCall<string, string> asyncCall, FakeNativeCall fakeCall, Task<bool> moveNextTask, StatusCode expectedStatusCode)
{
Assert.IsTrue(moveNextTask.IsCompleted);
Assert.IsTrue(fakeCall.IsDisposed);
var ex = Assert.ThrowsAsync<RpcException>(async () => await moveNextTask);
Assert.AreEqual(expectedStatusCode, ex.Status.StatusCode);
Assert.AreEqual(expectedStatusCode, asyncCall.GetStatus().StatusCode);
Assert.AreEqual(0, asyncCall.GetTrailers().Count);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace ODataValidator.Rule.Helper
{
#region Namespaces
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Xml.Linq;
using System.Xml.XPath;
using Newtonsoft.Json.Linq;
using ODataValidator.RuleEngine;
using ODataValidator.RuleEngine.Common;
#endregion
/// <summary>
/// Utility class of JSON response parser.
/// </summary>
public static class JsonParserHelper
{
/// <summary>
/// Gets JSON response object from service context object.
/// </summary>
/// <param name="context">The service context</param>
/// <returns>JObject of the response in JSON format; null otherwise</returns>
public static JObject GetResponseObject(ServiceContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
return JsonParserHelper.GetResponseObject(context.ResponsePayload);
}
/// <summary>
/// Gets JSON object of response payload.
/// </summary>
/// <param name="payload">The payload literal</param>
/// <returns>JObject of the response in JSON format; null otherwise</returns>
public static JObject GetResponseObject(string payload)
{
JObject result = null;
if (payload.TryToJObject(out result))
{
// do nothing; already get it in result object
}
return result;
}
/// <summary>
/// Gets array of JSON object representing collection of entities.
/// </summary>
/// <param name="feed">The JSON objet of response payload for feed type</param>
/// <returns>JArray object representing the feed; null if it is not feed in JSON</returns>
public static JArray GetEntries(JObject feed)
{
JArray result = null;
if (feed == null)
{
return null;
}
else if (feed.Count == 1)
{
var d = (JProperty)feed.First;
if (d.Name.Equals(Constants.BeginMarkD, StringComparison.Ordinal))
{
var sub = d.Value;
if (sub.Type == JTokenType.Array)
{
// V1 JSON format
result = (JArray)sub;
}
else if (sub.Type == JTokenType.Object)
{
// V2 format: looking for name-value pair of "result:{...}"
JObject resultObject = (JObject)sub;
var resultValues = from p in resultObject.Children<JProperty>()
where p.Name.Equals(Constants.Results, StringComparison.Ordinal)
&& p.Value.Type == JTokenType.Array
select (JArray)p.Value;
if (resultValues.Any())
{
result = resultValues.First();
}
}
}
}
else
{
foreach (var r in feed.Children<JProperty>())
{
if (r.Name.Equals(Constants.Value, StringComparison.Ordinal)
&& r.Value.Type == JTokenType.Array)
{
result = (JArray)r.Value;
break;
}
}
}
return result;
}
/// <summary>
/// Gets all entities from the service's response payload.
/// </summary>
/// <param name="responsePayload">The specified response payload.</param>
/// <returns>Returns the entities' list.</returns>
public static List<JObject> GetEntities(string responsePayload)
{
var entities = new List<JObject>();
if (string.IsNullOrEmpty(responsePayload))
{
return entities;
}
JObject jObj = JObject.Parse(responsePayload);
JArray jArr = jObj.GetValue("value") as JArray;
if (null != jArr)
{
if (jArr.Any())
{
foreach (JObject entity in jArr)
{
entities.Add(entity);
}
}
else
{
return entities;
}
}
else
{
entities.Add(jObj);
}
return entities;
}
/// <summary>
/// Gets the last entry from the collection of entries.
/// </summary>
/// <param name="entries">The collection of entries</param>
/// <returns>JOBject of the last entity </returns>
public static JObject GetLastEntry(JArray entries)
{
JObject lastEntry = null;
if (entries != null && entries.Count > 0)
{
JToken lastItem = entries.Last(o => o.Type == JTokenType.Object);
lastEntry = (JObject)lastItem;
}
return lastEntry;
}
/// <summary>
/// Gets the opaque token value of the entity.
/// </summary>
/// <param name="entry">The entity</param>
/// <returns>The token value if one is found; null otherwise</returns>
public static string GetTokenOfEntry(JObject entry)
{
string token = null;
string selfTag = JsonHelper.GetPropertyOfElement(entry, Constants.JsonVerboseMetadataPropertyName, Constants.JsonVerboseUriPropertyName);
if (!string.IsNullOrEmpty(selfTag))
{
int length = selfTag.Length;
if (selfTag[length - 1] == ')')
{
int posLastSeg = selfTag.LastIndexOf('/');
int openParenthesis = posLastSeg >= 0 ? selfTag.IndexOf('(', posLastSeg) : selfTag.LastIndexOf('(');
token = selfTag.Substring(openParenthesis + 1, length - openParenthesis - 2);
}
}
return token;
}
/// <summary>
/// Validates a Json schema against a payload string
/// </summary>
/// <param name="jschema">The JSon schema</param>
/// <param name="payload">The payload string</param>
/// <param name="testResult">output parameter of detailed test result</param>
/// <returns>Returns true when the payload is validated; otherwise false</returns>
public static bool ValidateJson(string jschema, string payload, out RuleEngine.TestResult testResult)
{
JsonSchemaVerifier verifer = new JsonSchemaVerifier(jschema);
return verifer.Verify(payload, out testResult);
}
/// <summary>
/// Gets the OData version implication from Json payload object
/// </summary>
/// <param name="jo">The Json payload input</param>
/// <returns>The OData version implication based on the Json object wrapping</returns>
public static ODataVersion GetPayloadODataVersion(JObject jo)
{
ODataVersion result = ODataVersion.UNKNOWN;
var d = from p in jo.Properties()
where p.Name.Equals(Constants.BeginMarkD, StringComparison.Ordinal)
select p;
if (d.Any())
{
result = ODataVersion.V1;
var dToken = d.First().Value;
if (dToken.Type == JTokenType.Object)
{
var dObject = (JObject)dToken;
var r = from p in dObject.Properties()
where p.Name.Equals(Constants.Result, StringComparison.Ordinal)
select p;
if (r.Any())
{
result = ODataVersion.V2;
}
}
}
return result;
}
/// <summary>
/// Whether specified Annoatation exist.
/// </summary>
/// <param name="context">Service context</param>
/// <param name="specifiedAnnoatation">The specified Annoatation</param>
/// <returns>true if exist; false otherwise</returns>
public static bool IsSpecifiedAnnotationExist(ServiceContext context, string specifiedAnnoatation)
{
JObject allobject;
context.ResponsePayload.TryToJObject(out allobject);
bool isExist = false;
// If PayloadType is Feed, verify as below.
if (context.PayloadType.Equals(RuleEngine.PayloadType.Feed))
{
var entries = JsonParserHelper.GetEntries(allobject);
foreach (JObject entry in entries)
{
var jProps = entry.Children();
foreach (JProperty jProp in jProps)
{
// Whether specified Annoatation exist in response.
if (jProp.Name.Equals(specifiedAnnoatation))
{
isExist = true;
break;
}
else
{
isExist = false;
}
}
if (isExist)
{
break;
}
}
}
else
{
var jProps = allobject.Children();
foreach (JProperty jProp in jProps)
{
// Whether specified Annoatation exist in response.
if (jProp.Name.Equals(specifiedAnnoatation))
{
isExist = true;
break;
}
else
{
isExist = false;
}
}
}
return isExist;
}
/// <summary>
/// Get all values of specified property from JSON object.
/// </summary>
/// <param name="jo">The JSON object instance.</param>
/// <param name="identity">The identity of property name.</param>
/// <param name="compareType">The compare method of identity.</param>
/// <returns>The string list of got values.</returns>
public static List<string> GetPropValuesFromJSONObject(JObject jo, string identity, StringCompareType compareType)
{
List<string> results = new List<string>();
bool isExist = false;
foreach (var p in jo)
{
isExist = false;
if (p.Value.Type == JTokenType.Object)
{
foreach (string link in GetPropValuesFromJSONObject((JObject)p.Value, identity, compareType))
{
results.Add(link);
}
}
else if (p.Value.Type == JTokenType.Array)
{
foreach (string link in GetPropValuesFromJSONArray((JArray)p.Value, identity, compareType))
{
results.Add(link);
}
}
else
{
switch (compareType)
{
case StringCompareType.Equal:
isExist = p.Key.ToString().Equals(identity);
break;
case StringCompareType.Contain:
isExist = p.Key.ToString().Contains(identity);
break;
default:
break;
}
if (isExist)
{
results.Add(p.Value.ToString().StripOffDoubleQuotes());
}
}
}
return results;
}
/// <summary>
/// Get all values of specified property from JSON array.
/// </summary>
/// <param name="jo">The JSON array instance.</param>
/// <param name="identity">The identity of property name.</param>
/// <param name="compareType">The compare method of identity.</param>
/// <returns>The string list of got values.</returns>
public static List<string> GetPropValuesFromJSONArray(JArray ja, string identity, StringCompareType compareType)
{
List<string> results = new List<string>();
foreach (var p in ja)
{
if (p.Type == JTokenType.Object)
{
foreach (string s in GetPropValuesFromJSONObject((JObject)p, identity, compareType))
{
results.Add(s);
}
}
else if (p.Type == JTokenType.Array)
{
foreach (string s in GetPropValuesFromJSONArray((JArray)p, identity, compareType))
{
results.Add(s);
}
}
}
return results;
}
/// <summary>
/// Gets all the json objects from the current response payload.
/// </summary>
/// <param name="jObj">The response payload.</param>
/// <param name="objects">Stores all the json objects which were got from response payload.</param>
public static void GetJsonObjectsFromRespPayload(JObject jObj, ref List<JToken> objects)
{
if (jObj != null && objects != null)
{
objects.Add(jObj);
var jProps = jObj.Children();
foreach (JProperty jProp in jProps)
{
if (jProp.Value.Type == JTokenType.Object)
{
GetJsonObjectsFromRespPayload((JObject)jProp.Value, ref objects);
}
else if (jProp.Value.Type == JTokenType.Array)
{
var objs = jProp.Value.Children();
foreach (var obj in objs)
{
if (typeof(JObject) == obj.GetType())
{
JObject jo = obj as JObject;
GetJsonObjectsFromRespPayload(jo, ref objects);
}
}
}
}
}
}
/// <summary>
/// Gets all the annotations from the response payload.
/// </summary>
/// <param name="jObj">The response payload.</param>
/// <param name="version">The version of the odata service.</param>
/// <param name="type">The annotation type.</param>
/// <param name="annotations">Stores all the annotation which were got from the response payload.</param>
public static void GetAnnotationsFromResponsePayload(JObject jObj, ODataVersion version, AnnotationType type, ref List<JProperty> annotations)
{
if (jObj != null && annotations != null)
{
var jProps = jObj.Children();
foreach (JProperty jProp in jProps)
{
if (jProp.Value.Type == JTokenType.Object)
{
GetAnnotationsFromResponsePayload((JObject)jProp.Value, version, type, ref annotations);
}
else if (jProp.Value.Type == JTokenType.Array)
{
var objs = jProp.Value.Children();
foreach (var obj in objs)
{
if (typeof(JObject) == obj.GetType())
{
GetAnnotationsFromResponsePayload((JObject)obj, version, type, ref annotations);
}
}
}
else
{
// If the property's name contains dot(.), it will indicate that this property is an annotation.
if (jProp.Name.Contains("."))
{
switch (type)
{
default:
case AnnotationType.All:
annotations.Add(jProp);
break;
case AnnotationType.ArrayOrPrimitive:
if (version == ODataVersion.V4 ? !jProp.Name.StartsWith("@") : jProp.Name.Contains("@"))
{
annotations.Add(jProp);
}
break;
case AnnotationType.Object:
if (version == ODataVersion.V4 ? jProp.Name.StartsWith("@") : !jProp.Name.Contains("@"))
{
annotations.Add(jProp);
}
break;
}
}
}
}
}
}
/// <summary>
/// Get specified property's value from an entry payload.
/// </summary>
/// <param name="entry">An entry.</param>
/// <param name="elementName">An element name which is expected to get.</param>
/// <returns>Returns a list of values.</returns>
public static List<JToken> GetSpecifiedPropertyValsFromEntryPayload(JObject entry, string elementName, MatchType matchType)
{
if (entry == null || elementName == null || elementName == string.Empty || matchType == MatchType.None)
{
return vals;
}
if (entry != null && entry.Type == JTokenType.Object)
{
var jProps = entry.Children();
foreach (JProperty jProp in jProps)
{
if (matchType == MatchType.Equal && jProp.Name == elementName)
{
vals.Add(jProp.Value);
}
else if (matchType == MatchType.Contained && jProp.Name.Contains(elementName))
{
vals.Add(jProp.Value);
}
if (jProp.Value.Type == JTokenType.Object)
{
GetSpecifiedPropertyValsFromEntryPayload(jProp.Value as JObject, elementName, matchType);
}
if (jProp.Value.Type == JTokenType.Array && ((JArray)(jProp.Value)).Count != 0)
{
var collection = jProp.Value.Children();
int childrenNum = collection.Count();
var element = collection.First();
while (--childrenNum >= 0)
{
if (element.Type == JTokenType.Object)
{
GetSpecifiedPropertyValsFromEntryPayload(element as JObject, elementName, matchType);
}
if (childrenNum > 0)
{
element = element.Next;
}
}
}
}
}
return vals;
}
/// <summary>
/// Get specified property's name from an entry payload.
/// </summary>
/// <param name="entry">An entry.</param>
/// <param name="elementName">An element name which is expected to get.</param>
/// <returns>Returns a list of names.</returns>
public static List<string> GetSpecifiedPropertyNamesFromEntryPayload(JObject entry, string elementName, MatchType matchType)
{
if (entry == null || elementName == null || elementName == string.Empty || matchType == MatchType.None)
{
return names;
}
if (entry != null && entry.Type == JTokenType.Object)
{
var jProps = entry.Children();
foreach (JProperty jProp in jProps)
{
if (matchType == MatchType.Equal && jProp.Name == elementName)
{
names.Add(jProp.Name);
}
else if (matchType == MatchType.Contained && jProp.Name.Contains(elementName))
{
names.Add(jProp.Name);
}
if (jProp.Value.Type == JTokenType.Object)
{
GetSpecifiedPropertyValsFromEntryPayload(jProp.Value as JObject, elementName, matchType);
}
if (jProp.Value.Type == JTokenType.Array && ((JArray)(jProp.Value)).Count != 0)
{
var collection = jProp.Value.Children();
int childrenNum = collection.Count();
var element = collection.First();
while (--childrenNum >= 0)
{
if (element.Type == JTokenType.Object)
{
GetSpecifiedPropertyValsFromEntryPayload(element as JObject, elementName, matchType);
}
if (childrenNum > 0)
{
element = element.Next;
}
}
}
}
}
return names;
}
/// <summary>
/// Get specified properties from an entry payload.
/// </summary>
/// <param name="entry">An entry.</param>
/// <param name="elementName">An element name which is expected to get.</param>
/// <returns>Returns a list of properties.</returns>
public static List<JProperty> GetSpecifiedPropertiesFromEntryPayload(JObject entry, string elementName)
{
if (entry == null || elementName == null || elementName == string.Empty)
{
return props;
}
if (entry != null && entry.Type == JTokenType.Object)
{
var jProps = entry.Children();
foreach (JProperty jProp in jProps)
{
if (jProp.Name == elementName)
{
props.Add(jProp);
}
if (jProp.Value.Type == JTokenType.Object)
{
GetSpecifiedPropertiesFromEntryPayload(jProp.Value as JObject, elementName);
}
if (jProp.Value.Type == JTokenType.Array && ((JArray)(jProp.Value)).Count != 0)
{
var collection = jProp.Value.Children();
int childrenNum = collection.Count();
var element = collection.First();
while (--childrenNum >= 0)
{
if (element.Type == JTokenType.Object)
{
GetSpecifiedPropertiesFromEntryPayload(element as JObject, elementName);
}
if (childrenNum > 0)
{
element = element.Next;
}
}
}
}
}
return props;
}
/// <summary>
/// Get specified properties from an feed payload.
/// </summary>
/// <param name="feed">A feed.</param>
/// <param name="elementName">An element name which is expected to get.</param>
/// <returns>Returns a list of properties.</returns>
public static List<JProperty> GetSpecifiedPropertiesFromFeedPayload(JArray feed, string elementName)
{
if (feed == null || elementName == null || elementName == string.Empty)
{
return props;
}
if (feed != null && feed.Type == JTokenType.Array)
{
foreach (JObject entry in feed.Children())
{
props = GetSpecifiedPropertiesFromEntryPayload(entry, elementName);
}
}
return props;
}
/// <summary>
/// Whether the json property is function or action property.
/// </summary>
/// <param name="FucOrActNames">The function or action names from metadata</param>
/// <param name="jProp">The json property</param>
/// <param name="metadataSchema">The metadata Schema XML element.</param>
/// <returns>true if function or action property; false otherwise</returns>
public static bool isFunctionOrActionProperty(List<string> FucOrActNames, JProperty jProp, XElement metadataSchema)
{
bool isImportName = false;
AliasNamespacePair aliasNamespacePair = MetadataHelper.GetAliasAndNamespace(metadataSchema);
foreach (string name in FucOrActNames)
{
if (!string.IsNullOrEmpty(name) &&
(jProp.Name.Equals("#" + aliasNamespacePair.Alias + "." + name)
|| jProp.Name.Equals("#" + aliasNamespacePair.Namespace + "." + name)))
{
isImportName = true;
break;
}
}
return isImportName;
}
/// <summary>
/// Get total count of entities in feed response.
/// </summary>
/// <param name="url">The input url.</param>
/// <param name="feed">The json object of feed response.</param>
/// <param name="version">The version of the service.</param>
/// <param name="RequestHeaders">The request headers.</param>
/// <param name="totalCount">The amount of the entities.</param>
public static void GetEntitiesCountFromFeed(Uri url, JObject feed, IEnumerable<KeyValuePair<string, string>> RequestHeaders, ref int totalCount)
{
int skiptoken = 0;
foreach (var r in feed.Children<JProperty>())
{
if (r.Name.Equals(Constants.Value, StringComparison.Ordinal) && r.Value.Type == JTokenType.Array)
{
totalCount += ((JArray)r.Value).Count;
}
// When entities are more than one page.
if (r.Name.Equals(Constants.V4OdataNextLink, StringComparison.Ordinal))
{
string[] skiptokenValues = r.Value.ToString().StripOffDoubleQuotes().Split(new string[] { "skiptoken=" }, StringSplitOptions.None);
skiptoken = Int32.Parse(skiptokenValues[1]);
string nextLinkUrl = !url.AbsoluteUri.Contains("?$") ? url + @"?$skiptoken=" + skiptoken.ToString() : url + @"&$skiptoken=" + skiptoken.ToString();
Response response = WebHelper.Get(new Uri(nextLinkUrl), Constants.AcceptHeaderJson, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, RequestHeaders);
JObject jo;
response.ResponsePayload.TryToJObject(out jo);
GetEntitiesCountFromFeed(url, jo, RequestHeaders, ref totalCount);
}
}
}
/// <summary>
/// Gets the amount of entities in a navigation property with collection type.
/// </summary>
/// <param name="url">An entry input URL.</param>
/// <param name="entry">The entry JSON response payload.</param>
/// <param name="navigPropName">The name of navigation property with collection type.</param>
/// <param name="requestHeaders">The request header.</param>
/// <param name="totalCount">The actual amount of the entities in a navigation property with collection type.</param>
public static void GetEntitiesNumFromCollectionValuedNavigProp(string url, JObject entry, string navigPropName, IEnumerable<KeyValuePair<string, string>> requestHeaders, ref int totalCount)
{
if (string.IsNullOrEmpty(url) || entry == null || string.IsNullOrEmpty(navigPropName) || requestHeaders == null)
{
return;
}
foreach (var jProp in entry.Children<JProperty>())
{
if (jProp.Name.Equals(navigPropName, StringComparison.Ordinal) && jProp.Value.Type == JTokenType.Array)
{
totalCount += ((JArray)jProp.Value).Count;
}
if (jProp.Name.Equals(navigPropName + Constants.V4OdataNextLink, StringComparison.Ordinal))
{
string[] nextLinkInfo = jProp.Value.ToString().StripOffDoubleQuotes().Split(new string[] { "skiptoken=" }, StringSplitOptions.None);
string nextLinkUrl = string.Format("{0}/{1}?$skiptoken={2}", url, navigPropName, nextLinkInfo[1]);
Response resp = WebHelper.Get(new Uri(nextLinkUrl), Constants.AcceptHeaderJson, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, requestHeaders);
JObject jObj;
resp.ResponsePayload.TryToJObject(out jObj);
GetEntitiesCountFromFeed(new Uri(string.Format("{0}/{1}", url, navigPropName)), jObj, requestHeaders, ref totalCount);
}
}
}
/// <summary>
/// Gets the error message from response payload.
/// </summary>
/// <param name="responsePayload">The content of response payload.</param>
/// <returns>Returns the error message.</returns>
public static string GetErrorMessage(this string responsePayload)
{
if (string.IsNullOrEmpty(responsePayload))
{
return string.Empty;
}
string result = string.Empty;
if (responsePayload.IsXmlPayload())
{
try
{
string xpath = @"./*[local-name()='message']";
XElement errorMsg = XElement.Parse(responsePayload);
result = errorMsg.XPathSelectElement(xpath, ODataNamespaceManager.Instance).Value;
}
catch (FormatException e)
{
throw new FormatException("This XML format of error message is unknown.", e.InnerException);
}
}
else if (responsePayload.IsJsonPayload())
{
var payload = JToken.Parse(responsePayload);
try
{
var errorBody = ((JObject)payload)["error"];
var message = ((JObject)errorBody)["message"];
result = message.ToString();
}
catch (FormatException e)
{
throw new FormatException("This JSON format of error message is unknown.", e.InnerException);
}
}
else
{
throw new FormatException("The response payload is unknown.");
}
return result;
}
/// <summary>
/// Get specified count of entities from first feed of service document.
/// </summary>
/// <param name="context">The service document context.</param>
/// <returns>Returns an entity URLs's list.</returns>
public static bool GetBatchSupportedEntityUrls(out KeyValuePair<string, IEnumerable<string>> entityUrls)
{
entityUrls = new KeyValuePair<string, IEnumerable<string>>();
var svcStatus = ServiceStatus.GetInstance();
List<string> vocDocs = new List<string>() { TermDocuments.GetInstance().VocCapabilitiesDoc };
var payloadFormat = svcStatus.ServiceDocument.GetFormatFromPayload();
var batchSupportedEntitySetUrls = new List<string>();
var batchSupportedEntitySetNames = AnnotationsHelper.SelectEntitySetSupportBatch(svcStatus.MetadataDocument, vocDocs);
batchSupportedEntitySetNames.ForEach(temp => { batchSupportedEntitySetUrls.Add(temp.MapEntitySetNameToEntitySetURL()); });
var entitySetUrls = ContextHelper.GetFeeds(svcStatus.ServiceDocument, payloadFormat).ToArray();
if (entitySetUrls.Any())
{
string entitySetUrl = string.Empty;
foreach (var setUrl in entitySetUrls)
{
string entityTypeShortName = setUrl.MapEntitySetURLToEntityTypeShortName();
if (batchSupportedEntitySetUrls.Contains(setUrl) && !entityTypeShortName.IsMediaType())
{
entitySetUrl = setUrl;
break;
}
}
if (string.IsNullOrEmpty(entitySetUrl))
{
return false;
}
string url = string.Format("{0}/{1}?$top=1", svcStatus.RootURL, entitySetUrl);
Response response = WebHelper.Get(new Uri(url), Constants.V4AcceptHeaderJsonFullMetadata, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders);
payloadFormat = response.ResponsePayload.GetFormatFromPayload();
var payloadType = ContextHelper.GetPayloadType(response.ResponsePayload, payloadFormat, response.ResponseHeaders);
if (payloadType == RuleEngine.PayloadType.Feed)
{
entityUrls = new KeyValuePair<string, IEnumerable<string>>(entitySetUrl, ContextHelper.GetEntries(response.ResponsePayload, payloadFormat));
return true;
}
}
return false;
}
/// <summary>
/// Gets the amount of entities from a feed.
/// </summary>
/// <param name="entitySetUrl">A feed URL.</param>
/// <returns>Return the amount of entities in current feed.</returns>
public static int GetEntitiesCountFromFeed(string entitySetUrl, IEnumerable<KeyValuePair<string, string>> headers = null)
{
int amount = 0;
if (!Uri.IsWellFormedUriString(entitySetUrl, UriKind.Absolute))
{
throw new UriFormatException("The input parameter 'entitySetUrl' is not a URL string.");
}
var resp = WebHelper.Get(new Uri(entitySetUrl), Constants.V4AcceptHeaderJsonFullMetadata, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, headers);
if (null != resp && HttpStatusCode.OK == resp.StatusCode)
{
var jObj = JObject.Parse(resp.ResponsePayload);
var jArr = jObj.GetValue(Constants.Value) as JArray;
amount += jArr.Count;
while (null != jObj[Constants.V4OdataNextLink])
{
string url = Uri.IsWellFormedUriString(jObj[Constants.V4OdataNextLink].ToString(), UriKind.Absolute) ?
jObj[Constants.V4OdataNextLink].ToString() :
ServiceStatus.GetInstance().RootURL.TrimEnd('/') + "/" + jObj[Constants.V4OdataNextLink].ToString();
resp = WebHelper.Get(new Uri(url), Constants.V4AcceptHeaderJsonFullMetadata, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, headers);
jObj = JObject.Parse(resp.ResponsePayload);
jArr = jObj.GetValue(Constants.Value) as JArray;
amount += jArr.Count;
}
}
return amount;
}
/// <summary>
/// Clear the property values list.
/// </summary>
public static void ClearPropertyNamesList()
{
names = new List<string>();
}
/// <summary>
/// Clear the property values list.
/// </summary>
public static void ClearProperyValsList()
{
vals = new List<JToken>();
}
/// <summary>
/// Clear the properties list.
/// </summary>
public static void ClearPropertiesList()
{
props = new List<JProperty>();
}
/// <summary>
/// Store the name which is got from entry's properties.
/// </summary>
private static List<string> names = new List<string>();
/// <summary>
/// Store the value which is got from entry's properties.
/// </summary>
private static List<JToken> vals = new List<JToken>();
/// <summary>
/// Store the properties which is got from entry.
/// </summary>
private static List<JProperty> props = new List<JProperty>();
}
}
| |
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using FluentAssertions;
using Moq;
using StockportWebapp.Config;
using StockportWebapp.FeatureToggling;
using StockportWebapp.Http;
using StockportWebapp.Services;
using StockportWebapp.Utils;
using Xunit;
namespace StockportWebappTests_Unit.Unit.Services
{
public class HealthcheckServiceTest
{
private readonly HealthcheckService _healthcheckService;
private readonly string _shaPath;
private readonly string _appVersionPath;
private readonly Mock<IFileWrapper> _fileWrapperMock;
private readonly Mock<IHttpClient> _mockHttpClient = new Mock<IHttpClient>();
private readonly Mock<IStubToUrlConverter> _mockUrlGenerator;
private const string healthcheckUrl = "http://localhost:5000/_healthcheck";
private readonly Mock<IApplicationConfiguration> _configuration;
private readonly BusinessId _businessId;
public HealthcheckServiceTest()
{
_appVersionPath = "./Unit/version.txt";
_shaPath = "./Unit/sha.txt";
_fileWrapperMock = new Mock<IFileWrapper>();
_businessId = new BusinessId("businessId");
_mockUrlGenerator = new Mock<IStubToUrlConverter>();
_mockUrlGenerator.Setup(o => o.HealthcheckUrl()).Returns(healthcheckUrl);
_configuration = new Mock<IApplicationConfiguration>();
_configuration.Setup(_ => _.GetContentApiAuthenticationKey()).Returns("AuthKey");
var httpResponseMessage = new HttpResponse(200, "{\"appVersion\":\"dev\",\"sha\":\"test-sha\",\"environment\":\"local\",\"redisValueData\":[]}", "");
_mockHttpClient
.Setup(_ => _.Get(It.IsAny<string>(), It.IsAny<Dictionary<string, string>>()))
.ReturnsAsync(httpResponseMessage);
SetUpFakeFileSystem();
_healthcheckService = CreateHealthcheckService(_appVersionPath, _shaPath, new FeatureToggles());
}
private void SetUpFakeFileSystem()
{
_fileWrapperMock.Setup(x => x.Exists(_appVersionPath)).Returns(true);
_fileWrapperMock.Setup(x => x.ReadAllLines(_appVersionPath)).Returns(new[] { "0.0.3" });
_fileWrapperMock.Setup(x => x.Exists(_shaPath)).Returns(true);
_fileWrapperMock.Setup(x => x.ReadAllLines(_shaPath))
.Returns(new[] { "d8213ee84c7d8c119c401b7ddd0adef923692188" });
}
private HealthcheckService CreateHealthcheckService(string appVersionPath, string shaPath,
FeatureToggles featureToggles)
{
return new HealthcheckService(appVersionPath, shaPath, _fileWrapperMock.Object, featureToggles, _mockHttpClient.Object, _mockUrlGenerator.Object, "local", _configuration.Object, _businessId);
}
private HealthcheckService CreateHealthcheckServiceWithDefaultFeatureToggles(string appVersionPath,
string shaPath)
{
return CreateHealthcheckService(appVersionPath, shaPath, new FeatureToggles());
}
[Fact]
public async Task ShouldContainTheAppVersionInTheResponse()
{
var check = await _healthcheckService.Get();
check.AppVersion.Should().Be("0.0.3");
}
[Fact]
public async Task ShouldContainTheGitShaInTheResponse()
{
var check = await _healthcheckService.Get();
check.SHA.Should().Be("d8213ee84c7d8c119c401b7ddd0adef923692188");
}
[Fact]
public async Task ShouldSetAppVersionToDevIfFileNotFound()
{
var notFoundVersionPath = "notfound";
_fileWrapperMock.Setup(x => x.Exists(notFoundVersionPath)).Returns(false);
var healthCheckServiceWithNotFoundVersion =
CreateHealthcheckServiceWithDefaultFeatureToggles(notFoundVersionPath, _shaPath);
var check = await healthCheckServiceWithNotFoundVersion.Get();
check.AppVersion.Should().Be("dev");
}
[Fact]
public async Task ShouldSetAppVersionToDevIfFileEmpty()
{
string newFile = "newFile";
_fileWrapperMock.Setup(x => x.Exists(newFile)).Returns(true);
_fileWrapperMock.Setup(x => x.ReadAllLines(newFile)).Returns(new string[] { });
var healthCheckServiceWithNotFoundVersion = CreateHealthcheckServiceWithDefaultFeatureToggles(newFile,
_shaPath);
var check = await healthCheckServiceWithNotFoundVersion.Get();
check.AppVersion.Should().Be("dev");
}
[Fact]
public async Task ShouldSetAppVersionToDevIfFileHasAnEmptyAString()
{
string newFile = "newFile";
_fileWrapperMock.Setup(x => x.Exists(newFile)).Returns(true);
_fileWrapperMock.Setup(x => x.ReadAllLines(newFile)).Returns(new[] { "" });
var healthCheckServiceWithNotFoundVersion = CreateHealthcheckServiceWithDefaultFeatureToggles(newFile,
_shaPath);
var check = await healthCheckServiceWithNotFoundVersion.Get();
check.AppVersion.Should().Be("dev");
}
[Fact]
public async Task ShouldSetSHAToEmptyIfFileNotFound()
{
var notFoundShaPath = "notfound";
_fileWrapperMock.Setup(x => x.Exists(notFoundShaPath)).Returns(false);
var healthCheckServiceWithNotFoundVersion =
CreateHealthcheckServiceWithDefaultFeatureToggles(_appVersionPath, notFoundShaPath);
var check = await healthCheckServiceWithNotFoundVersion.Get();
check.SHA.Should().Be("");
}
[Fact]
public async Task ShouldIncludeFeatureTogglesInHealthcheck()
{
var featureToggles = new FeatureToggles();
var healthCheckServiceWithNotFoundVersion = CreateHealthcheckService(_appVersionPath, _shaPath,
featureToggles);
var check = await healthCheckServiceWithNotFoundVersion.Get();
check.FeatureToggles.Should().NotBeNull();
check.FeatureToggles.Should().BeEquivalentTo(featureToggles);
}
[Fact]
public async Task ShouldSetAppDependenciesGotFromTheContentApi()
{
var check = await _healthcheckService.Get();
check.Dependencies.Should().NotBeNull();
check.Dependencies.Should().ContainKey("contentApi");
var dependency = check.Dependencies["contentApi"];
dependency.AppVersion.Should().Be("dev");
dependency.SHA.Should().Be("test-sha");
dependency.FeatureToggles.Should().BeNull();
}
[Fact]
public async Task ShouldSetAppDependenciesToNullIfNoResponseGotFromContentApi()
{
var httpResponseMessage = new HttpResponse((int)HttpStatusCode.BadRequest, new StringContent(""), null);
_mockHttpClient
.Setup(_ => _.Get(It.IsAny<string>(), It.IsAny<Dictionary<string, string>>()))
.ReturnsAsync(httpResponseMessage);
var healthcheckService = new HealthcheckService(_appVersionPath, _shaPath, _fileWrapperMock.Object,
new FeatureToggles(), _mockHttpClient.Object, _mockUrlGenerator.Object, "local", _configuration.Object, _businessId);
var check = await healthcheckService.Get();
check.Dependencies.Should().NotBeNull();
check.Dependencies.Should().ContainKey("contentApi");
var dependency = check.Dependencies["contentApi"];
dependency.AppVersion.Should().Be("Not available");
dependency.SHA.Should().Be("Not available");
dependency.FeatureToggles.Should().BeNull();
dependency.Dependencies.Should().BeEmpty();
}
[Fact]
public async Task ShouldSetAppDependenciesToNullIfRequestToContentApi()
{
_mockHttpClient
.Setup(_ => _.Get(It.IsAny<string>(), It.IsAny<Dictionary<string, string>>()))
.ReturnsAsync(default(HttpResponse));
var healthcheckService = new HealthcheckService(_appVersionPath, _shaPath, _fileWrapperMock.Object,
new FeatureToggles(), _mockHttpClient.Object, _mockUrlGenerator.Object, "local", _configuration.Object, _businessId);
var check = await healthcheckService.Get();
check.Dependencies.Should().NotBeNull();
check.Dependencies.Should().ContainKey("contentApi");
var dependency = check.Dependencies["contentApi"];
dependency.AppVersion.Should().Be("Not available");
dependency.SHA.Should().Be("Not available");
dependency.FeatureToggles.Should().BeNull();
dependency.Dependencies.Should().BeEmpty();
}
[Fact]
public async Task ShouldContainTheBusinessIdInTheResponse()
{
var check = await _healthcheckService.Get();
check.BusinessId.Should().Be("businessId");
}
}
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using System.Collections;
using System.Configuration;
using PCSComUtils.DataAccess;
using PCSComUtils.PCSExc;
using PCSComUtils.Common;
namespace PCSComSale.Order.DS
{
public class SO_CustomerItemRefDetailDS
{
public SO_CustomerItemRefDetailDS()
{
}
private const string THIS = "PCSComUtils.Framework.TableFrame.DS.SO_CustomerItemRefDetailDS";
//**************************************************************************
/// <Description>
/// This method uses to add data to SO_CustomerItemRefDetail
/// </Description>
/// <Inputs>
/// SO_CustomerItemRefDetailVO
/// </Inputs>
/// <Outputs>
/// newly inserted primarkey value
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, October 18, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Add(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".Add()";
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS =null;
try
{
SO_CustomerItemRefDetailVO objObject = (SO_CustomerItemRefDetailVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql= "INSERT INTO SO_CustomerItemRefDetail("
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD + ","
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMMODEL_FLD + ","
+ SO_CustomerItemRefDetailTable.PRODUCTID_FLD + ","
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMREFMASTERID_FLD + ","
+ SO_CustomerItemRefDetailTable.UNITPRICE_FLD + ","
+ SO_CustomerItemRefDetailTable.UNITOFMEASUREID_FLD + ")"
+ "VALUES(?,?,?,?,?,?)";
ocmdPCS.Parameters.Add(new OleDbParameter(SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD, OleDbType.VarChar));
ocmdPCS.Parameters[SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD].Value = objObject.CustomerItemCode;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_CustomerItemRefDetailTable.CUSTOMERITEMMODEL_FLD, OleDbType.VarChar));
ocmdPCS.Parameters[SO_CustomerItemRefDetailTable.CUSTOMERITEMMODEL_FLD].Value = objObject.CustomerItemModel;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_CustomerItemRefDetailTable.PRODUCTID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_CustomerItemRefDetailTable.PRODUCTID_FLD].Value = objObject.ProductID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_CustomerItemRefDetailTable.CUSTOMERITEMREFMASTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_CustomerItemRefDetailTable.CUSTOMERITEMREFMASTERID_FLD].Value = objObject.CustomerItemRefMasterID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_CustomerItemRefDetailTable.UNITPRICE_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[SO_CustomerItemRefDetailTable.UNITPRICE_FLD].Value = objObject.UnitPrice;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_CustomerItemRefDetailTable.UNITOFMEASUREID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_CustomerItemRefDetailTable.UNITOFMEASUREID_FLD].Value = objObject.UnitOfMeasureID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to delete data from SO_CustomerItemRefDetail
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// void
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Delete(int pintID)
{
const string METHOD_NAME = THIS + ".Delete()";
string strSql = String.Empty;
strSql= "DELETE " + SO_CustomerItemRefDetailTable.TABLE_NAME + " WHERE " + "CustomerItemRefDetailID" + "=" + pintID.ToString();
OleDbConnection oconPCS=null;
OleDbCommand ocmdPCS =null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
ocmdPCS = null;
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from SO_CustomerItemRefDetail
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// SO_CustomerItemRefDetailVO
/// </Outputs>
/// <Returns>
/// SO_CustomerItemRefDetailVO
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, October 18, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(int pintID)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
DataSet dstPCS = new DataSet();
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMREFDETAILID_FLD + ","
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD + ","
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMMODEL_FLD + ","
+ SO_CustomerItemRefDetailTable.PRODUCTID_FLD + ","
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMREFMASTERID_FLD + ","
+ SO_CustomerItemRefDetailTable.UNITPRICE_FLD + ","
+ SO_CustomerItemRefDetailTable.UNITOFMEASUREID_FLD
+ " FROM " + SO_CustomerItemRefDetailTable.TABLE_NAME
+" WHERE " + SO_CustomerItemRefDetailTable.CUSTOMERITEMREFDETAILID_FLD + "=" + pintID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
SO_CustomerItemRefDetailVO objObject = null;
if (odrPCS.Read())
{
objObject = new SO_CustomerItemRefDetailVO();
objObject.CustomerItemRefDetailID = int.Parse(odrPCS[SO_CustomerItemRefDetailTable.CUSTOMERITEMREFDETAILID_FLD].ToString());
objObject.CustomerItemCode = odrPCS[SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD].ToString();
objObject.CustomerItemModel = odrPCS[SO_CustomerItemRefDetailTable.CUSTOMERITEMMODEL_FLD].ToString();
objObject.ProductID = int.Parse(odrPCS[SO_CustomerItemRefDetailTable.PRODUCTID_FLD].ToString());
objObject.CustomerItemRefMasterID = int.Parse(odrPCS[SO_CustomerItemRefDetailTable.CUSTOMERITEMREFMASTERID_FLD].ToString());
objObject.UnitPrice = Decimal.Parse(odrPCS[SO_CustomerItemRefDetailTable.UNITPRICE_FLD].ToString());
objObject.UnitOfMeasureID = int.Parse(odrPCS[SO_CustomerItemRefDetailTable.UNITOFMEASUREID_FLD].ToString());
}
return objObject;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from SO_CustomerItemRefDetail
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// SO_CustomerItemRefDetailVO
/// </Outputs>
/// <Returns>
/// SO_CustomerItemRefDetailVO
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, October 18, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(int pintProductID, int pintCustomerID)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
DataSet dstPCS = new DataSet();
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMREFDETAILID_FLD + ","
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD + ","
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMMODEL_FLD + ","
+ SO_CustomerItemRefDetailTable.PRODUCTID_FLD + ","
+ SO_CustomerItemRefDetailTable.TABLE_NAME + "." + SO_CustomerItemRefDetailTable.CUSTOMERITEMREFMASTERID_FLD + ","
+ SO_CustomerItemRefDetailTable.UNITPRICE_FLD + ","
+ SO_CustomerItemRefDetailTable.UNITOFMEASUREID_FLD
+ " FROM " + SO_CustomerItemRefDetailTable.TABLE_NAME + " INNER JOIN " + SO_CustomerItemRefMasterTable.TABLE_NAME
+ " ON " + SO_CustomerItemRefDetailTable.TABLE_NAME + "." + SO_CustomerItemRefDetailTable.CUSTOMERITEMREFMASTERID_FLD
+ " = " + SO_CustomerItemRefMasterTable.TABLE_NAME + "." + SO_CustomerItemRefMasterTable.CUSTOMERITEMREFMASTERID_FLD
+ " WHERE " + SO_CustomerItemRefDetailTable.PRODUCTID_FLD + "=" + pintProductID
+ " AND " + SO_CustomerItemRefMasterTable.PARTYID_FLD + "=" + pintCustomerID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
SO_CustomerItemRefDetailVO objObject = null;
if (odrPCS.Read())
{
objObject = new SO_CustomerItemRefDetailVO();
objObject.CustomerItemRefDetailID = int.Parse(odrPCS[SO_CustomerItemRefDetailTable.CUSTOMERITEMREFDETAILID_FLD].ToString());
objObject.CustomerItemCode = odrPCS[SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD].ToString();
objObject.CustomerItemModel = odrPCS[SO_CustomerItemRefDetailTable.CUSTOMERITEMMODEL_FLD].ToString();
objObject.ProductID = int.Parse(odrPCS[SO_CustomerItemRefDetailTable.PRODUCTID_FLD].ToString());
objObject.CustomerItemRefMasterID = int.Parse(odrPCS[SO_CustomerItemRefDetailTable.CUSTOMERITEMREFMASTERID_FLD].ToString());
objObject.UnitPrice = Decimal.Parse(odrPCS[SO_CustomerItemRefDetailTable.UNITPRICE_FLD].ToString());
objObject.UnitOfMeasureID = int.Parse(odrPCS[SO_CustomerItemRefDetailTable.UNITOFMEASUREID_FLD].ToString());
}
return objObject;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update data to SO_CustomerItemRefDetail
/// </Description>
/// <Inputs>
/// SO_CustomerItemRefDetailVO
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Update(object pobjObjecVO)
{
const string METHOD_NAME = THIS + ".Update()";
SO_CustomerItemRefDetailVO objObject = (SO_CustomerItemRefDetailVO) pobjObjecVO;
//prepare value for parameters
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
strSql= "UPDATE SO_CustomerItemRefDetail SET "
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD + "= ?" + ","
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMMODEL_FLD + "= ?" + ","
+ SO_CustomerItemRefDetailTable.PRODUCTID_FLD + "= ?" + ","
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMREFMASTERID_FLD + "= ?" + ","
+ SO_CustomerItemRefDetailTable.UNITPRICE_FLD + "= ?" + ","
+ SO_CustomerItemRefDetailTable.UNITOFMEASUREID_FLD + "= ?"
+" WHERE " + SO_CustomerItemRefDetailTable.CUSTOMERITEMREFDETAILID_FLD + "= ?";
ocmdPCS.Parameters.Add(new OleDbParameter(SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD, OleDbType.VarChar));
ocmdPCS.Parameters[SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD].Value = objObject.CustomerItemCode;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_CustomerItemRefDetailTable.CUSTOMERITEMMODEL_FLD, OleDbType.VarChar));
ocmdPCS.Parameters[SO_CustomerItemRefDetailTable.CUSTOMERITEMMODEL_FLD].Value = objObject.CustomerItemModel;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_CustomerItemRefDetailTable.PRODUCTID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_CustomerItemRefDetailTable.PRODUCTID_FLD].Value = objObject.ProductID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_CustomerItemRefDetailTable.CUSTOMERITEMREFMASTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_CustomerItemRefDetailTable.CUSTOMERITEMREFMASTERID_FLD].Value = objObject.CustomerItemRefMasterID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_CustomerItemRefDetailTable.UNITPRICE_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[SO_CustomerItemRefDetailTable.UNITPRICE_FLD].Value = objObject.UnitPrice;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_CustomerItemRefDetailTable.UNITOFMEASUREID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_CustomerItemRefDetailTable.UNITOFMEASUREID_FLD].Value = objObject.UnitOfMeasureID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_CustomerItemRefDetailTable.CUSTOMERITEMREFDETAILID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_CustomerItemRefDetailTable.CUSTOMERITEMREFDETAILID_FLD].Value = objObject.CustomerItemRefDetailID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from SO_CustomerItemRefDetail
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, October 18, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet List()
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMREFDETAILID_FLD + ","
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD + ","
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMMODEL_FLD + ","
+ SO_CustomerItemRefDetailTable.PRODUCTID_FLD + ","
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMREFMASTERID_FLD + ","
+ SO_CustomerItemRefDetailTable.UNITPRICE_FLD + ","
+ SO_CustomerItemRefDetailTable.UNITOFMEASUREID_FLD
+ " FROM " + SO_CustomerItemRefDetailTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,SO_CustomerItemRefDetailTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update a DataSet
/// </Description>
/// <Inputs>
/// DataSet
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, October 18, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void UpdateDataSet(DataSet pData)
{
const string METHOD_NAME = THIS + ".UpdateDataSet()";
string strSql;
OleDbConnection oconPCS =null;
OleDbCommandBuilder odcbPCS ;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
try
{
strSql= "SELECT "
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMREFDETAILID_FLD + ","
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD + ","
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMMODEL_FLD + ","
+ SO_CustomerItemRefDetailTable.PRODUCTID_FLD + ","
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMREFMASTERID_FLD + ","
+ SO_CustomerItemRefDetailTable.UNITPRICE_FLD + ","
+ SO_CustomerItemRefDetailTable.UNITOFMEASUREID_FLD
+ " FROM " + SO_CustomerItemRefDetailTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
odcbPCS = new OleDbCommandBuilder(odadPCS);
pData.EnforceConstraints = false;
odadPCS.Update(pData, "SO_CustomerItemRefDetail");
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// Get detail by MasterID and CCNID
/// </summary>
/// <param name="pintMasterID"></param>
/// <param name="pintCCNID"></param>
/// <returns></returns>
public DataSet List(int pintMasterID, int pintCCNID)
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ ITM_ProductTable.TABLE_NAME + "." + ITM_ProductTable.CODE_FLD + ","
+ ITM_ProductTable.TABLE_NAME + "." + ITM_ProductTable.DESCRIPTION_FLD + ","
+ ITM_ProductTable.TABLE_NAME + "." + ITM_ProductTable.REVISION_FLD + ","
+ ITM_CategoryTable.TABLE_NAME + "." + ITM_CategoryTable.CODE_FLD + " as " + ITM_CategoryTable.TABLE_NAME + ITM_CategoryTable.CODE_FLD + ","
+ MST_UnitOfMeasureTable.TABLE_NAME + "." + MST_UnitOfMeasureTable.CODE_FLD + " as " + MST_UnitOfMeasureTable.TABLE_NAME + MST_UnitOfMeasureTable.CODE_FLD + ","
+ SO_CustomerItemRefDetailTable.UNITPRICE_FLD + ","
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMREFDETAILID_FLD + ","
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD + ","
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMMODEL_FLD + ","
+ SO_CustomerItemRefDetailTable.TABLE_NAME + "." + SO_CustomerItemRefDetailTable.PRODUCTID_FLD + ","
+ SO_CustomerItemRefDetailTable.TABLE_NAME + "." + SO_CustomerItemRefDetailTable.CUSTOMERITEMREFMASTERID_FLD + ","
+ SO_CustomerItemRefDetailTable.TABLE_NAME + "." + SO_CustomerItemRefDetailTable.UNITOFMEASUREID_FLD
+ " FROM " + SO_CustomerItemRefDetailTable.TABLE_NAME + " INNER JOIN "
+ SO_CustomerItemRefMasterTable.TABLE_NAME + " ON " + SO_CustomerItemRefMasterTable.TABLE_NAME + "." + SO_CustomerItemRefMasterTable.CUSTOMERITEMREFMASTERID_FLD
+ "=" + SO_CustomerItemRefDetailTable.TABLE_NAME + "." + SO_CustomerItemRefDetailTable.CUSTOMERITEMREFMASTERID_FLD
+ " INNER JOIN " + ITM_ProductTable.TABLE_NAME + " ON " + ITM_ProductTable.TABLE_NAME + "." + ITM_ProductTable.PRODUCTID_FLD + "="
+ SO_CustomerItemRefDetailTable.TABLE_NAME + "." + SO_CustomerItemRefDetailTable.PRODUCTID_FLD
+ " LEFT JOIN MST_UnitOfMeasure on MST_UnitOfMeasure.UnitOfMeasureID = " + SO_CustomerItemRefDetailTable.TABLE_NAME + "." + SO_CustomerItemRefDetailTable.UNITOFMEASUREID_FLD
+ " LEFT JOIN ITM_Category on ITM_Category.CategoryID = " + ITM_ProductTable.TABLE_NAME + "." + ITM_ProductTable.CATEGORYID_FLD
+ " WHERE "+ SO_CustomerItemRefMasterTable.TABLE_NAME + "." + SO_CustomerItemRefMasterTable.PARTYID_FLD + "=" + pintMasterID
+ " AND " + SO_CustomerItemRefMasterTable.TABLE_NAME + "." + SO_CustomerItemRefMasterTable.CCNID_FLD + "=" + pintCCNID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,SO_CustomerItemRefDetailTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
#region // HACK: DuongNA 2005-10-20
//**************************************************************************
/// <Description>
/// This method uses to get data from SO_CustomerItemRefDetail
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// SO_CustomerItemRefDetailVO
/// </Outputs>
/// <Returns>
/// SO_CustomerItemRefDetailVO
/// </Returns>
/// <Authors>
/// DuongNA
/// </Authors>
/// <History>
/// Thursday, October 20, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(int pintMasterID, string pstrCustomerItemCode)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
DataSet dstPCS = new DataSet();
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMREFDETAILID_FLD + ","
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD + ","
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMMODEL_FLD + ","
+ SO_CustomerItemRefDetailTable.PRODUCTID_FLD + ","
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMREFMASTERID_FLD + ","
+ SO_CustomerItemRefDetailTable.UNITPRICE_FLD + ","
+ SO_CustomerItemRefDetailTable.UNITOFMEASUREID_FLD
+ " FROM " + SO_CustomerItemRefDetailTable.TABLE_NAME
+ " WHERE " + SO_CustomerItemRefDetailTable.CUSTOMERITEMREFMASTERID_FLD + "=" + pintMasterID
+ " AND RTRIM(LTRIM(" + SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD + "))= ?";
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Parameters.Add(new OleDbParameter(SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD, OleDbType.VarChar));
ocmdPCS.Parameters[SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD].Value = pstrCustomerItemCode;
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
SO_CustomerItemRefDetailVO objObject = new SO_CustomerItemRefDetailVO();
while (odrPCS.Read())
{
objObject.CustomerItemRefDetailID = int.Parse(odrPCS[SO_CustomerItemRefDetailTable.CUSTOMERITEMREFDETAILID_FLD].ToString());
objObject.CustomerItemCode = odrPCS[SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD].ToString();
objObject.CustomerItemModel = odrPCS[SO_CustomerItemRefDetailTable.CUSTOMERITEMMODEL_FLD].ToString();
objObject.ProductID = int.Parse(odrPCS[SO_CustomerItemRefDetailTable.PRODUCTID_FLD].ToString());
objObject.CustomerItemRefMasterID = int.Parse(odrPCS[SO_CustomerItemRefDetailTable.CUSTOMERITEMREFMASTERID_FLD].ToString());
objObject.UnitPrice = Decimal.Parse(odrPCS[SO_CustomerItemRefDetailTable.UNITPRICE_FLD].ToString());
objObject.UnitOfMeasureID = int.Parse(odrPCS[SO_CustomerItemRefDetailTable.UNITOFMEASUREID_FLD].ToString());
}
return objObject;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
#endregion // END: DuongNA 2005-10-20
//**************************************************************************
/// <Description>
/// This method uses to get data from SO_CustomerItemRefDetail
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// SO_CustomerItemRefDetailVO
/// </Outputs>
/// <Returns>
/// SO_CustomerItemRefDetailVO
/// </Returns>
/// <Authors>
/// TuanDM
/// </Authors>
/// <History>
/// Thursday, October 20, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(int pintMasterID, string pstrCustomerItemCode, string pstrCustomerItemModel)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
DataSet dstPCS = new DataSet();
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMREFDETAILID_FLD + ","
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD + ","
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMMODEL_FLD + ","
+ SO_CustomerItemRefDetailTable.PRODUCTID_FLD + ","
+ SO_CustomerItemRefDetailTable.CUSTOMERITEMREFMASTERID_FLD + ","
+ SO_CustomerItemRefDetailTable.UNITPRICE_FLD + ","
+ SO_CustomerItemRefDetailTable.UNITOFMEASUREID_FLD
+ " FROM " + SO_CustomerItemRefDetailTable.TABLE_NAME
+ " WHERE " + SO_CustomerItemRefDetailTable.CUSTOMERITEMREFMASTERID_FLD + "=" + pintMasterID
+ " AND RTRIM(LTRIM(" + SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD + "))= ?"
+ " AND RTRIM(LTRIM(" + SO_CustomerItemRefDetailTable.CUSTOMERITEMMODEL_FLD + "))= ?";
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Parameters.Add(new OleDbParameter(SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD, OleDbType.VarChar));
ocmdPCS.Parameters[SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD].Value = pstrCustomerItemCode;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_CustomerItemRefDetailTable.CUSTOMERITEMMODEL_FLD, OleDbType.VarChar));
ocmdPCS.Parameters[SO_CustomerItemRefDetailTable.CUSTOMERITEMMODEL_FLD].Value = pstrCustomerItemModel;
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
SO_CustomerItemRefDetailVO objObject = new SO_CustomerItemRefDetailVO();
while (odrPCS.Read())
{
objObject.CustomerItemRefDetailID = int.Parse(odrPCS[SO_CustomerItemRefDetailTable.CUSTOMERITEMREFDETAILID_FLD].ToString());
objObject.CustomerItemCode = odrPCS[SO_CustomerItemRefDetailTable.CUSTOMERITEMCODE_FLD].ToString();
objObject.CustomerItemModel = odrPCS[SO_CustomerItemRefDetailTable.CUSTOMERITEMMODEL_FLD].ToString();
objObject.ProductID = int.Parse(odrPCS[SO_CustomerItemRefDetailTable.PRODUCTID_FLD].ToString());
objObject.CustomerItemRefMasterID = int.Parse(odrPCS[SO_CustomerItemRefDetailTable.CUSTOMERITEMREFMASTERID_FLD].ToString());
objObject.UnitPrice = Decimal.Parse(odrPCS[SO_CustomerItemRefDetailTable.UNITPRICE_FLD].ToString());
objObject.UnitOfMeasureID = int.Parse(odrPCS[SO_CustomerItemRefDetailTable.UNITOFMEASUREID_FLD].ToString());
}
return objObject;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace iTrellis.ToDo.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace System.DirectoryServices.AccountManagement
{
internal class FindResultEnumerator<T> : IEnumerator<T>, IEnumerator
{
//
// Public properties
//
// Checks to make sure we're not before the start (beforeStart == true) or after
// the end (endReached == true) of the FindResult<T> collection, then retrieves the current
// principal from resultSet. If T == typeof(Principal), calls resultSet.CurrentAsPrincipal.
public T Current
{
[System.Security.SecurityCritical]
get
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "FindResultEnumerator", "Entering Current, T={0}", typeof(T));
CheckDisposed();
if (_beforeStart == true || _endReached == true || _resultSet == null)
{
// Either we're before the beginning or after the end of the collection.
GlobalDebug.WriteLineIf(
GlobalDebug.Warn,
"FindResultEnumerator",
"Current: bad position, beforeStart={0}, endReached={1}, resultSet={2}",
_beforeStart,
_endReached,
_resultSet);
throw new InvalidOperationException(SR.FindResultEnumInvalidPos);
}
Debug.Assert(typeof(T) == typeof(System.DirectoryServices.AccountManagement.Principal) || typeof(T).IsSubclassOf(typeof(System.DirectoryServices.AccountManagement.Principal)));
return (T)_resultSet.CurrentAsPrincipal;
}
}
object IEnumerator.Current
{
[System.Security.SecurityCritical]
get
{
return Current;
}
}
//
// Public methods
//
// Calls resultSet.MoveNext() to advance to the next principal in the ResultSet.
// Returns false when it reaches the end of the last ResultSet in resultSets, and sets endReached to true.
[System.Security.SecurityCritical]
public bool MoveNext()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "FindResultEnumerator", "Entering MoveNext, T={0}", typeof(T));
CheckDisposed();
// If we previously reached the end, nothing more to move on to
if (_endReached)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "FindResultEnumerator", "MoveNext: end previously reached");
return false;
}
// No ResultSet, so we've already reached the end
if (_resultSet == null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "FindResultEnumerator", "MoveNext: no resultSet");
return false;
}
bool f;
lock (_resultSet)
{
// If before the first ResultSet, move to the first ResultSet
if (_beforeStart == true)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "FindResultEnumerator", "MoveNext: Moving to first resultSet");
_beforeStart = false;
// In case we previously iterated over this ResultSet,
// and are now back to the start because our Reset() method was called.
// Or in case another instance of FindResultEnumerator previously iterated over this ResultSet.
_resultSet.Reset();
}
f = _resultSet.MoveNext();
}
// If f is false, we must have reached the end of resultSet.
if (!f)
{
// we've reached the end
_endReached = true;
}
GlobalDebug.WriteLineIf(GlobalDebug.Info, "FindResultEnumerator", "MoveNext: returning {0}", f);
return f;
}
[System.Security.SecurityCritical]
bool IEnumerator.MoveNext()
{
return MoveNext();
}
// Repositions us to the beginning by setting beforeStart to true. Also clears endReached
// by setting it back to false;
[System.Security.SecurityCritical]
public void Reset()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "FindResultEnumerator", "Entering Reset");
CheckDisposed();
_endReached = false;
_beforeStart = true;
}
[System.Security.SecurityCritical]
void IEnumerator.Reset()
{
Reset();
}
public void Dispose()
{
// We really don't have anything to Dispose, since our ResultSet is actually
// owned by our parent FindResult<T>. However, IEnumerable<T> requires us to implement
// IDisposable.
GlobalDebug.WriteLineIf(GlobalDebug.Info, "FindResultEnumerator", "Dispose: disposing");
_disposed = true;
}
//
// Internal Constructors
//
// Constructs an enumerator to enumerate over the supplied of ResultSet
// Note that resultSet can be null
internal FindResultEnumerator(ResultSet resultSet)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "FindResultEnumerator", "Ctor");
_resultSet = resultSet;
}
//
// Private Implementation
//
//
// SYNCHRONIZATION
// Access to:
// resultSet
// must be synchronized, since multiple enumerators could be iterating over us at once.
// Synchronize by locking on resultSet (if resultSet is non-null).
// The ResultSet over which we're enumerating, passed to us from the FindResult<T>.
// Note that there's conceptually one FindResultEnumerator per FindResult, but can be multiple
// actual FindResultEnumerator objects per FindResult, so there's no risk
// of multiple FindResultEnumerators "interfering" with each other by trying to enumerate
// over the same ResultSet.
//
// Note that S.DS (based on code review and testing) and Sys.Storage (based on code review)
// both seem fine with the "one enumerator per result set" model.
private ResultSet _resultSet;
// if true, we're before the start of the ResultSet
private bool _beforeStart = true;
// if true, we've reached the end of the ResultSet
private bool _endReached = false;
// true if Dispose() has been called
private bool _disposed = false;
//
private void CheckDisposed()
{
if (_disposed)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "FindResultEnumerator", "CheckDisposed: accessing disposed object");
throw new ObjectDisposedException("FindResultEnumerator");
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using System;
using NPOI.OpenXmlFormats.Dml.Spreadsheet;
using NPOI.SS.UserModel;
namespace NPOI.XSSF.UserModel
{
/**
* A client anchor is attached to an excel worksheet. It anchors against
* top-left and bottom-right cells.
*
* @author Yegor Kozlov
*/
public class XSSFClientAnchor : XSSFAnchor, IClientAnchor
{
private int anchorType;
/**
* Starting anchor point
*/
private CT_Marker cell1;
/**
* Ending anchor point
*/
private CT_Marker cell2;
/**
* Creates a new client anchor and defaults all the anchor positions to 0.
*/
public XSSFClientAnchor()
{
cell1 = new CT_Marker();
cell1.col= (0);
cell1.colOff=(0);
cell1.row=(0);
cell1.rowOff=(0);
cell2 = new CT_Marker();
cell2.col=(0);
cell2.colOff=(0);
cell2.row=(0);
cell2.rowOff=(0);
}
/**
* Creates a new client anchor and Sets the top-left and bottom-right
* coordinates of the anchor.
*
* @param dx1 the x coordinate within the first cell.
* @param dy1 the y coordinate within the first cell.
* @param dx2 the x coordinate within the second cell.
* @param dy2 the y coordinate within the second cell.
* @param col1 the column (0 based) of the first cell.
* @param row1 the row (0 based) of the first cell.
* @param col2 the column (0 based) of the second cell.
* @param row2 the row (0 based) of the second cell.
*/
public XSSFClientAnchor(int dx1, int dy1, int dx2, int dy2, int col1, int row1, int col2, int row2)
: this()
{
cell1.col = (col1);
cell1.colOff = (dx1);
cell1.row = (row1);
cell1.rowOff = (dy1);
cell2.col = (col2);
cell2.colOff = (dx2);
cell2.row = (row2);
cell2.rowOff = (dy2);
}
/**
* Create XSSFClientAnchor from existing xml beans
*
* @param cell1 starting anchor point
* @param cell2 ending anchor point
*/
internal XSSFClientAnchor(CT_Marker cell1, CT_Marker cell2)
{
this.cell1 = cell1;
this.cell2 = cell2;
}
public override bool Equals(Object o)
{
if (o == null || !(o is XSSFClientAnchor)) return false;
XSSFClientAnchor anchor = (XSSFClientAnchor)o;
return Dx1 == anchor.Dx1 &&
Dx2 == anchor.Dx2 &&
Dy1 == anchor.Dy1 &&
Dy2 == anchor.Dy2 &&
Col1 == anchor.Col1 &&
Col2 == anchor.Col2 &&
Row1 == anchor.Row1 &&
Row2 == anchor.Row2;
}
public override String ToString()
{
return "from : " + cell1.ToString() + "; to: " + cell2.ToString();
}
/**
* Return starting anchor point
*
* @return starting anchor point
*/
internal CT_Marker From
{
get
{
return cell1;
}
set
{
cell1 = value;
}
}
/**
* Return ending anchor point
*
* @return ending anchor point
*/
internal CT_Marker To
{
get
{
return cell2;
}
set
{
cell2 = value;
}
}
internal bool IsSet()
{
return !(cell1.col == 0 && cell2.col == 0 &&
cell1.row == 0 && cell2.row == 0);
}
#region IClientAnchor Members
public override int Dx1
{
get
{
return (int)cell1.colOff;
}
set
{
cell1.colOff = value;
}
}
public override int Dy1
{
get
{
return (int)cell1.rowOff;
}
set
{
cell1.rowOff = value;
}
}
public override int Dy2
{
get
{
return (int)cell2.rowOff;
}
set
{
cell2.rowOff = value;
}
}
public override int Dx2
{
get
{
return (int)cell2.colOff;
}
set
{
cell2.colOff = value;
}
}
public int AnchorType
{
get
{
return this.anchorType;
}
set
{
this.anchorType = value;
}
}
public int Col1
{
get
{
return cell1.col;
}
set
{
cell1.col=value;
}
}
public int Col2
{
get
{
return cell2.col;
}
set
{
cell2.col = value;
}
}
public int Row1
{
get
{
return cell1.row;
}
set
{
cell1.row = value;
}
}
public int Row2
{
get
{
return cell2.row;
}
set
{
cell2.row = value;
}
}
#endregion
}
}
| |
// Copyright (c) Valdis Iljuconoks. All rights reserved.
// Licensed under Apache-2.0. See the LICENSE file in the project root for more information
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace DbLocalizationProvider.Abstractions
{
/// <summary>
/// Collection of translations.
/// </summary>
public class LocalizationResourceTranslationCollection : List<LocalizationResourceTranslation>
{
private readonly bool _enableInvariantCultureFallback;
/// <summary>
/// Initializes new instance of the class with specified fallback to invariant language setting.
/// </summary>
/// <param name="enableInvariantCultureFallback">Should we use invariant fallback or not.</param>
public LocalizationResourceTranslationCollection(bool enableInvariantCultureFallback)
{
_enableInvariantCultureFallback = enableInvariantCultureFallback;
}
/// <summary>
/// Finds translation the by language.
/// </summary>
/// <param name="language">The language.</param>
/// <returns>Translation class</returns>
public LocalizationResourceTranslation FindByLanguage(CultureInfo language)
{
return FindByLanguage(language.Name);
}
/// <summary>
/// Finds translation by language.
/// </summary>
/// <param name="language">The language.</param>
/// <returns>Translation class</returns>
public LocalizationResourceTranslation FindByLanguage(string language)
{
return this.FirstOrDefault(t => t.Language == language);
}
/// <summary>
/// Find translation in invariant culture.
/// </summary>
/// <returns>Translation class</returns>
public LocalizationResourceTranslation InvariantTranslation()
{
return FindByLanguage(CultureInfo.InvariantCulture);
}
/// <summary>
/// Finds translation by language.
/// </summary>
/// <param name="language">The language.</param>
/// <returns>Translation class</returns>
public string ByLanguage(CultureInfo language)
{
return ByLanguage(language.Name);
}
/// <summary>
/// Finds translation by language.
/// </summary>
/// <param name="language">The language.</param>
/// <returns>Translation class</returns>
public string ByLanguage(string language)
{
return ByLanguage(language, _enableInvariantCultureFallback);
}
/// <summary>
/// Finds translation by language.
/// </summary>
/// <param name="language">The language.</param>
/// <param name="invariantCultureFallback">if set to <c>true</c> invariant culture fallback is used.</param>
/// <returns>Translation class</returns>
public string ByLanguage(CultureInfo language, bool invariantCultureFallback)
{
return ByLanguage(language.Name, invariantCultureFallback);
}
/// <summary>
/// Finds translation by language.
/// </summary>
/// <param name="language">The language.</param>
/// <param name="invariantCultureFallback">if set to <c>true</c> [invariant culture fallback].</param>
/// <returns>Translation class</returns>
/// <exception cref="ArgumentNullException">language</exception>
public string ByLanguage(string language, bool invariantCultureFallback)
{
if (language == null)
{
throw new ArgumentNullException(nameof(language));
}
var translation = FindByLanguage(language);
return translation != null ? translation.Value
: invariantCultureFallback
? FindByLanguage(string.Empty)?.Value
: string.Empty;
}
/// <summary>
/// Checks whether translation exists in given language.
/// </summary>
/// <param name="language">The language.</param>
/// <returns><c>true</c> is translation exists; otherwise <c>false</c></returns>
/// <exception cref="ArgumentNullException">language</exception>
public bool ExistsLanguage(string language)
{
if (language == null)
{
throw new ArgumentNullException(nameof(language));
}
return this.FirstOrDefault(t => t.Language == language) != null;
}
/// <summary>
/// Get translation in given language or in any of fallback languages
/// </summary>
/// <param name="language">Language in which to get translation first</param>
/// <param name="fallbackLanguages">
/// If translation does not exist in language supplied by parameter <paramref name="language" /> then this list
/// of fallback languages is used to find translation
/// </param>
/// <returns>Translation in requested language or uin any fallback languages; <c>null</c> otherwise if translation is not found</returns>
public string GetValueWithFallback(CultureInfo language, IReadOnlyCollection<CultureInfo> fallbackLanguages)
{
return GetValueWithFallback(language.Name, fallbackLanguages);
}
/// <summary>
/// Get translation in given language or in any of fallback languages
/// </summary>
/// <param name="language">Language in which to get translation first</param>
/// <param name="fallbackLanguages">
/// If translation does not exist in language supplied by parameter <paramref name="language" /> then this list
/// of fallback languages is used to find translation
/// </param>
/// <returns>Translation in requested language or uin any fallback languages; <c>null</c> otherwise if translation is not found</returns>
public string GetValueWithFallback(string language, IReadOnlyCollection<CultureInfo> fallbackLanguages)
{
if (language == null)
{
throw new ArgumentNullException(nameof(language));
}
if (fallbackLanguages == null)
{
throw new ArgumentNullException(nameof(fallbackLanguages));
}
var inRequestedLanguage = FindByLanguage(language);
if (inRequestedLanguage != null)
{
return inRequestedLanguage.Value;
}
// check if we have regional language. if so - maybe we have parent language available
var cultureInfo = new CultureInfo(language);
if (!cultureInfo.Parent.Equals(CultureInfo.InvariantCulture))
{
var inParentLanguage = FindByLanguage(cultureInfo.Parent.Name);
if (inParentLanguage != null)
{
return inParentLanguage.Value;
}
}
// find if requested language is not "inside" fallback languages
var culture = new CultureInfo(language);
var searchableLanguages = fallbackLanguages.ToList();
if (fallbackLanguages.Contains(culture))
{
// requested language is inside fallback languages, so we need to "continue" from there
var restOfFallbackLanguages = fallbackLanguages.SkipWhile(c => !Equals(c, culture)).ToList();
// check if we are not at the end of the list
if (restOfFallbackLanguages.Any())
{
// if there are still elements - we have to skip 1 (as this is requested language)
searchableLanguages = restOfFallbackLanguages.Skip(1).ToList();
}
}
foreach (var fallbackLanguage in searchableLanguages)
{
var translationInFallback = FindByLanguage(fallbackLanguage);
if (translationInFallback != null)
{
return translationInFallback.Value;
}
}
return null;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Extensions.EnumExtensions;
using osu.Framework.Input;
using osuTK.Input;
using SDL2;
namespace osu.Framework.Platform.SDL2
{
public static class SDL2Extensions
{
public static Key ToKey(this SDL.SDL_Keysym sdlKeysym)
{
// Apple devices don't have the notion of NumLock (they have a Clear key instead).
// treat them as if they always have NumLock on (the numpad always performs its primary actions).
bool numLockOn = sdlKeysym.mod.HasFlagFast(SDL.SDL_Keymod.KMOD_NUM) || RuntimeInfo.IsApple;
switch (sdlKeysym.scancode)
{
default:
case SDL.SDL_Scancode.SDL_SCANCODE_UNKNOWN:
return Key.Unknown;
case SDL.SDL_Scancode.SDL_SCANCODE_KP_COMMA:
return Key.Comma;
case SDL.SDL_Scancode.SDL_SCANCODE_KP_TAB:
return Key.Tab;
case SDL.SDL_Scancode.SDL_SCANCODE_KP_BACKSPACE:
return Key.BackSpace;
case SDL.SDL_Scancode.SDL_SCANCODE_KP_A:
return Key.A;
case SDL.SDL_Scancode.SDL_SCANCODE_KP_B:
return Key.B;
case SDL.SDL_Scancode.SDL_SCANCODE_KP_C:
return Key.C;
case SDL.SDL_Scancode.SDL_SCANCODE_KP_D:
return Key.D;
case SDL.SDL_Scancode.SDL_SCANCODE_KP_E:
return Key.E;
case SDL.SDL_Scancode.SDL_SCANCODE_KP_F:
return Key.F;
case SDL.SDL_Scancode.SDL_SCANCODE_KP_SPACE:
return Key.Space;
case SDL.SDL_Scancode.SDL_SCANCODE_KP_CLEAR:
return Key.Clear;
case SDL.SDL_Scancode.SDL_SCANCODE_RETURN:
return Key.Enter;
case SDL.SDL_Scancode.SDL_SCANCODE_ESCAPE:
return Key.Escape;
case SDL.SDL_Scancode.SDL_SCANCODE_BACKSPACE:
return Key.BackSpace;
case SDL.SDL_Scancode.SDL_SCANCODE_TAB:
return Key.Tab;
case SDL.SDL_Scancode.SDL_SCANCODE_SPACE:
return Key.Space;
case SDL.SDL_Scancode.SDL_SCANCODE_APOSTROPHE:
return Key.Quote;
case SDL.SDL_Scancode.SDL_SCANCODE_COMMA:
return Key.Comma;
case SDL.SDL_Scancode.SDL_SCANCODE_MINUS:
return Key.Minus;
case SDL.SDL_Scancode.SDL_SCANCODE_PERIOD:
return Key.Period;
case SDL.SDL_Scancode.SDL_SCANCODE_SLASH:
return Key.Slash;
case SDL.SDL_Scancode.SDL_SCANCODE_0:
return Key.Number0;
case SDL.SDL_Scancode.SDL_SCANCODE_1:
return Key.Number1;
case SDL.SDL_Scancode.SDL_SCANCODE_2:
return Key.Number2;
case SDL.SDL_Scancode.SDL_SCANCODE_3:
return Key.Number3;
case SDL.SDL_Scancode.SDL_SCANCODE_4:
return Key.Number4;
case SDL.SDL_Scancode.SDL_SCANCODE_5:
return Key.Number5;
case SDL.SDL_Scancode.SDL_SCANCODE_6:
return Key.Number6;
case SDL.SDL_Scancode.SDL_SCANCODE_7:
return Key.Number7;
case SDL.SDL_Scancode.SDL_SCANCODE_8:
return Key.Number8;
case SDL.SDL_Scancode.SDL_SCANCODE_9:
return Key.Number9;
case SDL.SDL_Scancode.SDL_SCANCODE_SEMICOLON:
return Key.Semicolon;
case SDL.SDL_Scancode.SDL_SCANCODE_EQUALS:
return Key.Plus;
case SDL.SDL_Scancode.SDL_SCANCODE_LEFTBRACKET:
return Key.BracketLeft;
case SDL.SDL_Scancode.SDL_SCANCODE_BACKSLASH:
return Key.BackSlash;
case SDL.SDL_Scancode.SDL_SCANCODE_RIGHTBRACKET:
return Key.BracketRight;
case SDL.SDL_Scancode.SDL_SCANCODE_GRAVE:
return Key.Tilde;
case SDL.SDL_Scancode.SDL_SCANCODE_A:
return Key.A;
case SDL.SDL_Scancode.SDL_SCANCODE_B:
return Key.B;
case SDL.SDL_Scancode.SDL_SCANCODE_C:
return Key.C;
case SDL.SDL_Scancode.SDL_SCANCODE_D:
return Key.D;
case SDL.SDL_Scancode.SDL_SCANCODE_E:
return Key.E;
case SDL.SDL_Scancode.SDL_SCANCODE_F:
return Key.F;
case SDL.SDL_Scancode.SDL_SCANCODE_G:
return Key.G;
case SDL.SDL_Scancode.SDL_SCANCODE_H:
return Key.H;
case SDL.SDL_Scancode.SDL_SCANCODE_I:
return Key.I;
case SDL.SDL_Scancode.SDL_SCANCODE_J:
return Key.J;
case SDL.SDL_Scancode.SDL_SCANCODE_K:
return Key.K;
case SDL.SDL_Scancode.SDL_SCANCODE_L:
return Key.L;
case SDL.SDL_Scancode.SDL_SCANCODE_M:
return Key.M;
case SDL.SDL_Scancode.SDL_SCANCODE_N:
return Key.N;
case SDL.SDL_Scancode.SDL_SCANCODE_O:
return Key.O;
case SDL.SDL_Scancode.SDL_SCANCODE_P:
return Key.P;
case SDL.SDL_Scancode.SDL_SCANCODE_Q:
return Key.Q;
case SDL.SDL_Scancode.SDL_SCANCODE_R:
return Key.R;
case SDL.SDL_Scancode.SDL_SCANCODE_S:
return Key.S;
case SDL.SDL_Scancode.SDL_SCANCODE_T:
return Key.T;
case SDL.SDL_Scancode.SDL_SCANCODE_U:
return Key.U;
case SDL.SDL_Scancode.SDL_SCANCODE_V:
return Key.V;
case SDL.SDL_Scancode.SDL_SCANCODE_W:
return Key.W;
case SDL.SDL_Scancode.SDL_SCANCODE_X:
return Key.X;
case SDL.SDL_Scancode.SDL_SCANCODE_Y:
return Key.Y;
case SDL.SDL_Scancode.SDL_SCANCODE_Z:
return Key.Z;
case SDL.SDL_Scancode.SDL_SCANCODE_CAPSLOCK:
return Key.CapsLock;
case SDL.SDL_Scancode.SDL_SCANCODE_F1:
return Key.F1;
case SDL.SDL_Scancode.SDL_SCANCODE_F2:
return Key.F2;
case SDL.SDL_Scancode.SDL_SCANCODE_F3:
return Key.F3;
case SDL.SDL_Scancode.SDL_SCANCODE_F4:
return Key.F4;
case SDL.SDL_Scancode.SDL_SCANCODE_F5:
return Key.F5;
case SDL.SDL_Scancode.SDL_SCANCODE_F6:
return Key.F6;
case SDL.SDL_Scancode.SDL_SCANCODE_F7:
return Key.F7;
case SDL.SDL_Scancode.SDL_SCANCODE_F8:
return Key.F8;
case SDL.SDL_Scancode.SDL_SCANCODE_F9:
return Key.F9;
case SDL.SDL_Scancode.SDL_SCANCODE_F10:
return Key.F10;
case SDL.SDL_Scancode.SDL_SCANCODE_F11:
return Key.F11;
case SDL.SDL_Scancode.SDL_SCANCODE_F12:
return Key.F12;
case SDL.SDL_Scancode.SDL_SCANCODE_PRINTSCREEN:
return Key.PrintScreen;
case SDL.SDL_Scancode.SDL_SCANCODE_SCROLLLOCK:
return Key.ScrollLock;
case SDL.SDL_Scancode.SDL_SCANCODE_PAUSE:
return Key.Pause;
case SDL.SDL_Scancode.SDL_SCANCODE_INSERT:
return Key.Insert;
case SDL.SDL_Scancode.SDL_SCANCODE_HOME:
return Key.Home;
case SDL.SDL_Scancode.SDL_SCANCODE_PAGEUP:
return Key.PageUp;
case SDL.SDL_Scancode.SDL_SCANCODE_DELETE:
return Key.Delete;
case SDL.SDL_Scancode.SDL_SCANCODE_END:
return Key.End;
case SDL.SDL_Scancode.SDL_SCANCODE_PAGEDOWN:
return Key.PageDown;
case SDL.SDL_Scancode.SDL_SCANCODE_RIGHT:
return Key.Right;
case SDL.SDL_Scancode.SDL_SCANCODE_LEFT:
return Key.Left;
case SDL.SDL_Scancode.SDL_SCANCODE_DOWN:
return Key.Down;
case SDL.SDL_Scancode.SDL_SCANCODE_UP:
return Key.Up;
case SDL.SDL_Scancode.SDL_SCANCODE_NUMLOCKCLEAR:
return Key.NumLock;
case SDL.SDL_Scancode.SDL_SCANCODE_KP_DIVIDE:
return Key.KeypadDivide;
case SDL.SDL_Scancode.SDL_SCANCODE_KP_MULTIPLY:
return Key.KeypadMultiply;
case SDL.SDL_Scancode.SDL_SCANCODE_KP_MINUS:
return Key.KeypadMinus;
case SDL.SDL_Scancode.SDL_SCANCODE_KP_PLUS:
return Key.KeypadPlus;
case SDL.SDL_Scancode.SDL_SCANCODE_KP_ENTER:
return Key.KeypadEnter;
case SDL.SDL_Scancode.SDL_SCANCODE_KP_1:
return numLockOn ? Key.Keypad1 : Key.End;
case SDL.SDL_Scancode.SDL_SCANCODE_KP_2:
return numLockOn ? Key.Keypad2 : Key.Down;
case SDL.SDL_Scancode.SDL_SCANCODE_KP_3:
return numLockOn ? Key.Keypad3 : Key.PageDown;
case SDL.SDL_Scancode.SDL_SCANCODE_KP_4:
return numLockOn ? Key.Keypad4 : Key.Left;
case SDL.SDL_Scancode.SDL_SCANCODE_KP_5:
return Key.Keypad5;
case SDL.SDL_Scancode.SDL_SCANCODE_KP_6:
return numLockOn ? Key.Keypad6 : Key.Right;
case SDL.SDL_Scancode.SDL_SCANCODE_KP_7:
return numLockOn ? Key.Keypad7 : Key.Home;
case SDL.SDL_Scancode.SDL_SCANCODE_KP_8:
return numLockOn ? Key.Keypad8 : Key.Up;
case SDL.SDL_Scancode.SDL_SCANCODE_KP_9:
return numLockOn ? Key.Keypad9 : Key.PageUp;
case SDL.SDL_Scancode.SDL_SCANCODE_KP_0:
return numLockOn ? Key.Keypad0 : Key.Insert;
case SDL.SDL_Scancode.SDL_SCANCODE_KP_PERIOD:
return numLockOn ? Key.KeypadPeriod : Key.Delete;
case SDL.SDL_Scancode.SDL_SCANCODE_NONUSBACKSLASH:
return Key.NonUSBackSlash;
case SDL.SDL_Scancode.SDL_SCANCODE_F13:
return Key.F13;
case SDL.SDL_Scancode.SDL_SCANCODE_F14:
return Key.F14;
case SDL.SDL_Scancode.SDL_SCANCODE_F15:
return Key.F15;
case SDL.SDL_Scancode.SDL_SCANCODE_F16:
return Key.F16;
case SDL.SDL_Scancode.SDL_SCANCODE_F17:
return Key.F17;
case SDL.SDL_Scancode.SDL_SCANCODE_F18:
return Key.F18;
case SDL.SDL_Scancode.SDL_SCANCODE_F19:
return Key.F19;
case SDL.SDL_Scancode.SDL_SCANCODE_F20:
return Key.F20;
case SDL.SDL_Scancode.SDL_SCANCODE_F21:
return Key.F21;
case SDL.SDL_Scancode.SDL_SCANCODE_F22:
return Key.F22;
case SDL.SDL_Scancode.SDL_SCANCODE_F23:
return Key.F23;
case SDL.SDL_Scancode.SDL_SCANCODE_F24:
return Key.F24;
case SDL.SDL_Scancode.SDL_SCANCODE_MENU:
return Key.Menu;
case SDL.SDL_Scancode.SDL_SCANCODE_STOP:
return Key.Stop;
case SDL.SDL_Scancode.SDL_SCANCODE_MUTE:
return Key.Mute;
case SDL.SDL_Scancode.SDL_SCANCODE_VOLUMEUP:
return Key.VolumeUp;
case SDL.SDL_Scancode.SDL_SCANCODE_VOLUMEDOWN:
return Key.VolumeDown;
case SDL.SDL_Scancode.SDL_SCANCODE_CLEAR:
return Key.Clear;
case SDL.SDL_Scancode.SDL_SCANCODE_DECIMALSEPARATOR:
return Key.KeypadDecimal;
case SDL.SDL_Scancode.SDL_SCANCODE_LCTRL:
return Key.ControlLeft;
case SDL.SDL_Scancode.SDL_SCANCODE_LSHIFT:
return Key.ShiftLeft;
case SDL.SDL_Scancode.SDL_SCANCODE_LALT:
return Key.AltLeft;
case SDL.SDL_Scancode.SDL_SCANCODE_LGUI:
return Key.WinLeft;
case SDL.SDL_Scancode.SDL_SCANCODE_RCTRL:
return Key.ControlRight;
case SDL.SDL_Scancode.SDL_SCANCODE_RSHIFT:
return Key.ShiftRight;
case SDL.SDL_Scancode.SDL_SCANCODE_RALT:
return Key.AltRight;
case SDL.SDL_Scancode.SDL_SCANCODE_RGUI:
return Key.WinRight;
case SDL.SDL_Scancode.SDL_SCANCODE_AUDIONEXT:
return Key.TrackNext;
case SDL.SDL_Scancode.SDL_SCANCODE_AUDIOPREV:
return Key.TrackPrevious;
case SDL.SDL_Scancode.SDL_SCANCODE_AUDIOSTOP:
return Key.Stop;
case SDL.SDL_Scancode.SDL_SCANCODE_AUDIOPLAY:
return Key.PlayPause;
case SDL.SDL_Scancode.SDL_SCANCODE_AUDIOMUTE:
return Key.Mute;
case SDL.SDL_Scancode.SDL_SCANCODE_SLEEP:
return Key.Sleep;
}
}
public static WindowState ToWindowState(this SDL.SDL_WindowFlags windowFlags)
{
if (windowFlags.HasFlagFast(SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN_DESKTOP) ||
windowFlags.HasFlagFast(SDL.SDL_WindowFlags.SDL_WINDOW_BORDERLESS))
return WindowState.FullscreenBorderless;
if (windowFlags.HasFlagFast(SDL.SDL_WindowFlags.SDL_WINDOW_MINIMIZED))
return WindowState.Minimised;
if (windowFlags.HasFlagFast(SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN))
return WindowState.Fullscreen;
if (windowFlags.HasFlagFast(SDL.SDL_WindowFlags.SDL_WINDOW_MAXIMIZED))
return WindowState.Maximised;
return WindowState.Normal;
}
public static SDL.SDL_WindowFlags ToFlags(this WindowState state)
{
switch (state)
{
case WindowState.Normal:
return 0;
case WindowState.Fullscreen:
return SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN;
case WindowState.Maximised:
return SDL.SDL_WindowFlags.SDL_WINDOW_MAXIMIZED;
case WindowState.Minimised:
return SDL.SDL_WindowFlags.SDL_WINDOW_MINIMIZED;
case WindowState.FullscreenBorderless:
return SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN_DESKTOP;
}
return 0;
}
public static JoystickAxisSource ToJoystickAxisSource(this SDL.SDL_GameControllerAxis axis)
{
switch (axis)
{
default:
case SDL.SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_INVALID:
return 0;
case SDL.SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_LEFTX:
return JoystickAxisSource.GamePadLeftStickX;
case SDL.SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_LEFTY:
return JoystickAxisSource.GamePadLeftStickY;
case SDL.SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_TRIGGERLEFT:
return JoystickAxisSource.GamePadLeftTrigger;
case SDL.SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_RIGHTX:
return JoystickAxisSource.GamePadRightStickX;
case SDL.SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_RIGHTY:
return JoystickAxisSource.GamePadRightStickY;
case SDL.SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_TRIGGERRIGHT:
return JoystickAxisSource.GamePadRightTrigger;
}
}
public static JoystickButton ToJoystickButton(this SDL.SDL_GameControllerButton button)
{
switch (button)
{
default:
case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_INVALID:
return 0;
case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_A:
return JoystickButton.GamePadA;
case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_B:
return JoystickButton.GamePadB;
case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_X:
return JoystickButton.GamePadX;
case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_Y:
return JoystickButton.GamePadY;
case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_BACK:
return JoystickButton.GamePadBack;
case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_GUIDE:
return JoystickButton.GamePadGuide;
case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_START:
return JoystickButton.GamePadStart;
case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_LEFTSTICK:
return JoystickButton.GamePadLeftStick;
case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_RIGHTSTICK:
return JoystickButton.GamePadRightStick;
case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_LEFTSHOULDER:
return JoystickButton.GamePadLeftShoulder;
case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_RIGHTSHOULDER:
return JoystickButton.GamePadRightShoulder;
case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_DPAD_UP:
return JoystickButton.GamePadDPadUp;
case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_DPAD_DOWN:
return JoystickButton.GamePadDPadDown;
case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_DPAD_LEFT:
return JoystickButton.GamePadDPadLeft;
case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_DPAD_RIGHT:
return JoystickButton.GamePadDPadRight;
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
namespace FlatMate.Module.Common.Tasks.Cron
{
[Serializable]
public sealed class CrontabFieldImpl
{
public static readonly CrontabFieldImpl Day = new CrontabFieldImpl(CrontabFieldKind.Day, 1, 31, null);
public static readonly CrontabFieldImpl DayOfWeek = new CrontabFieldImpl(CrontabFieldKind.DayOfWeek, 0, 6,
new[]
{
"Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday",
"Saturday"
});
public static readonly CrontabFieldImpl Hour = new CrontabFieldImpl(CrontabFieldKind.Hour, 0, 23, null);
public static readonly CrontabFieldImpl Minute = new CrontabFieldImpl(CrontabFieldKind.Minute, 0, 59, null);
public static readonly CrontabFieldImpl Month = new CrontabFieldImpl(CrontabFieldKind.Month, 1, 12,
new[]
{
"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November",
"December"
});
private static readonly char[] Comma = { ',' };
private static readonly CompareInfo Comparer = CultureInfo.InvariantCulture.CompareInfo;
private static readonly CrontabFieldImpl[] FieldByKind = { Minute, Hour, Day, Month, DayOfWeek };
private readonly string[] _names;
private CrontabFieldImpl(CrontabFieldKind kind, int minValue, int maxValue, string[] names)
{
Debug.Assert(Enum.IsDefined(typeof(CrontabFieldKind), kind));
Debug.Assert(minValue >= 0);
Debug.Assert(maxValue >= minValue);
Debug.Assert(names == null || names.Length == maxValue - minValue + 1);
Kind = kind;
MinValue = minValue;
MaxValue = maxValue;
_names = names;
}
public CrontabFieldKind Kind { get; }
public int MaxValue { get; }
public int MinValue { get; }
public int ValueCount => MaxValue - MinValue + 1;
public void Format(CrontabField field, TextWriter writer, bool noNames)
{
if (field == null)
{
throw new ArgumentNullException(nameof(field));
}
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
var next = field.GetFirst();
var count = 0;
while (next != -1)
{
var first = next;
int last;
do
{
last = next;
next = field.Next(last + 1);
} while (next - last == 1);
if (count == 0 && first == MinValue && last == MaxValue)
{
writer.Write('*');
return;
}
if (count > 0)
{
writer.Write(',');
}
if (first == last)
{
FormatValue(first, writer, noNames);
}
else
{
FormatValue(first, writer, noNames);
writer.Write('-');
FormatValue(last, writer, noNames);
}
count++;
}
}
public static CrontabFieldImpl FromKind(CrontabFieldKind kind)
{
if (!Enum.IsDefined(typeof(CrontabFieldKind), kind))
{
throw new ArgumentException(string.Format(
"Invalid crontab field kind. Valid values are {0}.",
string.Join(", ", Enum.GetNames(typeof(CrontabFieldKind)))), nameof(kind));
}
return FieldByKind[(int) kind];
}
public void Parse(string str, CrontabFieldAccumulator acc)
{
if (acc == null)
{
throw new ArgumentNullException(nameof(acc));
}
if (string.IsNullOrEmpty(str))
{
return;
}
try
{
InternalParse(str, acc);
}
catch (FormatException e)
{
ThrowParseException(e, str);
}
}
private static void FastFormatNumericValue(int value, TextWriter writer)
{
Debug.Assert(value >= 0 && value < 100);
Debug.Assert(writer != null);
if (value >= 10)
{
writer.Write((char) ('0' + value / 10));
writer.Write((char) ('0' + value % 10));
}
else
{
writer.Write((char) ('0' + value));
}
}
private void FormatValue(int value, TextWriter writer, bool noNames)
{
Debug.Assert(writer != null);
if (noNames || _names == null)
{
if (value >= 0 && value < 100)
{
FastFormatNumericValue(value, writer);
}
else
{
writer.Write(value.ToString(CultureInfo.InvariantCulture));
}
}
else
{
var index = value - MinValue;
writer.Write(_names[index]);
}
}
private void InternalParse(string str, CrontabFieldAccumulator acc)
{
Debug.Assert(str != null);
Debug.Assert(acc != null);
if (str.Length == 0)
{
throw new FormatException("A crontab field value cannot be empty.");
}
//
// Next, look for a list of values (e.g. 1,2,3).
//
var commaIndex = str.IndexOf(",", StringComparison.Ordinal);
if (commaIndex > 0)
{
foreach (var token in str.Split(Comma))
{
InternalParse(token, acc);
}
}
else
{
var every = 1;
//
// Look for stepping first (e.g. */2 = every 2nd).
//
var slashIndex = str.IndexOf("/", StringComparison.Ordinal);
if (slashIndex > 0)
{
every = int.Parse(str.Substring(slashIndex + 1), CultureInfo.InvariantCulture);
str = str.Substring(0, slashIndex);
}
//
// Next, look for wildcard (*).
//
if (str.Length == 1 && str[0] == '*')
{
acc(-1, -1, every);
return;
}
//
// Next, look for a range of values (e.g. 2-10).
//
var dashIndex = str.IndexOf("-", StringComparison.Ordinal);
if (dashIndex > 0)
{
var first = ParseValue(str.Substring(0, dashIndex));
var last = ParseValue(str.Substring(dashIndex + 1));
acc(first, last, every);
return;
}
//
// Finally, handle the case where there is only one number.
//
var value = ParseValue(str);
if (every == 1)
{
acc(value, value, 1);
}
else
{
Debug.Assert(every != 0);
acc(value, MaxValue, every);
}
}
}
private int ParseValue(string str)
{
Debug.Assert(str != null);
if (str.Length == 0)
{
throw new FormatException("A crontab field value cannot be empty.");
}
var firstChar = str[0];
if (firstChar >= '0' && firstChar <= '9')
{
return int.Parse(str, CultureInfo.InvariantCulture);
}
if (_names == null)
{
throw new FormatException(string.Format("'{0}' is not a valid value for this crontab field. It must be a numeric value between {1} and {2} (all inclusive).", str, MinValue, MaxValue));
}
for (var i = 0; i < _names.Length; i++)
{
if (Comparer.IsPrefix(_names[i], str, CompareOptions.IgnoreCase))
{
return i + MinValue;
}
}
throw new FormatException(string.Format("'{0}' is not a known value name. Use one of the following: {1}.", str, string.Join(", ", _names)));
}
private static void ThrowParseException(Exception innerException, string str)
{
Debug.Assert(str != null);
Debug.Assert(innerException != null);
throw new FormatException(string.Format("'{0}' is not a valid crontab field expression.", str),
innerException);
}
}
}
| |
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.CSharp.TypeSystem.ConstantValues;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
namespace ICSharpCode.NRefactory.CSharp.TypeSystem
{
/// <summary>
/// Produces type and member definitions from the DOM.
/// </summary>
public class TypeSystemConvertVisitor : DepthFirstAstVisitor<IUnresolvedEntity>
{
readonly CSharpUnresolvedFile unresolvedFile;
UsingScope usingScope;
CSharpUnresolvedTypeDefinition currentTypeDefinition;
DefaultUnresolvedMethod currentMethod;
IInterningProvider interningProvider = new SimpleInterningProvider();
/// <summary>
/// Gets/Sets the interning provider to use.
/// The default value is a new <see cref="SimpleInterningProvider"/> instance.
/// </summary>
public IInterningProvider InterningProvider {
get { return interningProvider; }
set { interningProvider = value; }
}
/// <summary>
/// Gets/Sets whether to ignore XML documentation.
/// The default value is false.
/// </summary>
public bool SkipXmlDocumentation { get; set; }
/// <summary>
/// Creates a new TypeSystemConvertVisitor.
/// </summary>
/// <param name="fileName">The file name (used for DomRegions).</param>
public TypeSystemConvertVisitor(string fileName)
{
if (fileName == null)
throw new ArgumentNullException("fileName");
this.unresolvedFile = new CSharpUnresolvedFile(fileName);
this.usingScope = unresolvedFile.RootUsingScope;
}
/// <summary>
/// Creates a new TypeSystemConvertVisitor and initializes it with a given context.
/// </summary>
/// <param name="unresolvedFile">The parsed file to which members should be added.</param>
/// <param name="currentUsingScope">The current using scope.</param>
/// <param name="currentTypeDefinition">The current type definition.</param>
public TypeSystemConvertVisitor(CSharpUnresolvedFile unresolvedFile, UsingScope currentUsingScope = null, CSharpUnresolvedTypeDefinition currentTypeDefinition = null)
{
if (unresolvedFile == null)
throw new ArgumentNullException("unresolvedFile");
this.unresolvedFile = unresolvedFile;
this.usingScope = currentUsingScope ?? unresolvedFile.RootUsingScope;
this.currentTypeDefinition = currentTypeDefinition;
}
public CSharpUnresolvedFile UnresolvedFile {
get { return unresolvedFile; }
}
DomRegion MakeRegion(TextLocation start, TextLocation end)
{
return new DomRegion(unresolvedFile.FileName, start.Line, start.Column, end.Line, end.Column);
}
DomRegion MakeRegion(AstNode node)
{
if (node == null || node.IsNull)
return DomRegion.Empty;
else
return MakeRegion(GetStartLocationAfterAttributes(node), node.EndLocation);
}
internal static TextLocation GetStartLocationAfterAttributes(AstNode node)
{
AstNode child = node.FirstChild;
// Skip attributes and comments between attributes for the purpose of
// getting a declaration's region.
while (child != null && (child is AttributeSection || child.NodeType == NodeType.Whitespace))
child = child.NextSibling;
return (child ?? node).StartLocation;
}
DomRegion MakeBraceRegion(AstNode node)
{
if (node == null || node.IsNull)
return DomRegion.Empty;
else
return MakeRegion(node.GetChildByRole(Roles.LBrace).StartLocation,
node.GetChildByRole(Roles.RBrace).EndLocation);
}
#region Compilation Unit
public override IUnresolvedEntity VisitSyntaxTree (SyntaxTree unit)
{
unresolvedFile.Errors = unit.Errors;
return base.VisitSyntaxTree (unit);
}
#endregion
#region Using Declarations
public override IUnresolvedEntity VisitExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration)
{
usingScope.ExternAliases.Add(externAliasDeclaration.Name);
return null;
}
public override IUnresolvedEntity VisitUsingDeclaration(UsingDeclaration usingDeclaration)
{
TypeOrNamespaceReference u = usingDeclaration.Import.ToTypeReference(NameLookupMode.TypeInUsingDeclaration) as TypeOrNamespaceReference;
if (u != null) {
if (interningProvider != null)
u = interningProvider.Intern(u);
usingScope.Usings.Add(u);
}
return null;
}
public override IUnresolvedEntity VisitUsingAliasDeclaration(UsingAliasDeclaration usingDeclaration)
{
TypeOrNamespaceReference u = usingDeclaration.Import.ToTypeReference(NameLookupMode.TypeInUsingDeclaration) as TypeOrNamespaceReference;
if (u != null) {
if (interningProvider != null)
u = interningProvider.Intern(u);
usingScope.UsingAliases.Add(new KeyValuePair<string, TypeOrNamespaceReference>(usingDeclaration.Alias, u));
}
return null;
}
#endregion
#region Namespace Declaration
public override IUnresolvedEntity VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration)
{
DomRegion region = MakeRegion(namespaceDeclaration);
UsingScope previousUsingScope = usingScope;
foreach (Identifier ident in namespaceDeclaration.Identifiers) {
usingScope = new UsingScope(usingScope, ident.Name);
usingScope.Region = region;
}
base.VisitNamespaceDeclaration(namespaceDeclaration);
unresolvedFile.UsingScopes.Add(usingScope); // add after visiting children so that nested scopes come first
usingScope = previousUsingScope;
return null;
}
#endregion
#region Type Definitions
CSharpUnresolvedTypeDefinition CreateTypeDefinition(string name)
{
CSharpUnresolvedTypeDefinition newType;
if (currentTypeDefinition != null) {
newType = new CSharpUnresolvedTypeDefinition(currentTypeDefinition, name);
foreach (var typeParameter in currentTypeDefinition.TypeParameters)
newType.TypeParameters.Add(typeParameter);
currentTypeDefinition.NestedTypes.Add(newType);
} else {
newType = new CSharpUnresolvedTypeDefinition(usingScope, name);
unresolvedFile.TopLevelTypeDefinitions.Add(newType);
}
newType.UnresolvedFile = unresolvedFile;
newType.HasExtensionMethods = false; // gets set to true when an extension method is added
return newType;
}
public override IUnresolvedEntity VisitTypeDeclaration(TypeDeclaration typeDeclaration)
{
var td = currentTypeDefinition = CreateTypeDefinition(typeDeclaration.Name);
td.Region = MakeRegion(typeDeclaration);
td.BodyRegion = MakeBraceRegion(typeDeclaration);
AddXmlDocumentation(td, typeDeclaration);
ApplyModifiers(td, typeDeclaration.Modifiers);
switch (typeDeclaration.ClassType) {
case ClassType.Enum:
td.Kind = TypeKind.Enum;
break;
case ClassType.Interface:
td.Kind = TypeKind.Interface;
td.IsAbstract = true; // interfaces are implicitly abstract
break;
case ClassType.Struct:
td.Kind = TypeKind.Struct;
td.IsSealed = true; // enums/structs are implicitly sealed
break;
}
ConvertAttributes(td.Attributes, typeDeclaration.Attributes);
ConvertTypeParameters(td.TypeParameters, typeDeclaration.TypeParameters, typeDeclaration.Constraints, EntityType.TypeDefinition);
foreach (AstType baseType in typeDeclaration.BaseTypes) {
td.BaseTypes.Add(baseType.ToTypeReference(NameLookupMode.BaseTypeReference));
}
foreach (EntityDeclaration member in typeDeclaration.Members) {
member.AcceptVisitor(this);
}
currentTypeDefinition = (CSharpUnresolvedTypeDefinition)currentTypeDefinition.DeclaringTypeDefinition;
if (interningProvider != null) {
td.ApplyInterningProvider(interningProvider);
}
return td;
}
public override IUnresolvedEntity VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration)
{
var td = currentTypeDefinition = CreateTypeDefinition(delegateDeclaration.Name);
td.Kind = TypeKind.Delegate;
td.Region = MakeRegion(delegateDeclaration);
td.BaseTypes.Add(KnownTypeReference.MulticastDelegate);
AddXmlDocumentation(td, delegateDeclaration);
ApplyModifiers(td, delegateDeclaration.Modifiers);
td.IsSealed = true; // delegates are implicitly sealed
ConvertTypeParameters(td.TypeParameters, delegateDeclaration.TypeParameters, delegateDeclaration.Constraints, EntityType.TypeDefinition);
ITypeReference returnType = delegateDeclaration.ReturnType.ToTypeReference();
List<IUnresolvedParameter> parameters = new List<IUnresolvedParameter>();
ConvertParameters(parameters, delegateDeclaration.Parameters);
AddDefaultMethodsToDelegate(td, returnType, parameters);
foreach (AttributeSection section in delegateDeclaration.Attributes) {
if (section.AttributeTarget == "return") {
List<IUnresolvedAttribute> returnTypeAttributes = new List<IUnresolvedAttribute>();
ConvertAttributes(returnTypeAttributes, section);
IUnresolvedMethod invokeMethod = (IUnresolvedMethod)td.Members.Single(m => m.Name == "Invoke");
IUnresolvedMethod endInvokeMethod = (IUnresolvedMethod)td.Members.Single(m => m.Name == "EndInvoke");
foreach (IUnresolvedAttribute attr in returnTypeAttributes) {
invokeMethod.ReturnTypeAttributes.Add(attr);
endInvokeMethod.ReturnTypeAttributes.Add(attr);
}
} else {
ConvertAttributes(td.Attributes, section);
}
}
currentTypeDefinition = (CSharpUnresolvedTypeDefinition)currentTypeDefinition.DeclaringTypeDefinition;
if (interningProvider != null) {
td.ApplyInterningProvider(interningProvider);
}
return td;
}
static readonly IUnresolvedParameter delegateObjectParameter = MakeParameter(KnownTypeReference.Object, "object");
static readonly IUnresolvedParameter delegateIntPtrMethodParameter = MakeParameter(KnownTypeReference.IntPtr, "method");
static readonly IUnresolvedParameter delegateAsyncCallbackParameter = MakeParameter(typeof(AsyncCallback).ToTypeReference(), "callback");
static readonly IUnresolvedParameter delegateResultParameter = MakeParameter(typeof(IAsyncResult).ToTypeReference(), "result");
static IUnresolvedParameter MakeParameter(ITypeReference type, string name)
{
DefaultUnresolvedParameter p = new DefaultUnresolvedParameter(type, name);
p.Freeze();
return p;
}
/// <summary>
/// Adds the 'Invoke', 'BeginInvoke', 'EndInvoke' methods, and a constructor, to the <paramref name="delegateType"/>.
/// </summary>
public static void AddDefaultMethodsToDelegate(DefaultUnresolvedTypeDefinition delegateType, ITypeReference returnType, IEnumerable<IUnresolvedParameter> parameters)
{
if (delegateType == null)
throw new ArgumentNullException("delegateType");
if (returnType == null)
throw new ArgumentNullException("returnType");
if (parameters == null)
throw new ArgumentNullException("parameters");
DomRegion region = delegateType.Region;
region = new DomRegion(region.FileName, region.BeginLine, region.BeginColumn); // remove end position
DefaultUnresolvedMethod invoke = new DefaultUnresolvedMethod(delegateType, "Invoke");
invoke.Accessibility = Accessibility.Public;
invoke.IsSynthetic = true;
foreach (var p in parameters)
invoke.Parameters.Add(p);
invoke.ReturnType = returnType;
invoke.Region = region;
delegateType.Members.Add(invoke);
DefaultUnresolvedMethod beginInvoke = new DefaultUnresolvedMethod(delegateType, "BeginInvoke");
beginInvoke.Accessibility = Accessibility.Public;
beginInvoke.IsSynthetic = true;
foreach (var p in parameters)
beginInvoke.Parameters.Add(p);
beginInvoke.Parameters.Add(delegateAsyncCallbackParameter);
beginInvoke.Parameters.Add(delegateObjectParameter);
beginInvoke.ReturnType = delegateResultParameter.Type;
beginInvoke.Region = region;
delegateType.Members.Add(beginInvoke);
DefaultUnresolvedMethod endInvoke = new DefaultUnresolvedMethod(delegateType, "EndInvoke");
endInvoke.Accessibility = Accessibility.Public;
endInvoke.IsSynthetic = true;
endInvoke.Parameters.Add(delegateResultParameter);
endInvoke.ReturnType = invoke.ReturnType;
endInvoke.Region = region;
delegateType.Members.Add(endInvoke);
DefaultUnresolvedMethod ctor = new DefaultUnresolvedMethod(delegateType, ".ctor");
ctor.EntityType = EntityType.Constructor;
ctor.Accessibility = Accessibility.Public;
ctor.IsSynthetic = true;
ctor.Parameters.Add(delegateObjectParameter);
ctor.Parameters.Add(delegateIntPtrMethodParameter);
ctor.ReturnType = delegateType;
ctor.Region = region;
delegateType.Members.Add(ctor);
}
#endregion
#region Fields
public override IUnresolvedEntity VisitFieldDeclaration(FieldDeclaration fieldDeclaration)
{
bool isSingleField = fieldDeclaration.Variables.Count == 1;
Modifiers modifiers = fieldDeclaration.Modifiers;
DefaultUnresolvedField field = null;
foreach (VariableInitializer vi in fieldDeclaration.Variables) {
field = new DefaultUnresolvedField(currentTypeDefinition, vi.Name);
field.Region = isSingleField ? MakeRegion(fieldDeclaration) : MakeRegion(vi);
field.BodyRegion = MakeRegion(vi);
ConvertAttributes(field.Attributes, fieldDeclaration.Attributes);
AddXmlDocumentation(field, fieldDeclaration);
ApplyModifiers(field, modifiers);
field.IsVolatile = (modifiers & Modifiers.Volatile) != 0;
field.IsReadOnly = (modifiers & Modifiers.Readonly) != 0;
field.ReturnType = fieldDeclaration.ReturnType.ToTypeReference();
if ((modifiers & Modifiers.Const) != 0) {
field.ConstantValue = ConvertConstantValue(field.ReturnType, vi.Initializer);
field.IsStatic = true;
}
currentTypeDefinition.Members.Add(field);
if (interningProvider != null) {
field.ApplyInterningProvider(interningProvider);
}
}
return isSingleField ? field : null;
}
public override IUnresolvedEntity VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration)
{
// TODO: add support for fixed fields
return base.VisitFixedFieldDeclaration(fixedFieldDeclaration);
}
public override IUnresolvedEntity VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration)
{
DefaultUnresolvedField field = new DefaultUnresolvedField(currentTypeDefinition, enumMemberDeclaration.Name);
field.Region = field.BodyRegion = MakeRegion(enumMemberDeclaration);
ConvertAttributes(field.Attributes, enumMemberDeclaration.Attributes);
AddXmlDocumentation(field, enumMemberDeclaration);
if (currentTypeDefinition.TypeParameters.Count == 0) {
field.ReturnType = currentTypeDefinition;
} else {
ITypeReference[] typeArgs = new ITypeReference[currentTypeDefinition.TypeParameters.Count];
for (int i = 0; i < typeArgs.Length; i++) {
typeArgs[i] = new TypeParameterReference(EntityType.TypeDefinition, i);
}
field.ReturnType = new ParameterizedTypeReference(currentTypeDefinition, typeArgs);
}
field.Accessibility = Accessibility.Public;
field.IsStatic = true;
if (!enumMemberDeclaration.Initializer.IsNull) {
field.ConstantValue = ConvertConstantValue(field.ReturnType, enumMemberDeclaration.Initializer);
} else {
DefaultUnresolvedField prevField = currentTypeDefinition.Members.LastOrDefault() as DefaultUnresolvedField;
if (prevField == null || prevField.ConstantValue == null) {
field.ConstantValue = ConvertConstantValue(field.ReturnType, new PrimitiveExpression(0));
} else {
field.ConstantValue = new IncrementConstantValue(prevField.ConstantValue);
}
}
currentTypeDefinition.Members.Add(field);
if (interningProvider != null) {
field.ApplyInterningProvider(interningProvider);
}
return field;
}
#endregion
#region Methods
public override IUnresolvedEntity VisitMethodDeclaration(MethodDeclaration methodDeclaration)
{
DefaultUnresolvedMethod m = new DefaultUnresolvedMethod(currentTypeDefinition, methodDeclaration.Name);
currentMethod = m; // required for resolving type parameters
m.Region = MakeRegion(methodDeclaration);
m.BodyRegion = MakeRegion(methodDeclaration.Body);
AddXmlDocumentation(m, methodDeclaration);
if (InheritsConstraints(methodDeclaration) && methodDeclaration.Constraints.Count == 0) {
int index = 0;
foreach (TypeParameterDeclaration tpDecl in methodDeclaration.TypeParameters) {
var tp = new MethodTypeParameterWithInheritedConstraints(index++, tpDecl.Name);
tp.Region = MakeRegion(tpDecl);
ConvertAttributes(tp.Attributes, tpDecl.Attributes);
tp.Variance = tpDecl.Variance;
m.TypeParameters.Add(tp);
}
} else {
ConvertTypeParameters(m.TypeParameters, methodDeclaration.TypeParameters, methodDeclaration.Constraints, EntityType.Method);
}
m.ReturnType = methodDeclaration.ReturnType.ToTypeReference();
ConvertAttributes(m.Attributes, methodDeclaration.Attributes.Where(s => s.AttributeTarget != "return"));
ConvertAttributes(m.ReturnTypeAttributes, methodDeclaration.Attributes.Where(s => s.AttributeTarget == "return"));
ApplyModifiers(m, methodDeclaration.Modifiers);
if (methodDeclaration.IsExtensionMethod) {
m.IsExtensionMethod = true;
currentTypeDefinition.HasExtensionMethods = true;
}
m.IsPartial = methodDeclaration.HasModifier(Modifiers.Partial);
m.HasBody = !methodDeclaration.Body.IsNull;
ConvertParameters(m.Parameters, methodDeclaration.Parameters);
if (!methodDeclaration.PrivateImplementationType.IsNull) {
m.Accessibility = Accessibility.None;
m.IsExplicitInterfaceImplementation = true;
m.ExplicitInterfaceImplementations.Add(new DefaultMemberReference(
m.EntityType, methodDeclaration.PrivateImplementationType.ToTypeReference(), m.Name,
m.TypeParameters.Count, GetParameterTypes(m.Parameters)));
}
currentTypeDefinition.Members.Add(m);
currentMethod = null;
if (interningProvider != null) {
m.ApplyInterningProvider(interningProvider);
}
return m;
}
IList<ITypeReference> GetParameterTypes(IList<IUnresolvedParameter> parameters)
{
if (parameters.Count == 0)
return EmptyList<ITypeReference>.Instance;
ITypeReference[] types = new ITypeReference[parameters.Count];
for (int i = 0; i < types.Length; i++) {
types[i] = parameters[i].Type;
}
return types;
}
bool InheritsConstraints(MethodDeclaration methodDeclaration)
{
// overrides and explicit interface implementations inherit constraints
if ((methodDeclaration.Modifiers & Modifiers.Override) == Modifiers.Override)
return true;
return !methodDeclaration.PrivateImplementationType.IsNull;
}
void ConvertTypeParameters(IList<IUnresolvedTypeParameter> output, AstNodeCollection<TypeParameterDeclaration> typeParameters,
AstNodeCollection<Constraint> constraints, EntityType ownerType)
{
// output might be non-empty when type parameters were copied from an outer class
int index = output.Count;
List<DefaultUnresolvedTypeParameter> list = new List<DefaultUnresolvedTypeParameter>();
foreach (TypeParameterDeclaration tpDecl in typeParameters) {
DefaultUnresolvedTypeParameter tp = new DefaultUnresolvedTypeParameter(ownerType, index++, tpDecl.Name);
tp.Region = MakeRegion(tpDecl);
ConvertAttributes(tp.Attributes, tpDecl.Attributes);
tp.Variance = tpDecl.Variance;
list.Add(tp);
output.Add(tp); // tp must be added to list here so that it can be referenced by constraints
}
foreach (Constraint c in constraints) {
foreach (var tp in list) {
if (tp.Name == c.TypeParameter.Identifier) {
foreach (AstType type in c.BaseTypes) {
PrimitiveType primType = type as PrimitiveType;
if (primType != null) {
if (primType.Keyword == "new") {
tp.HasDefaultConstructorConstraint = true;
continue;
} else if (primType.Keyword == "class") {
tp.HasReferenceTypeConstraint = true;
continue;
} else if (primType.Keyword == "struct") {
tp.HasValueTypeConstraint = true;
continue;
}
}
tp.Constraints.Add(type.ToTypeReference());
}
break;
}
}
}
}
IMemberReference ConvertInterfaceImplementation(AstType interfaceType, AbstractUnresolvedMember unresolvedMember)
{
ITypeReference interfaceTypeReference = interfaceType.ToTypeReference();
int typeParameterCount = 0;
IList<ITypeReference> parameterTypes = null;
if (unresolvedMember.EntityType == EntityType.Method) {
typeParameterCount = ((IUnresolvedMethod)unresolvedMember).TypeParameters.Count;
}
IUnresolvedParameterizedMember parameterizedMember = unresolvedMember as IUnresolvedParameterizedMember;
if (parameterizedMember != null) {
parameterTypes = new ITypeReference[parameterizedMember.Parameters.Count];
for (int i = 0; i < parameterTypes.Count; i++) {
parameterTypes[i] = parameterizedMember.Parameters[i].Type;
}
}
return new DefaultMemberReference(unresolvedMember.EntityType, interfaceTypeReference, unresolvedMember.Name, typeParameterCount, parameterTypes);
}
#endregion
#region Operators
public override IUnresolvedEntity VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration)
{
DefaultUnresolvedMethod m = new DefaultUnresolvedMethod(currentTypeDefinition, operatorDeclaration.Name);
m.EntityType = EntityType.Operator;
m.Region = MakeRegion(operatorDeclaration);
m.BodyRegion = MakeRegion(operatorDeclaration.Body);
AddXmlDocumentation(m, operatorDeclaration);
m.ReturnType = operatorDeclaration.ReturnType.ToTypeReference();
ConvertAttributes(m.Attributes, operatorDeclaration.Attributes.Where(s => s.AttributeTarget != "return"));
ConvertAttributes(m.ReturnTypeAttributes, operatorDeclaration.Attributes.Where(s => s.AttributeTarget == "return"));
ApplyModifiers(m, operatorDeclaration.Modifiers);
m.HasBody = !operatorDeclaration.Body.IsNull;
ConvertParameters(m.Parameters, operatorDeclaration.Parameters);
currentTypeDefinition.Members.Add(m);
if (interningProvider != null) {
m.ApplyInterningProvider(interningProvider);
}
return m;
}
#endregion
#region Constructors
public override IUnresolvedEntity VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration)
{
Modifiers modifiers = constructorDeclaration.Modifiers;
bool isStatic = (modifiers & Modifiers.Static) != 0;
DefaultUnresolvedMethod ctor = new DefaultUnresolvedMethod(currentTypeDefinition, isStatic ? ".cctor" : ".ctor");
ctor.EntityType = EntityType.Constructor;
ctor.Region = MakeRegion(constructorDeclaration);
if (!constructorDeclaration.Initializer.IsNull) {
ctor.BodyRegion = MakeRegion(constructorDeclaration.Initializer.StartLocation, constructorDeclaration.EndLocation);
} else {
ctor.BodyRegion = MakeRegion(constructorDeclaration.Body);
}
ctor.ReturnType = KnownTypeReference.Void;
ConvertAttributes(ctor.Attributes, constructorDeclaration.Attributes);
ConvertParameters(ctor.Parameters, constructorDeclaration.Parameters);
AddXmlDocumentation(ctor, constructorDeclaration);
ctor.HasBody = !constructorDeclaration.Body.IsNull;
if (isStatic)
ctor.IsStatic = true;
else
ApplyModifiers(ctor, modifiers);
currentTypeDefinition.Members.Add(ctor);
if (interningProvider != null) {
ctor.ApplyInterningProvider(interningProvider);
}
return ctor;
}
#endregion
#region Destructors
public override IUnresolvedEntity VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration)
{
DefaultUnresolvedMethod dtor = new DefaultUnresolvedMethod(currentTypeDefinition, "Finalize");
dtor.EntityType = EntityType.Destructor;
dtor.Region = MakeRegion(destructorDeclaration);
dtor.BodyRegion = MakeRegion(destructorDeclaration.Body);
dtor.Accessibility = Accessibility.Protected;
dtor.IsOverride = true;
dtor.ReturnType = KnownTypeReference.Void;
dtor.HasBody = !destructorDeclaration.Body.IsNull;
ConvertAttributes(dtor.Attributes, destructorDeclaration.Attributes);
AddXmlDocumentation(dtor, destructorDeclaration);
currentTypeDefinition.Members.Add(dtor);
if (interningProvider != null) {
dtor.ApplyInterningProvider(interningProvider);
}
return dtor;
}
#endregion
#region Properties / Indexers
public override IUnresolvedEntity VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration)
{
DefaultUnresolvedProperty p = new DefaultUnresolvedProperty(currentTypeDefinition, propertyDeclaration.Name);
p.Region = MakeRegion(propertyDeclaration);
p.BodyRegion = MakeBraceRegion(propertyDeclaration);
ApplyModifiers(p, propertyDeclaration.Modifiers);
p.ReturnType = propertyDeclaration.ReturnType.ToTypeReference();
ConvertAttributes(p.Attributes, propertyDeclaration.Attributes);
AddXmlDocumentation(p, propertyDeclaration);
if (!propertyDeclaration.PrivateImplementationType.IsNull) {
p.Accessibility = Accessibility.None;
p.IsExplicitInterfaceImplementation = true;
p.ExplicitInterfaceImplementations.Add(new DefaultMemberReference(
p.EntityType, propertyDeclaration.PrivateImplementationType.ToTypeReference(), p.Name));
}
bool isExtern = propertyDeclaration.HasModifier(Modifiers.Extern);
p.Getter = ConvertAccessor(propertyDeclaration.Getter, p, "get_", isExtern);
p.Setter = ConvertAccessor(propertyDeclaration.Setter, p, "set_", isExtern);
currentTypeDefinition.Members.Add(p);
if (interningProvider != null) {
p.ApplyInterningProvider(interningProvider);
}
return p;
}
public override IUnresolvedEntity VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration)
{
DefaultUnresolvedProperty p = new DefaultUnresolvedProperty(currentTypeDefinition, "Item");
p.EntityType = EntityType.Indexer;
p.Region = MakeRegion(indexerDeclaration);
p.BodyRegion = MakeBraceRegion(indexerDeclaration);
ApplyModifiers(p, indexerDeclaration.Modifiers);
p.ReturnType = indexerDeclaration.ReturnType.ToTypeReference();
ConvertAttributes(p.Attributes, indexerDeclaration.Attributes);
AddXmlDocumentation(p, indexerDeclaration);
ConvertParameters(p.Parameters, indexerDeclaration.Parameters);
if (!indexerDeclaration.PrivateImplementationType.IsNull) {
p.Accessibility = Accessibility.None;
p.IsExplicitInterfaceImplementation = true;
p.ExplicitInterfaceImplementations.Add(new DefaultMemberReference(
p.EntityType, indexerDeclaration.PrivateImplementationType.ToTypeReference(), p.Name, 0, GetParameterTypes(p.Parameters)));
}
bool isExtern = indexerDeclaration.HasModifier(Modifiers.Extern);
p.Getter = ConvertAccessor(indexerDeclaration.Getter, p, "get_", isExtern);
p.Setter = ConvertAccessor(indexerDeclaration.Setter, p, "set_", isExtern);
currentTypeDefinition.Members.Add(p);
if (interningProvider != null) {
p.ApplyInterningProvider(interningProvider);
}
return p;
}
DefaultUnresolvedMethod ConvertAccessor(Accessor accessor, IUnresolvedMember p, string prefix, bool memberIsExtern)
{
if (accessor.IsNull)
return null;
var a = new DefaultUnresolvedMethod(currentTypeDefinition, prefix + p.Name);
a.EntityType = EntityType.Accessor;
a.AccessorOwner = p;
a.Accessibility = GetAccessibility(accessor.Modifiers) ?? p.Accessibility;
a.IsAbstract = p.IsAbstract;
a.IsOverride = p.IsOverride;
a.IsSealed = p.IsSealed;
a.IsStatic = p.IsStatic;
a.IsSynthetic = p.IsSynthetic;
a.IsVirtual = p.IsVirtual;
a.Region = MakeRegion(accessor);
a.BodyRegion = MakeRegion(accessor.Body);
// An accessor has no body if all both are true:
// a) there's no body in the code
// b) the member is either abstract or extern
a.HasBody = !(accessor.Body.IsNull && (p.IsAbstract || memberIsExtern));
if (p.EntityType == EntityType.Indexer) {
foreach (var indexerParam in ((IUnresolvedProperty)p).Parameters)
a.Parameters.Add(indexerParam);
}
DefaultUnresolvedParameter param = null;
if (accessor.Role == PropertyDeclaration.GetterRole) {
a.ReturnType = p.ReturnType;
} else {
param = new DefaultUnresolvedParameter(p.ReturnType, "value");
a.Parameters.Add(param);
a.ReturnType = KnownTypeReference.Void;
}
foreach (AttributeSection section in accessor.Attributes) {
if (section.AttributeTarget == "return") {
ConvertAttributes(a.ReturnTypeAttributes, section);
} else if (param != null && section.AttributeTarget == "param") {
ConvertAttributes(param.Attributes, section);
} else {
ConvertAttributes(a.Attributes, section);
}
}
if (p.IsExplicitInterfaceImplementation) {
a.IsExplicitInterfaceImplementation = true;
Debug.Assert(p.ExplicitInterfaceImplementations.Count == 1);
a.ExplicitInterfaceImplementations.Add(new DefaultMemberReference(
EntityType.Accessor,
p.ExplicitInterfaceImplementations[0].DeclaringTypeReference,
a.Name, 0, GetParameterTypes(a.Parameters)
));
}
return a;
}
#endregion
#region Events
public override IUnresolvedEntity VisitEventDeclaration(EventDeclaration eventDeclaration)
{
bool isSingleEvent = eventDeclaration.Variables.Count == 1;
Modifiers modifiers = eventDeclaration.Modifiers;
DefaultUnresolvedEvent ev = null;
foreach (VariableInitializer vi in eventDeclaration.Variables) {
ev = new DefaultUnresolvedEvent(currentTypeDefinition, vi.Name);
ev.Region = isSingleEvent ? MakeRegion(eventDeclaration) : MakeRegion(vi);
ev.BodyRegion = MakeRegion(vi);
ApplyModifiers(ev, modifiers);
AddXmlDocumentation(ev, eventDeclaration);
ev.ReturnType = eventDeclaration.ReturnType.ToTypeReference();
var valueParameter = new DefaultUnresolvedParameter(ev.ReturnType, "value");
ev.AddAccessor = CreateDefaultEventAccessor(ev, "add_" + ev.Name, valueParameter);
ev.RemoveAccessor = CreateDefaultEventAccessor(ev, "remove_" + ev.Name, valueParameter);
foreach (AttributeSection section in eventDeclaration.Attributes) {
if (section.AttributeTarget == "method") {
foreach (var attrNode in section.Attributes) {
IUnresolvedAttribute attr = ConvertAttribute(attrNode);
ev.AddAccessor.Attributes.Add(attr);
ev.RemoveAccessor.Attributes.Add(attr);
}
} else if (section.AttributeTarget != "field") {
ConvertAttributes(ev.Attributes, section);
}
}
currentTypeDefinition.Members.Add(ev);
if (interningProvider != null) {
ev.ApplyInterningProvider(interningProvider);
}
}
return isSingleEvent ? ev : null;
}
DefaultUnresolvedMethod CreateDefaultEventAccessor(IUnresolvedEvent ev, string name, IUnresolvedParameter valueParameter)
{
var a = new DefaultUnresolvedMethod(currentTypeDefinition, name);
a.EntityType = EntityType.Accessor;
a.AccessorOwner = ev;
a.Region = ev.BodyRegion;
a.BodyRegion = ev.BodyRegion;
a.Accessibility = ev.Accessibility;
a.IsAbstract = ev.IsAbstract;
a.IsOverride = ev.IsOverride;
a.IsSealed = ev.IsSealed;
a.IsStatic = ev.IsStatic;
a.IsSynthetic = ev.IsSynthetic;
a.IsVirtual = ev.IsVirtual;
a.HasBody = true;
a.ReturnType = KnownTypeReference.Void;
a.Parameters.Add(valueParameter);
return a;
}
public override IUnresolvedEntity VisitCustomEventDeclaration(CustomEventDeclaration eventDeclaration)
{
DefaultUnresolvedEvent e = new DefaultUnresolvedEvent(currentTypeDefinition, eventDeclaration.Name);
e.Region = MakeRegion(eventDeclaration);
e.BodyRegion = MakeBraceRegion(eventDeclaration);
ApplyModifiers(e, eventDeclaration.Modifiers);
e.ReturnType = eventDeclaration.ReturnType.ToTypeReference();
ConvertAttributes(e.Attributes, eventDeclaration.Attributes);
AddXmlDocumentation(e, eventDeclaration);
if (!eventDeclaration.PrivateImplementationType.IsNull) {
e.Accessibility = Accessibility.None;
e.IsExplicitInterfaceImplementation = true;
e.ExplicitInterfaceImplementations.Add(new DefaultMemberReference(
e.EntityType, eventDeclaration.PrivateImplementationType.ToTypeReference(), e.Name));
}
// custom events can't be extern; the non-custom event syntax must be used for extern events
e.AddAccessor = ConvertAccessor(eventDeclaration.AddAccessor, e, "add_", false);
e.RemoveAccessor = ConvertAccessor(eventDeclaration.RemoveAccessor, e, "remove_", false);
currentTypeDefinition.Members.Add(e);
if (interningProvider != null) {
e.ApplyInterningProvider(interningProvider);
}
return e;
}
#endregion
#region Modifiers
static void ApplyModifiers(DefaultUnresolvedTypeDefinition td, Modifiers modifiers)
{
td.Accessibility = GetAccessibility(modifiers) ?? (td.DeclaringTypeDefinition != null ? Accessibility.Private : Accessibility.Internal);
td.IsAbstract = (modifiers & (Modifiers.Abstract | Modifiers.Static)) != 0;
td.IsSealed = (modifiers & (Modifiers.Sealed | Modifiers.Static)) != 0;
td.IsShadowing = (modifiers & Modifiers.New) != 0;
}
static void ApplyModifiers(AbstractUnresolvedMember m, Modifiers modifiers)
{
// members from interfaces are always Public+Abstract.
if (m.DeclaringTypeDefinition.Kind == TypeKind.Interface) {
m.Accessibility = Accessibility.Public;
m.IsAbstract = true;
return;
}
m.Accessibility = GetAccessibility(modifiers) ?? Accessibility.Private;
m.IsAbstract = (modifiers & Modifiers.Abstract) != 0;
m.IsOverride = (modifiers & Modifiers.Override) != 0;
m.IsSealed = (modifiers & Modifiers.Sealed) != 0;
m.IsShadowing = (modifiers & Modifiers.New) != 0;
m.IsStatic = (modifiers & Modifiers.Static) != 0;
m.IsVirtual = (modifiers & Modifiers.Virtual) != 0;
}
static Accessibility? GetAccessibility(Modifiers modifiers)
{
switch (modifiers & Modifiers.VisibilityMask) {
case Modifiers.Private:
return Accessibility.Private;
case Modifiers.Internal:
return Accessibility.Internal;
case Modifiers.Protected | Modifiers.Internal:
return Accessibility.ProtectedOrInternal;
case Modifiers.Protected:
return Accessibility.Protected;
case Modifiers.Public:
return Accessibility.Public;
default:
return null;
}
}
#endregion
#region Attributes
public override IUnresolvedEntity VisitAttributeSection(AttributeSection attributeSection)
{
// non-assembly attributes are handled by their parent entity
if (attributeSection.AttributeTarget == "assembly") {
ConvertAttributes(unresolvedFile.AssemblyAttributes, attributeSection);
} else if (attributeSection.AttributeTarget == "module") {
ConvertAttributes(unresolvedFile.ModuleAttributes, attributeSection);
}
return null;
}
void ConvertAttributes(IList<IUnresolvedAttribute> outputList, IEnumerable<AttributeSection> attributes)
{
foreach (AttributeSection section in attributes) {
ConvertAttributes(outputList, section);
}
}
void ConvertAttributes(IList<IUnresolvedAttribute> outputList, AttributeSection attributeSection)
{
foreach (CSharp.Attribute attr in attributeSection.Attributes) {
outputList.Add(ConvertAttribute(attr));
}
}
internal static ITypeReference ConvertAttributeType(AstType type)
{
ITypeReference tr = type.ToTypeReference();
if (!type.GetChildByRole(Roles.Identifier).IsVerbatim) {
// Try to add "Attribute" suffix, but only if the identifier
// (=last identifier in fully qualified name) isn't a verbatim identifier.
SimpleTypeOrNamespaceReference st = tr as SimpleTypeOrNamespaceReference;
MemberTypeOrNamespaceReference mt = tr as MemberTypeOrNamespaceReference;
if (st != null)
return new AttributeTypeReference(st, st.AddSuffix("Attribute"));
else if (mt != null)
return new AttributeTypeReference(mt, mt.AddSuffix("Attribute"));
}
return tr;
}
CSharpAttribute ConvertAttribute(CSharp.Attribute attr)
{
DomRegion region = MakeRegion(attr);
ITypeReference type = ConvertAttributeType(attr.Type);
List<IConstantValue> positionalArguments = null;
List<KeyValuePair<string, IConstantValue>> namedCtorArguments = null;
List<KeyValuePair<string, IConstantValue>> namedArguments = null;
foreach (Expression expr in attr.Arguments) {
NamedArgumentExpression nae = expr as NamedArgumentExpression;
if (nae != null) {
if (namedCtorArguments == null)
namedCtorArguments = new List<KeyValuePair<string, IConstantValue>>();
namedCtorArguments.Add(new KeyValuePair<string, IConstantValue>(nae.Name, ConvertAttributeArgument(nae.Expression)));
} else {
NamedExpression namedExpression = expr as NamedExpression;
if (namedExpression != null) {
string name = namedExpression.Name;
if (namedArguments == null)
namedArguments = new List<KeyValuePair<string, IConstantValue>>();
namedArguments.Add(new KeyValuePair<string, IConstantValue>(name, ConvertAttributeArgument(namedExpression.Expression)));
} else {
if (positionalArguments == null)
positionalArguments = new List<IConstantValue>();
positionalArguments.Add(ConvertAttributeArgument(expr));
}
}
}
return new CSharpAttribute(type, region, positionalArguments, namedCtorArguments, namedArguments);
}
#endregion
#region Types
[Obsolete("Use AstType.ToTypeReference() instead.")]
public static ITypeReference ConvertType(AstType type, NameLookupMode lookupMode = NameLookupMode.Type)
{
return type.ToTypeReference(lookupMode);
}
#endregion
#region Constant Values
IConstantValue ConvertConstantValue(ITypeReference targetType, AstNode expression)
{
return ConvertConstantValue(targetType, expression, currentTypeDefinition, currentMethod, usingScope);
}
internal static IConstantValue ConvertConstantValue(
ITypeReference targetType, AstNode expression,
IUnresolvedTypeDefinition parentTypeDefinition, IUnresolvedMethod parentMethodDefinition, UsingScope parentUsingScope)
{
ConstantValueBuilder b = new ConstantValueBuilder(false);
ConstantExpression c = expression.AcceptVisitor(b);
if (c == null)
return new ErrorConstantValue(targetType);
PrimitiveConstantExpression pc = c as PrimitiveConstantExpression;
if (pc != null && pc.Type == targetType) {
// Save memory by directly using a SimpleConstantValue.
return new SimpleConstantValue(targetType, pc.Value);
}
// cast to the desired type
return new ConstantCast(targetType, c);
}
IConstantValue ConvertAttributeArgument(Expression expression)
{
ConstantValueBuilder b = new ConstantValueBuilder(true);
return expression.AcceptVisitor(b);
}
sealed class ConstantValueBuilder : DepthFirstAstVisitor<ConstantExpression>
{
readonly bool isAttributeArgument;
public ConstantValueBuilder(bool isAttributeArgument)
{
this.isAttributeArgument = isAttributeArgument;
}
protected override ConstantExpression VisitChildren(AstNode node)
{
return null;
}
public override ConstantExpression VisitNullReferenceExpression(NullReferenceExpression nullReferenceExpression)
{
return new PrimitiveConstantExpression(KnownTypeReference.Object, null);
}
public override ConstantExpression VisitPrimitiveExpression(PrimitiveExpression primitiveExpression)
{
TypeCode typeCode = Type.GetTypeCode(primitiveExpression.Value.GetType());
return new PrimitiveConstantExpression(typeCode.ToTypeReference(), primitiveExpression.Value);
}
IList<ITypeReference> ConvertTypeArguments(AstNodeCollection<AstType> types)
{
int count = types.Count;
if (count == 0)
return null;
ITypeReference[] result = new ITypeReference[count];
int pos = 0;
foreach (AstType type in types) {
result[pos++] = type.ToTypeReference();
}
return result;
}
public override ConstantExpression VisitIdentifierExpression(IdentifierExpression identifierExpression)
{
return new ConstantIdentifierReference(identifierExpression.Identifier, ConvertTypeArguments(identifierExpression.TypeArguments));
}
public override ConstantExpression VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression)
{
TypeReferenceExpression tre = memberReferenceExpression.Target as TypeReferenceExpression;
if (tre != null) {
// handle "int.MaxValue"
return new ConstantMemberReference(
tre.Type.ToTypeReference(),
memberReferenceExpression.MemberName,
ConvertTypeArguments(memberReferenceExpression.TypeArguments));
}
ConstantExpression v = memberReferenceExpression.Target.AcceptVisitor(this);
if (v == null)
return null;
return new ConstantMemberReference(
v, memberReferenceExpression.MemberName,
ConvertTypeArguments(memberReferenceExpression.TypeArguments));
}
public override ConstantExpression VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression)
{
return parenthesizedExpression.Expression.AcceptVisitor(this);
}
public override ConstantExpression VisitCastExpression(CastExpression castExpression)
{
ConstantExpression v = castExpression.Expression.AcceptVisitor(this);
if (v == null)
return null;
return new ConstantCast(castExpression.Type.ToTypeReference(), v);
}
public override ConstantExpression VisitCheckedExpression(CheckedExpression checkedExpression)
{
ConstantExpression v = checkedExpression.Expression.AcceptVisitor(this);
if (v != null)
return new ConstantCheckedExpression(true, v);
else
return null;
}
public override ConstantExpression VisitUncheckedExpression(UncheckedExpression uncheckedExpression)
{
ConstantExpression v = uncheckedExpression.Expression.AcceptVisitor(this);
if (v != null)
return new ConstantCheckedExpression(false, v);
else
return null;
}
public override ConstantExpression VisitDefaultValueExpression(DefaultValueExpression defaultValueExpression)
{
return new ConstantDefaultValue(defaultValueExpression.Type.ToTypeReference());
}
public override ConstantExpression VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression)
{
ConstantExpression v = unaryOperatorExpression.Expression.AcceptVisitor(this);
if (v == null)
return null;
switch (unaryOperatorExpression.Operator) {
case UnaryOperatorType.Not:
case UnaryOperatorType.BitNot:
case UnaryOperatorType.Minus:
case UnaryOperatorType.Plus:
return new ConstantUnaryOperator(unaryOperatorExpression.Operator, v);
default:
return null;
}
}
public override ConstantExpression VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression)
{
ConstantExpression left = binaryOperatorExpression.Left.AcceptVisitor(this);
ConstantExpression right = binaryOperatorExpression.Right.AcceptVisitor(this);
if (left == null || right == null)
return null;
return new ConstantBinaryOperator(left, binaryOperatorExpression.Operator, right);
}
public override ConstantExpression VisitTypeOfExpression(TypeOfExpression typeOfExpression)
{
if (isAttributeArgument) {
return new TypeOfConstantExpression(typeOfExpression.Type.ToTypeReference());
} else {
return null;
}
}
public override ConstantExpression VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression)
{
var initializer = arrayCreateExpression.Initializer;
// Attributes only allow one-dimensional arrays
if (isAttributeArgument && !initializer.IsNull && arrayCreateExpression.Arguments.Count < 2) {
ITypeReference type;
if (arrayCreateExpression.Type.IsNull) {
type = null;
} else {
type = arrayCreateExpression.Type.ToTypeReference();
foreach (var spec in arrayCreateExpression.AdditionalArraySpecifiers.Reverse()) {
type = new ArrayTypeReference(type, spec.Dimensions);
}
}
ConstantExpression[] elements = new ConstantExpression[initializer.Elements.Count];
int pos = 0;
foreach (Expression expr in initializer.Elements) {
ConstantExpression c = expr.AcceptVisitor(this);
if (c == null)
return null;
elements[pos++] = c;
}
return new ConstantArrayCreation(type, elements);
} else {
return null;
}
}
}
#endregion
#region Parameters
void ConvertParameters(IList<IUnresolvedParameter> outputList, IEnumerable<ParameterDeclaration> parameters)
{
foreach (ParameterDeclaration pd in parameters) {
DefaultUnresolvedParameter p = new DefaultUnresolvedParameter(pd.Type.ToTypeReference(), pd.Name);
p.Region = MakeRegion(pd);
ConvertAttributes(p.Attributes, pd.Attributes);
switch (pd.ParameterModifier) {
case ParameterModifier.Ref:
p.IsRef = true;
p.Type = new ByReferenceTypeReference(p.Type);
break;
case ParameterModifier.Out:
p.IsOut = true;
p.Type = new ByReferenceTypeReference(p.Type);
break;
case ParameterModifier.Params:
p.IsParams = true;
break;
}
if (!pd.DefaultExpression.IsNull)
p.DefaultValue = ConvertConstantValue(p.Type, pd.DefaultExpression);
outputList.Add(p);
}
}
internal static IList<ITypeReference> GetParameterTypes(IEnumerable<ParameterDeclaration> parameters)
{
List<ITypeReference> result = new List<ITypeReference>();
foreach (ParameterDeclaration pd in parameters) {
ITypeReference type = pd.Type.ToTypeReference();
if (pd.ParameterModifier == ParameterModifier.Ref || pd.ParameterModifier == ParameterModifier.Out)
type = new ByReferenceTypeReference(type);
result.Add(type);
}
return result;
}
#endregion
#region XML Documentation
void AddXmlDocumentation(IUnresolvedEntity entity, AstNode entityDeclaration)
{
if (this.SkipXmlDocumentation)
return;
List<string> documentation = null;
// traverse AST backwards until the next non-whitespace node
for (AstNode node = entityDeclaration.PrevSibling; node != null && node.NodeType == NodeType.Whitespace; node = node.PrevSibling) {
Comment c = node as Comment;
if (c != null && (c.CommentType == CommentType.Documentation || c.CommentType == CommentType.MultiLineDocumentation)) {
if (documentation == null)
documentation = new List<string>();
if (c.CommentType == CommentType.MultiLineDocumentation) {
documentation.Add(PrepareMultilineDocumentation(c.Content));
} else {
if (c.Content.Length > 0 && c.Content[0] == ' ')
documentation.Add(c.Content.Substring(1));
else
documentation.Add(c.Content);
}
}
}
if (documentation != null) {
documentation.Reverse(); // bring documentation in correct order
unresolvedFile.AddDocumentation(entity, string.Join(Environment.NewLine, documentation));
}
}
string PrepareMultilineDocumentation(string content)
{
StringBuilder b = new StringBuilder();
using (var reader = new StringReader(content)) {
string firstLine = reader.ReadLine();
// Add first line only if it's not empty:
if (!string.IsNullOrWhiteSpace(firstLine)) {
if (firstLine[0] == ' ')
b.Append(firstLine, 1, firstLine.Length - 1);
else
b.Append(firstLine);
}
// Read lines into list:
List<string> lines = new List<string>();
string line;
while ((line = reader.ReadLine()) != null)
lines.Add(line);
// If the last line (the line with '*/' delimiter) is white space only, ignore it.
if (lines.Count > 0 && string.IsNullOrWhiteSpace(lines[lines.Count - 1]))
lines.RemoveAt(lines.Count - 1);
if (lines.Count > 0) {
// Extract pattern from lines[0]: whitespace, asterisk, whitespace
int patternLength = 0;
string secondLine = lines[0];
while (patternLength < secondLine.Length && char.IsWhiteSpace(secondLine[patternLength]))
patternLength++;
if (patternLength < secondLine.Length && secondLine[patternLength] == '*') {
patternLength++;
while (patternLength < secondLine.Length && char.IsWhiteSpace(secondLine[patternLength]))
patternLength++;
} else {
// no asterisk
patternLength = 0;
}
// Now reduce pattern length to the common pattern:
for (int i = 1; i < lines.Count; i++) {
line = lines[i];
if (line.Length < patternLength)
patternLength = line.Length;
for (int j = 0; j < patternLength; j++) {
if (secondLine[j] != line[j])
patternLength = j;
}
}
// Append the lines to the string builder:
for (int i = 0; i < lines.Count; i++) {
if (b.Length > 0 || i > 0)
b.Append(Environment.NewLine);
b.Append(lines[i], patternLength, lines[i].Length - patternLength);
}
}
}
return b.ToString();
}
#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.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.IO
{
// A MemoryStream represents a Stream in memory (i.e, it has no backing store).
// This stream may reduce the need for temporary buffers and files in
// an application.
//
// There are two ways to create a MemoryStream. You can initialize one
// from an unsigned byte array, or you can create an empty one. Empty
// memory streams are resizable, while ones created with a byte array provide
// a stream "view" of the data.
public class MemoryStream : Stream
{
private byte[] _buffer; // Either allocated internally or externally.
private int _origin; // For user-provided arrays, start at this origin
private int _position; // read/write head.
[ContractPublicPropertyName("Length")]
private int _length; // Number of bytes within the memory stream
private int _capacity; // length of usable portion of buffer for stream
// Note that _capacity == _buffer.Length for non-user-provided byte[]'s
private bool _expandable; // User-provided buffers aren't expandable.
private bool _writable; // Can user write to this stream?
private bool _exposable; // Whether the array can be returned to the user.
private bool _isOpen; // Is this stream open or closed?
// <TODO>In V2, if we get support for arrays of more than 2 GB worth of elements,
// consider removing this constraint, or setting it to Int64.MaxValue.</TODO>
private const int MemStreamMaxLength = int.MaxValue;
public MemoryStream()
: this(0)
{
}
public MemoryStream(int capacity)
{
if (capacity < 0)
{
throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NegativeCapacity);
}
_buffer = capacity != 0 ? new byte[capacity] : Array.Empty<byte>();
_capacity = capacity;
_expandable = true;
_writable = true;
_exposable = true;
_origin = 0; // Must be 0 for byte[]'s created by MemoryStream
_isOpen = true;
}
public MemoryStream(byte[] buffer)
: this(buffer, true)
{
}
public MemoryStream(byte[] buffer, bool writable)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
_buffer = buffer;
_length = _capacity = buffer.Length;
_writable = writable;
_exposable = false;
_origin = 0;
_isOpen = true;
}
public MemoryStream(byte[] buffer, int index, int count)
: this(buffer, index, count, true, false)
{
}
public MemoryStream(byte[] buffer, int index, int count, bool writable)
: this(buffer, index, count, writable, false)
{
}
public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
_buffer = buffer;
_origin = _position = index;
_length = _capacity = index + count;
_writable = writable;
_exposable = publiclyVisible; // Can TryGetBuffer return the array?
_expandable = false;
_isOpen = true;
}
public override bool CanRead
{
[Pure]
get
{ return _isOpen; }
}
public override bool CanSeek
{
[Pure]
get
{ return _isOpen; }
}
public override bool CanWrite
{
[Pure]
get
{ return _writable; }
}
private void EnsureWriteable()
{
if (!CanWrite)
{
throw new NotSupportedException(SR.NotSupported_UnwritableStream);
}
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
_isOpen = false;
_writable = false;
_expandable = false;
// Don't set buffer to null - allow TryGetBuffer & ToArray to work.
}
}
finally
{
// Call base.Close() to cleanup async IO resources
base.Dispose(disposing);
}
}
// returns a bool saying whether we allocated a new array.
private bool EnsureCapacity(int value)
{
// Check for overflow
if (value < 0)
{
throw new IOException(SR.IO_IO_StreamTooLong);
}
if (value > _capacity)
{
int newCapacity = value;
if (newCapacity < 256)
{
newCapacity = 256;
}
if (newCapacity < _capacity * 2)
{
newCapacity = _capacity * 2;
}
Capacity = newCapacity;
return true;
}
return false;
}
public override void Flush()
{
}
#pragma warning disable 1998 //async method with no await operators
public override async Task FlushAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
Flush();
}
#pragma warning restore 1998
public virtual bool TryGetBuffer(out ArraySegment<byte> buffer)
{
if (!_exposable)
{
buffer = default(ArraySegment<byte>);
return false;
}
buffer = new ArraySegment<byte>(_buffer, offset: _origin, count: (_length - _origin));
return true;
}
// -------------- PERF: Internal functions for fast direct access of MemoryStream buffer (cf. BinaryReader for usage) ---------------
// PERF: Internal sibling of GetBuffer, always returns a buffer (cf. GetBuffer())
internal byte[] InternalGetBuffer()
{
return _buffer;
}
// PERF: True cursor position, we don't need _origin for direct access
internal int InternalGetPosition()
{
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
return _position;
}
// PERF: Takes out Int32 as fast as possible
internal int InternalReadInt32()
{
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
int pos = (_position += 4); // use temp to avoid race
if (pos > _length)
{
_position = _length;
throw new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF);
}
return (int)(_buffer[pos - 4] | _buffer[pos - 3] << 8 | _buffer[pos - 2] << 16 | _buffer[pos - 1] << 24);
}
// PERF: Get actual length of bytes available for read; do sanity checks; shift position - i.e. everything except actual copying bytes
internal int InternalEmulateRead(int count)
{
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
int n = _length - _position;
if (n > count)
{
n = count;
}
if (n < 0)
{
n = 0;
}
Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1.
_position += n;
return n;
}
// Gets & sets the capacity (number of bytes allocated) for this stream.
// The capacity cannot be set to a value less than the current length
// of the stream.
//
public virtual int Capacity
{
get
{
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
return _capacity - _origin;
}
set
{
// Only update the capacity if the MS is expandable and the value is different than the current capacity.
// Special behavior if the MS isn't expandable: we don't throw if value is the same as the current capacity
if (value < Length)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity);
}
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
if (!_expandable && (value != Capacity))
{
throw new NotSupportedException(SR.NotSupported_MemStreamNotExpandable);
}
// MemoryStream has this invariant: _origin > 0 => !expandable (see ctors)
if (_expandable && value != _capacity)
{
if (value > 0)
{
byte[] newBuffer = new byte[value];
if (_length > 0)
{
Buffer.BlockCopy(_buffer, 0, newBuffer, 0, _length);
}
_buffer = newBuffer;
}
else
{
_buffer = null;
}
_capacity = value;
}
}
}
public override long Length
{
get
{
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
return _length - _origin;
}
}
public override long Position
{
get
{
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
return _position - _origin;
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
if (value > MemStreamMaxLength)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength);
}
_position = _origin + (int)value;
}
}
public override int Read(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - offset < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
int n = _length - _position;
if (n > count)
{
n = count;
}
if (n <= 0)
{
return 0;
}
Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1.
if (n <= 8)
{
int byteCount = n;
while (--byteCount >= 0)
buffer[offset + byteCount] = _buffer[_position + byteCount];
}
else
Buffer.BlockCopy(_buffer, _position, buffer, offset, n);
_position += n;
return n;
}
public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - offset < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
return ReadAsyncImpl(buffer, offset, count, cancellationToken);
}
#pragma warning disable 1998 //async method with no await operators
private async Task<int> ReadAsyncImpl(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return Read(buffer, offset, count);
}
#pragma warning restore 1998
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) =>
TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), callback, state);
public override int EndRead(IAsyncResult asyncResult) =>
TaskToApm.End<int>(asyncResult);
public override int ReadByte()
{
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
if (_position >= _length)
{
return -1;
}
return _buffer[_position++];
}
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
// This implementation offers better performance compared to the base class version.
// The parameter checks must be in sync with the base version:
if (destination == null)
{
throw new ArgumentNullException(nameof(destination));
}
if (bufferSize <= 0)
{
throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum);
}
if (!CanRead && !CanWrite)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
if (!destination.CanRead && !destination.CanWrite)
{
throw new ObjectDisposedException(nameof(destination), SR.ObjectDisposed_StreamClosed);
}
if (!CanRead)
{
throw new NotSupportedException(SR.NotSupported_UnreadableStream);
}
if (!destination.CanWrite)
{
throw new NotSupportedException(SR.NotSupported_UnwritableStream);
}
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Read() or Write() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Read/Write) when we are not sure.
if (GetType() != typeof(MemoryStream))
{
return base.CopyToAsync(destination, bufferSize, cancellationToken);
}
return CopyToAsyncImpl(destination, bufferSize, cancellationToken);
}
private async Task CopyToAsyncImpl(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// Avoid copying data from this buffer into a temp buffer:
// (require that InternalEmulateRead does not throw,
// otherwise it needs to be wrapped into try-catch-Task.FromException like memStrDest.Write below)
int pos = _position;
int n = InternalEmulateRead(_length - _position);
// If destination is not a memory stream, write there asynchronously:
MemoryStream memStrDest = destination as MemoryStream;
if (memStrDest == null)
{
await destination.WriteAsync(_buffer, pos, n, cancellationToken).ConfigureAwait(false);
}
else
{
memStrDest.Write(_buffer, pos, n);
}
}
public override long Seek(long offset, SeekOrigin loc)
{
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
if (offset > MemStreamMaxLength)
{
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_StreamLength);
}
switch (loc)
{
case SeekOrigin.Begin:
{
int tempPosition = unchecked(_origin + (int)offset);
if (offset < 0 || tempPosition < _origin)
{
throw new IOException(SR.IO_IO_SeekBeforeBegin);
}
_position = tempPosition;
break;
}
case SeekOrigin.Current:
{
int tempPosition = unchecked(_position + (int)offset);
if (unchecked(_position + offset) < _origin || tempPosition < _origin)
{
throw new IOException(SR.IO_IO_SeekBeforeBegin);
}
_position = tempPosition;
break;
}
case SeekOrigin.End:
{
int tempPosition = unchecked(_length + (int)offset);
if (unchecked(_length + offset) < _origin || tempPosition < _origin)
{
throw new IOException(SR.IO_IO_SeekBeforeBegin);
}
_position = tempPosition;
break;
}
default:
throw new ArgumentException(SR.Argument_InvalidSeekOrigin);
}
Debug.Assert(_position >= 0, "_position >= 0");
return _position;
}
// Sets the length of the stream to a given value. The new
// value must be nonnegative and less than the space remaining in
// the array, Int32.MaxValue - origin
// Origin is 0 in all cases other than a MemoryStream created on
// top of an existing array and a specific starting offset was passed
// into the MemoryStream constructor. The upper bounds prevents any
// situations where a stream may be created on top of an array then
// the stream is made longer than the maximum possible length of the
// array (Int32.MaxValue).
//
public override void SetLength(long value)
{
if (value < 0 || value > int.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength);
}
EnsureWriteable();
// Origin wasn't publicly exposed above.
Debug.Assert(MemStreamMaxLength == int.MaxValue); // Check parameter validation logic in this method if this fails.
if (value > (int.MaxValue - _origin))
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength);
}
int newLength = _origin + (int)value;
bool allocatedNewArray = EnsureCapacity(newLength);
if (!allocatedNewArray && newLength > _length)
{
Array.Clear(_buffer, _length, newLength - _length);
}
_length = newLength;
if (_position > newLength)
{
_position = newLength;
}
}
public virtual byte[] ToArray()
{
//BCLDebug.Perf(_exposable, "MemoryStream::GetBuffer will let you avoid a copy.");
int count = _length - _origin;
if (count == 0)
{
return Array.Empty<byte>();
}
byte[] copy = new byte[count];
Buffer.BlockCopy(_buffer, _origin, copy, 0, _length - _origin);
return copy;
}
public override void Write(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - offset < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
EnsureWriteable();
int i = _position + count;
// Check for overflow
if (i < 0)
{
throw new IOException(SR.IO_IO_StreamTooLong);
}
if (i > _length)
{
bool mustZero = _position > _length;
if (i > _capacity)
{
bool allocatedNewArray = EnsureCapacity(i);
if (allocatedNewArray)
{
mustZero = false;
}
}
if (mustZero)
{
Array.Clear(_buffer, _length, i - _length);
}
_length = i;
}
if ((count <= 8) && (buffer != _buffer))
{
int byteCount = count;
while (--byteCount >= 0)
{
_buffer[_position + byteCount] = buffer[offset + byteCount];
}
}
else
{
Buffer.BlockCopy(buffer, offset, _buffer, _position, count);
}
_position = i;
}
public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - offset < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
return WriteAsyncImpl(buffer, offset, count, cancellationToken);
}
#pragma warning disable 1998 //async method with no await operators
private async Task WriteAsyncImpl(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
Write(buffer, offset, count);
}
#pragma warning restore 1998
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) =>
TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), callback, state);
public override void EndWrite(IAsyncResult asyncResult) =>
TaskToApm.End(asyncResult);
public override void WriteByte(byte value)
{
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
EnsureWriteable();
if (_position >= _length)
{
int newLength = _position + 1;
bool mustZero = _position > _length;
if (newLength >= _capacity)
{
bool allocatedNewArray = EnsureCapacity(newLength);
if (allocatedNewArray)
{
mustZero = false;
}
}
if (mustZero)
{
Array.Clear(_buffer, _length, _position - _length);
}
_length = newLength;
}
_buffer[_position++] = value;
}
// Writes this MemoryStream to another stream.
public virtual void WriteTo(Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream), SR.ArgumentNull_Stream);
}
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
stream.Write(_buffer, _origin, _length - _origin);
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_ASHTTP
{
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
/// <summary>
/// This scenario is designed to test optional headers of HTTP POST command.
/// </summary>
[TestClass]
public class S03_HTTPPOSTOptionalHeader : TestSuiteBase
{
#region Class initialize and clean up
/// <summary>
/// Initialize the class.
/// </summary>
/// <param name="testContext">VSTS test context.</param>
[ClassInitialize]
public static void ClassInitialize(TestContext testContext)
{
TestClassBase.Initialize(testContext);
}
/// <summary>
/// Clear the class.
/// </summary>
[ClassCleanup]
public static void ClassCleanup()
{
TestClassBase.Cleanup();
}
#endregion
#region Test cases
/// <summary>
/// This test case is intended to validate the MS-ASAcceptMultiPart optional header in HTTP POST request.
/// </summary>
[TestCategory("MSASHTTP"), TestMethod()]
public void MSASHTTP_S03_TC01_SetASAcceptMultiPartRequestHeader()
{
#region Call SendMail command to send email to User2.
// Call ConfigureRequestPrefixFields to set the QueryValueType to PlainText.
IDictionary<HTTPPOSTRequestPrefixField, string> requestPrefix = new Dictionary<HTTPPOSTRequestPrefixField, string>();
requestPrefix.Add(HTTPPOSTRequestPrefixField.QueryValueType, QueryValueType.PlainText.ToString());
this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefix);
// Call FolderSync command to synchronize the collection hierarchy.
this.CallFolderSyncCommand();
string sendMailSubject = Common.GenerateResourceName(Site, "SendMail");
string userOneMailboxAddress = Common.GetMailAddress(this.UserOneInformation.UserName, this.UserOneInformation.UserDomain);
string userTwoMailboxAddress = Common.GetMailAddress(this.UserTwoInformation.UserName, this.UserTwoInformation.UserDomain);
// Call SendMail command.
this.CallSendMailCommand(userOneMailboxAddress, userTwoMailboxAddress, sendMailSubject, null);
#endregion
#region Get the received email.
// Call ConfigureRequestPrefixFields to switch the credential to User2 and synchronize the collection hierarchy.
this.SwitchUser(this.UserTwoInformation, true);
this.AddCreatedItemToCollection("User2", this.UserTwoInformation.InboxCollectionId, sendMailSubject);
// Call Sync command to get the received email.
string itemServerId = this.LoopToSyncItem(this.UserTwoInformation.InboxCollectionId, sendMailSubject, true);
#endregion
#region Call ItemOperation command with setting MS-ASAcceptMultiPart header to "T".
// Call ConfigureRequestPrefixFields to set MS-ASAcceptMultiPart header to "T".
requestPrefix.Add(HTTPPOSTRequestPrefixField.AcceptMultiPart, "T");
this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefix);
// Call ItemOperation command to fetch the received email.
SendStringResponse itemOperationResponse = this.CallItemOperationsCommand(this.UserTwoInformation.InboxCollectionId, itemServerId, false);
Site.Assert.IsNotNull(itemOperationResponse.Headers["Content-Type"], "The Content-Type header should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R154");
// Verify MS-ASHTTP requirement: MS-ASHTTP_R154
// The content is in multipart, so this requirement can be captured.
Site.CaptureRequirementIfAreEqual<string>(
"application/vnd.ms-sync.multipart",
itemOperationResponse.Headers["Content-Type"],
154,
@"[In MS-ASAcceptMultiPart] If this [MS-ASAcceptMultiPart] header is present and the value is 'T', the client is requesting that the server return content in multipart format.");
#endregion
#region Call ItemOperation command with setting MS-ASAcceptMultiPart header to "F".
// Call ConfigureRequestPrefixFields to change the MS-ASAcceptMultiPart header to "F".
requestPrefix[HTTPPOSTRequestPrefixField.AcceptMultiPart] = "F";
this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefix);
// Call ItemOperation command to fetch the received email.
itemOperationResponse = this.CallItemOperationsCommand(this.UserTwoInformation.InboxCollectionId, itemServerId, false);
Site.Assert.IsNotNull(itemOperationResponse.Headers["Content-Type"], "The Content-Type header should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R440");
// Verify MS-ASHTTP requirement: MS-ASHTTP_R440
// The content is not in multipart, so this requirement can be captured.
Site.CaptureRequirementIfAreNotEqual<string>(
"application/vnd.ms-sync.multipart",
itemOperationResponse.Headers["Content-Type"],
440,
@"[In MS-ASAcceptMultiPart] If the [MS-ASAcceptMultiPart] header [is not present, or] is present and set to 'F', the client is requesting that the server return content in inline format.");
#endregion
#region Call ItemOperation command with setting MS-ASAcceptMultiPart header to null.
// Call ConfigureRequestPrefixFields to change the MS-ASAcceptMultiPart header to null.
requestPrefix[HTTPPOSTRequestPrefixField.AcceptMultiPart] = null;
this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefix);
// Call ItemOperation command to fetch the received email.
itemOperationResponse = this.CallItemOperationsCommand(this.UserTwoInformation.InboxCollectionId, itemServerId, false);
Site.Assert.IsNotNull(itemOperationResponse.Headers["Content-Type"], "The Content-Type header should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R155");
// Verify MS-ASHTTP requirement: MS-ASHTTP_R155
// The content is not in multipart, so this requirement can be captured.
Site.CaptureRequirementIfAreNotEqual<string>(
"application/vnd.ms-sync.multipart",
itemOperationResponse.Headers["Content-Type"],
155,
@"[In MS-ASAcceptMultiPart] If the [MS-ASAcceptMultiPart] header is not present [, or is present and set to 'F'], the client is requesting that the server return content in inline format.");
#endregion
#region Reset the query value type and credential.
requestPrefix[HTTPPOSTRequestPrefixField.QueryValueType] = Common.GetConfigurationPropertyValue("HeaderEncodingType", this.Site);
this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefix);
this.SwitchUser(this.UserOneInformation, false);
#endregion
}
/// <summary>
/// This test case is intended to validate the User-Agent optional header in HTTP POST request.
/// </summary>
[TestCategory("MSASHTTP"), TestMethod()]
public void MSASHTTP_S03_TC02_SetUserAgentRequestHeader()
{
#region Call ConfigureRequestPrefixFields to add the User-Agent header.
string folderSyncRequestBody = Common.CreateFolderSyncRequest("0").GetRequestDataSerializedXML();
Dictionary<HTTPPOSTRequestPrefixField, string> requestPrefixFields = new Dictionary<HTTPPOSTRequestPrefixField, string>
{
{
HTTPPOSTRequestPrefixField.UserAgent, "ASOM"
}
};
this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefixFields);
#endregion
#region Call FolderSync command.
SendStringResponse folderSyncResponse = HTTPAdapter.HTTPPOST(CommandName.FolderSync, null, folderSyncRequestBody);
// Check the command is executed successfully.
this.CheckResponseStatus(folderSyncResponse.ResponseDataXML);
#endregion
#region Reset the User-Agent header.
requestPrefixFields[HTTPPOSTRequestPrefixField.UserAgent] = null;
this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefixFields);
#endregion
}
/// <summary>
/// This test case is intended to validate the X-MS-PolicyKey optional header and Policy key optional field in HTTP POST request.
/// </summary>
[TestCategory("MSASHTTP"), TestMethod()]
public void MSASHTTP_S03_TC03_SetPolicyKeyRequestHeader()
{
#region Change the query value type to PlainText.
// Call ConfigureRequestPrefixFields to set the QueryValueType to PlainText.
IDictionary<HTTPPOSTRequestPrefixField, string> requestPrefix = new Dictionary<HTTPPOSTRequestPrefixField, string>();
requestPrefix.Add(HTTPPOSTRequestPrefixField.QueryValueType, QueryValueType.PlainText.ToString());
this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefix);
#endregion
#region Call Provision command without setting X-MS-PolicyKey header.
SendStringResponse provisionResponse = this.CallProvisionCommand(string.Empty);
// Get the policy key from the response of Provision command.
string policyKey = TestSuiteHelper.GetPolicyKeyFromSendString(provisionResponse);
#endregion
#region Call Provision command with setting X-MS-PolicyKey header of the PlainText encoded query value type.
// Set the X-MS-PolicyKey header.
requestPrefix.Add(HTTPPOSTRequestPrefixField.PolicyKey, policyKey);
this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefix);
this.CallProvisionCommand(policyKey);
// Reset the X-MS-PolicyKey header.
requestPrefix[HTTPPOSTRequestPrefixField.PolicyKey] = string.Empty;
this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefix);
#endregion
#region Change the query value type to Base64.
// Call ConfigureRequestPrefixFields to set the QueryValueType to Base64.
requestPrefix[HTTPPOSTRequestPrefixField.QueryValueType] = QueryValueType.Base64.ToString();
this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefix);
#endregion
#region Call Provision command without setting Policy key field.
provisionResponse = this.CallProvisionCommand(string.Empty);
// Get the policy key from the response of Provision command.
policyKey = TestSuiteHelper.GetPolicyKeyFromSendString(provisionResponse);
#endregion
#region Call Provision command with setting Policy key field of the base64 encoded query value type.
// Set the Policy key field.
requestPrefix[HTTPPOSTRequestPrefixField.PolicyKey] = policyKey;
this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefix);
this.CallProvisionCommand(policyKey);
// Reset the Policy key field.
requestPrefix[HTTPPOSTRequestPrefixField.PolicyKey] = string.Empty;
this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefix);
#endregion
#region Reset the query value type.
requestPrefix[HTTPPOSTRequestPrefixField.QueryValueType] = Common.GetConfigurationPropertyValue("HeaderEncodingType", this.Site);
this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefix);
#endregion
}
/// <summary>
/// This test case is intended to validate server can use different values for the number of User-Agent header changes or the time
/// period, or the time period that server blocks client from changing its User-Agent header value.
/// </summary>
[TestCategory("MSASHTTP"), TestMethod()]
public void MSASHTTP_S03_TC04_LimitChangesToUserAgentHeader()
{
Site.Assume.IsTrue(Common.IsRequirementEnabled(456, this.Site), "Exchange server 2013 and above support using different values for the number of User-Agent changes or the time period.");
Site.Assume.IsTrue(Common.IsRequirementEnabled(457, this.Site), "Exchange server 2013 and above support blocking clients for a different amount of time.");
#region Call FolderSync command for the first time with User-Agent header.
// Wait for 1 minute
System.Threading.Thread.Sleep(new TimeSpan(0, 1, 0));
DateTime startTime = DateTime.Now;
string folderSyncRequestBody = Common.CreateFolderSyncRequest("0").GetRequestDataSerializedXML();
Dictionary<HTTPPOSTRequestPrefixField, string> requestPrefixFields = new Dictionary<HTTPPOSTRequestPrefixField, string>
{
{
HTTPPOSTRequestPrefixField.UserAgent, Common.GenerateResourceName(this.Site, "ASOM", 1)
}
};
this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefixFields);
SendStringResponse folderSyncResponse = HTTPAdapter.HTTPPOST(CommandName.FolderSync, null, folderSyncRequestBody);
// Check the command is executed successfully.
this.CheckResponseStatus(folderSyncResponse.ResponseDataXML);
#endregion
#region Call FolderSync command for the second time with updated User-Agent header.
requestPrefixFields[HTTPPOSTRequestPrefixField.UserAgent] = Common.GenerateResourceName(this.Site, "ASOM", 2);
this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefixFields);
folderSyncResponse = HTTPAdapter.HTTPPOST(CommandName.FolderSync, null, folderSyncRequestBody);
// Check the command is executed successfully.
this.CheckResponseStatus(folderSyncResponse.ResponseDataXML);
#endregion
#region Call FolderSync command for third time with updated User-Agent header.
requestPrefixFields[HTTPPOSTRequestPrefixField.UserAgent] = Common.GenerateResourceName(this.Site, "ASOM", 3);
this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefixFields);
try
{
folderSyncResponse = HTTPAdapter.HTTPPOST(CommandName.FolderSync, null, folderSyncRequestBody);
Site.Assert.Fail("HTTP error 503 should be returned if server blocks a client from changing its User-Agent header value.");
}
catch (System.Net.WebException exception)
{
int statusCode = ((System.Net.HttpWebResponse)exception.Response).StatusCode.GetHashCode();
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R422");
// Verify MS-ASHTTP requirement: MS-ASHTTP_R422
Site.CaptureRequirementIfAreEqual<int>(
503,
statusCode,
422,
@"[In User-Agent Change Tracking] If the server blocks a client from changing its User-Agent header value, it [server] returns an HTTP error 503.");
if (Common.IsRequirementEnabled(456, this.Site))
{
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R456");
// Verify MS-ASHTTP requirement: MS-ASHTTP_R456
// Server configures the number of changes and the time period, and expected HTTP error is returned, this requirement can be captured.
Site.CaptureRequirementIfAreEqual<int>(
503,
statusCode,
456,
@"[In Appendix A: Product Behavior] Implementation can be configured to use different values for the allowed number of changes and the time period. (<8> Section 3.2.5.1.1: Exchange 2013 and Exchange 2016 Preview can be configured to use different values for the allowed number of changes and the time period.)");
}
}
#endregion
#region Call FolderSync command after server blocks client from changing its User-Agent header value.
requestPrefixFields[HTTPPOSTRequestPrefixField.UserAgent] = Common.GenerateResourceName(this.Site, "ASOM", 4);
this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefixFields);
bool isCorrectBlocked = false;
try
{
folderSyncResponse = HTTPAdapter.HTTPPOST(CommandName.FolderSync, null, folderSyncRequestBody);
}
catch (System.Net.WebException)
{
// HTTP error returns indicates server blocks client.
isCorrectBlocked = true;
}
// Server sets blocking client for 1 minute, wait for 1 minute for un-blocking.
System.Threading.Thread.Sleep(new TimeSpan(0, 1, 0));
requestPrefixFields[HTTPPOSTRequestPrefixField.UserAgent] = Common.GenerateResourceName(this.Site, "ASOM", 5);
this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefixFields);
try
{
folderSyncResponse = HTTPAdapter.HTTPPOST(CommandName.FolderSync, null, folderSyncRequestBody);
isCorrectBlocked = isCorrectBlocked && true;
}
catch (System.Net.WebException)
{
// HTTP error returns indicates server still blocks client.
isCorrectBlocked = false;
}
if (Common.IsRequirementEnabled(457, this.Site))
{
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASHTTP_R457");
// Verify MS-ASHTTP requirement: MS-ASHTTP_R457
// FolderSync command runs successfully after the blocking time period, and it runs with exception during the time period,
// this requirement can be captured.
Site.CaptureRequirementIfIsTrue(
isCorrectBlocked,
457,
@"[In Appendix A: Product Behavior] Implementation can be configured to block clients for an amount of time other than 14 hours. (<9> Section 3.2.5.1.1: Exchange 2013 and Exchange 2016 Preview can be configured to block clients for an amount of time other than 14 hours.)");
}
// Wait for 1 minute
System.Threading.Thread.Sleep(new TimeSpan(0, 1, 0));
#endregion
#region Reset the User-Agent header.
requestPrefixFields[HTTPPOSTRequestPrefixField.UserAgent] = null;
this.HTTPAdapter.ConfigureRequestPrefixFields(requestPrefixFields);
#endregion
}
#endregion
}
}
| |
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
[CanEditMultipleObjects]
[CustomEditor(typeof(tk2dSlicedSprite))]
class tk2dSlicedSpriteEditor : tk2dSpriteEditor
{
tk2dSlicedSprite[] targetSlicedSprites = new tk2dSlicedSprite[0];
new void OnEnable() {
base.OnEnable();
targetSlicedSprites = GetTargetsOfType<tk2dSlicedSprite>( targets );
}
public override void OnInspectorGUI()
{
tk2dSlicedSprite sprite = (tk2dSlicedSprite)target;
base.OnInspectorGUI();
if (sprite.Collection == null)
return;
var spriteData = sprite.GetCurrentSpriteDef();
if (spriteData == null) {
return;
}
EditorGUILayout.BeginVertical();
WarnSpriteRenderType(spriteData);
// need raw extents (excluding scale)
Vector3 extents = spriteData.boundsData[1];
// this is the size of one texel
Vector3 spritePixelMultiplier = new Vector3(0, 0);
bool newCreateBoxCollider = base.DrawCreateBoxColliderCheckbox(sprite.CreateBoxCollider);
if (newCreateBoxCollider != sprite.CreateBoxCollider) {
sprite.CreateBoxCollider = newCreateBoxCollider;
if (sprite.CreateBoxCollider) { sprite.EditMode__CreateCollider(); }
}
// if either of these are zero, the division to rescale to pixels will result in a
// div0, so display the data in fractions to avoid this situation
bool editBorderInFractions = true;
if (spriteData.texelSize.x != 0.0f && spriteData.texelSize.y != 0.0f && extents.x != 0.0f && extents.y != 0.0f)
{
spritePixelMultiplier = new Vector3(extents.x / spriteData.texelSize.x, extents.y / spriteData.texelSize.y, 1);
editBorderInFractions = false;
}
if (!editBorderInFractions)
{
Vector2 newDimensions = EditorGUILayout.Vector2Field("Dimensions (Pixel Units)", sprite.dimensions);
if (newDimensions != sprite.dimensions) {
tk2dUndo.RecordObjects(targetSlicedSprites, "Sliced Sprite Dimensions");
foreach (tk2dSlicedSprite spr in targetSlicedSprites) {
spr.dimensions = newDimensions;
}
}
tk2dSlicedSprite.Anchor newAnchor = (tk2dSlicedSprite.Anchor)EditorGUILayout.EnumPopup("Anchor", sprite.anchor);
if (newAnchor != sprite.anchor) {
tk2dUndo.RecordObjects(targetSlicedSprites, "Sliced Sprite Anchor");
foreach (tk2dSlicedSprite spr in targetSlicedSprites) {
spr.anchor = newAnchor;
}
}
EditorGUILayout.PrefixLabel("Border");
EditorGUI.indentLevel++;
float newBorderLeft = EditorGUILayout.FloatField("Left", sprite.borderLeft * spritePixelMultiplier.x) / spritePixelMultiplier.x;
if (newBorderLeft != sprite.borderLeft) {
tk2dUndo.RecordObjects(targetSlicedSprites, "Sliced Sprite BorderLeft");
foreach (tk2dSlicedSprite spr in targetSlicedSprites) spr.borderLeft = newBorderLeft;
}
float newBorderRight = EditorGUILayout.FloatField("Right", sprite.borderRight * spritePixelMultiplier.x) / spritePixelMultiplier.x;
if (newBorderRight != sprite.borderRight) {
tk2dUndo.RecordObjects(targetSlicedSprites, "Sliced Sprite BorderRight");
foreach (tk2dSlicedSprite spr in targetSlicedSprites) spr.borderRight = newBorderRight;
}
float newBorderTop = EditorGUILayout.FloatField("Top", sprite.borderTop * spritePixelMultiplier.y) / spritePixelMultiplier.y;
if (newBorderTop != sprite.borderTop) {
tk2dUndo.RecordObjects(targetSlicedSprites, "Sliced Sprite BorderTop");
foreach (tk2dSlicedSprite spr in targetSlicedSprites) spr.borderTop = newBorderTop;
}
float newBorderBottom = EditorGUILayout.FloatField("Bottom", sprite.borderBottom * spritePixelMultiplier.y) / spritePixelMultiplier.y;
if (newBorderBottom != sprite.borderBottom) {
tk2dUndo.RecordObjects(targetSlicedSprites, "Sliced Sprite BorderBottom");
foreach (tk2dSlicedSprite spr in targetSlicedSprites) spr.borderBottom = newBorderBottom;
}
bool newBorderOnly = EditorGUILayout.Toggle("Draw Border Only", sprite.BorderOnly);
if (newBorderOnly != sprite.BorderOnly) {
tk2dUndo.RecordObjects(targetSlicedSprites, "Sliced Sprite Border Only");
foreach (tk2dSlicedSprite spr in targetSlicedSprites) spr.BorderOnly = newBorderOnly;
}
EditorGUI.indentLevel--;
}
else
{
GUILayout.Label("Border (Displayed as Fraction).\nSprite Collection needs to be rebuilt.", "textarea");
EditorGUI.indentLevel++;
float newBorderLeft = EditorGUILayout.FloatField("Left", sprite.borderLeft);
if (newBorderLeft != sprite.borderLeft) {
tk2dUndo.RecordObjects(targetSlicedSprites, "Sliced Sprite BorderLeft");
foreach (tk2dSlicedSprite spr in targetSlicedSprites) spr.borderLeft = newBorderLeft;
}
float newBorderRight = EditorGUILayout.FloatField("Right", sprite.borderRight);
if (newBorderRight != sprite.borderRight) {
tk2dUndo.RecordObjects(targetSlicedSprites, "Sliced Sprite BorderRight");
foreach (tk2dSlicedSprite spr in targetSlicedSprites) spr.borderRight = newBorderRight;
}
float newBorderTop = EditorGUILayout.FloatField("Top", sprite.borderTop);
if (newBorderTop != sprite.borderTop) {
tk2dUndo.RecordObjects(targetSlicedSprites, "Sliced Sprite BorderTop");
foreach (tk2dSlicedSprite spr in targetSlicedSprites) spr.borderTop = newBorderTop;
}
float newBorderBottom = EditorGUILayout.FloatField("Bottom", sprite.borderBottom);
if (newBorderBottom != sprite.borderBottom) {
tk2dUndo.RecordObjects(targetSlicedSprites, "Sliced Sprite BorderBottom");
foreach (tk2dSlicedSprite spr in targetSlicedSprites) spr.borderBottom = newBorderBottom;
}
EditorGUI.indentLevel--;
}
// One of the border valus has changed, so simply rebuild mesh data here
if (GUI.changed)
{
foreach (tk2dSlicedSprite spr in targetSlicedSprites) {
spr.Build();
EditorUtility.SetDirty(spr);
}
}
EditorGUILayout.EndVertical();
}
public new void OnSceneGUI() {
if (tk2dPreferences.inst.enableSpriteHandles == false) return;
tk2dSlicedSprite spr = (tk2dSlicedSprite)target;
var sprite = spr.CurrentSprite;
if (sprite == null) {
return;
}
Transform t = spr.transform;
Vector2 meshSize = new Vector2(spr.dimensions.x * sprite.texelSize.x * spr.scale.x, spr.dimensions.y * sprite.texelSize.y * spr.scale.y);
Vector2 localRectOrig = tk2dSceneHelper.GetAnchorOffset(meshSize, spr.anchor);
Rect localRect = new Rect(localRectOrig.x, localRectOrig.y, meshSize.x, meshSize.y);
// Draw rect outline
Handles.color = new Color(1,1,1,0.5f);
tk2dSceneHelper.DrawRect (localRect, t);
Handles.BeginGUI ();
// Resize handles
if (tk2dSceneHelper.RectControlsToggle ()) {
EditorGUI.BeginChangeCheck ();
Rect resizeRect = tk2dSceneHelper.RectControl(123192, localRect, t);
if (EditorGUI.EndChangeCheck ()) {
tk2dUndo.RecordObjects (new Object[] {t, spr}, "Resize");
spr.ReshapeBounds(new Vector3(resizeRect.xMin, resizeRect.yMin) - new Vector3(localRect.xMin, localRect.yMin),
new Vector3(resizeRect.xMax, resizeRect.yMax) - new Vector3(localRect.xMax, localRect.yMax));
EditorUtility.SetDirty(spr);
}
}
// Rotate handles
if (!tk2dSceneHelper.RectControlsToggle ()) {
EditorGUI.BeginChangeCheck();
List<int> hidePts = tk2dSceneHelper.getAnchorHidePtList(spr.anchor, localRect, t);
float theta = tk2dSceneHelper.RectRotateControl( 456384, localRect, t, hidePts );
if (EditorGUI.EndChangeCheck()) {
if (Mathf.Abs(theta) > Mathf.Epsilon) {
tk2dUndo.RecordObject(t, "Rotate");
t.Rotate(t.forward, theta, Space.World);
}
}
}
Handles.EndGUI ();
// Sprite selecting
tk2dSceneHelper.HandleSelectSprites();
// Move targeted sprites
tk2dSceneHelper.HandleMoveSprites(t, localRect);
if (GUI.changed) {
EditorUtility.SetDirty(target);
}
}
[MenuItem("GameObject/Create Other/tk2d/Sliced Sprite", false, 12901)]
static void DoCreateSlicedSpriteObject()
{
tk2dSpriteGuiUtility.GetSpriteCollectionAndCreate( (sprColl) => {
GameObject go = tk2dEditorUtility.CreateGameObjectInScene("Sliced Sprite");
tk2dSlicedSprite sprite = go.AddComponent<tk2dSlicedSprite>();
sprite.SetSprite(sprColl, sprColl.FirstValidDefinitionIndex);
sprite.Build();
Selection.activeGameObject = go;
Undo.RegisterCreatedObjectUndo(go, "Create Sliced Sprite");
} );
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using MusicStore.Api.Areas.HelpPage.ModelDescriptions;
using MusicStore.Api.Areas.HelpPage.Models;
namespace MusicStore.Api.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
if (complexTypeDescription != null)
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit
{
using System;
using System.Threading;
using System.Threading.Tasks;
using GreenPipes;
using Util;
public static class EndpointConventionExtensions
{
/// <summary>
/// Send a message
/// </summary>
/// <typeparam name="T">The message type</typeparam>
/// <param name="provider"></param>
/// <param name="message">The message</param>
/// <param name="cancellationToken"></param>
/// <returns>The task which is completed once the Send is acknowledged by the broker</returns>
public static async Task Send<T>(this ISendEndpointProvider provider, T message, CancellationToken cancellationToken = default)
where T : class
{
if (!EndpointConvention.TryGetDestinationAddress<T>(out var destinationAddress))
throw new ArgumentException($"A convention for the message type {TypeMetadataCache<T>.ShortName} was not found");
var endpoint = await provider.GetSendEndpoint(destinationAddress).ConfigureAwait(false);
await endpoint.Send(message, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Send a message
/// </summary>
/// <typeparam name="T">The message type</typeparam>
/// <param name="provider"></param>
/// <param name="message">The message</param>
/// <param name="pipe"></param>
/// <param name="cancellationToken"></param>
/// <returns>The task which is completed once the Send is acknowledged by the broker</returns>
public static async Task Send<T>(this ISendEndpointProvider provider, T message, IPipe<SendContext<T>> pipe,
CancellationToken cancellationToken = default)
where T : class
{
if (!EndpointConvention.TryGetDestinationAddress<T>(out var destinationAddress))
throw new ArgumentException($"A convention for the message type {TypeMetadataCache<T>.ShortName} was not found");
var endpoint = await provider.GetSendEndpoint(destinationAddress).ConfigureAwait(false);
await endpoint.Send(message, pipe, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Send a message
/// </summary>
/// <typeparam name="T">The message type</typeparam>
/// <param name="provider"></param>
/// <param name="message">The message</param>
/// <param name="pipe"></param>
/// <param name="cancellationToken"></param>
/// <returns>The task which is completed once the Send is acknowledged by the broker</returns>
public static async Task Send<T>(this ISendEndpointProvider provider, T message, IPipe<SendContext> pipe, CancellationToken cancellationToken = default)
where T : class
{
if (!EndpointConvention.TryGetDestinationAddress<T>(out var destinationAddress))
throw new ArgumentException($"A convention for the message type {TypeMetadataCache<T>.ShortName} was not found");
var endpoint = await provider.GetSendEndpoint(destinationAddress).ConfigureAwait(false);
await endpoint.Send(message, pipe, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Send a message
/// </summary>
/// <param name="provider"></param>
/// <param name="message">The message</param>
/// <param name="cancellationToken"></param>
/// <returns>The task which is completed once the Send is acknowledged by the broker</returns>
public static async Task Send(this ISendEndpointProvider provider, object message, CancellationToken cancellationToken = default)
{
if (message == null)
throw new ArgumentNullException(nameof(message));
var messageType = message.GetType();
if (!EndpointConvention.TryGetDestinationAddress(messageType, out var destinationAddress))
throw new ArgumentException($"A convention for the message type {TypeMetadataCache.GetShortName(messageType)} was not found");
var endpoint = await provider.GetSendEndpoint(destinationAddress).ConfigureAwait(false);
await endpoint.Send(message, messageType, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Send a message
/// </summary>
/// <param name="provider"></param>
/// <param name="message">The message</param>
/// <param name="messageType"></param>
/// <param name="cancellationToken"></param>
/// <returns>The task which is completed once the Send is acknowledged by the broker</returns>
public static async Task Send(this ISendEndpointProvider provider, object message, Type messageType, CancellationToken cancellationToken = default)
{
if (!EndpointConvention.TryGetDestinationAddress(messageType, out var destinationAddress))
throw new ArgumentException($"A convention for the message type {TypeMetadataCache.GetShortName(messageType)} was not found");
var endpoint = await provider.GetSendEndpoint(destinationAddress).ConfigureAwait(false);
await endpoint.Send(message, messageType, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Send a message
/// </summary>
/// <param name="provider"></param>
/// <param name="message">The message</param>
/// <param name="messageType"></param>
/// <param name="pipe"></param>
/// <param name="cancellationToken"></param>
/// <returns>The task which is completed once the Send is acknowledged by the broker</returns>
public static async Task Send(this ISendEndpointProvider provider, object message, Type messageType, IPipe<SendContext> pipe,
CancellationToken cancellationToken = default)
{
if (message == null)
throw new ArgumentNullException(nameof(message));
if (messageType == null)
throw new ArgumentNullException(nameof(messageType));
if (!EndpointConvention.TryGetDestinationAddress(messageType, out var destinationAddress))
throw new ArgumentException($"A convention for the message type {TypeMetadataCache.GetShortName(messageType)} was not found");
var endpoint = await provider.GetSendEndpoint(destinationAddress).ConfigureAwait(false);
await endpoint.Send(message, messageType, pipe, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Send a message
/// </summary>
/// <param name="provider"></param>
/// <param name="message">The message</param>
/// <param name="pipe"></param>
/// <param name="cancellationToken"></param>
/// <returns>The task which is completed once the Send is acknowledged by the broker</returns>
public static async Task Send(this ISendEndpointProvider provider, object message, IPipe<SendContext> pipe,
CancellationToken cancellationToken = default)
{
if (message == null)
throw new ArgumentNullException(nameof(message));
var messageType = message.GetType();
if (!EndpointConvention.TryGetDestinationAddress(messageType, out var destinationAddress))
throw new ArgumentException($"A convention for the message type {TypeMetadataCache.GetShortName(messageType)} was not found");
var endpoint = await provider.GetSendEndpoint(destinationAddress).ConfigureAwait(false);
await endpoint.Send(message, pipe, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Send a message
/// </summary>
/// <typeparam name="T">The message type</typeparam>
/// <param name="provider"></param>
/// <param name="values"></param>
/// <param name="cancellationToken"></param>
/// <returns>The task which is completed once the Send is acknowledged by the broker</returns>
public static async Task Send<T>(this ISendEndpointProvider provider, object values, CancellationToken cancellationToken = default)
where T : class
{
var message = TypeMetadataCache<T>.InitializeFromObject(values);
if (!EndpointConvention.TryGetDestinationAddress<T>(out var destinationAddress))
throw new ArgumentException($"A convention for the message type {TypeMetadataCache<T>.ShortName} was not found");
var endpoint = await provider.GetSendEndpoint(destinationAddress).ConfigureAwait(false);
await endpoint.Send(message, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Send a message
/// </summary>
/// <typeparam name="T">The message type</typeparam>
/// <param name="provider"></param>
/// <param name="values"></param>
/// <param name="pipe"></param>
/// <param name="cancellationToken"></param>
/// <returns>The task which is completed once the Send is acknowledged by the broker</returns>
public static async Task Send<T>(this ISendEndpointProvider provider, object values, IPipe<SendContext<T>> pipe,
CancellationToken cancellationToken = default)
where T : class
{
var message = TypeMetadataCache<T>.InitializeFromObject(values);
if (!EndpointConvention.TryGetDestinationAddress<T>(out var destinationAddress))
throw new ArgumentException($"A convention for the message type {TypeMetadataCache<T>.ShortName} was not found");
var endpoint = await provider.GetSendEndpoint(destinationAddress).ConfigureAwait(false);
await endpoint.Send(message, pipe, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Send a message
/// </summary>
/// <typeparam name="T">The message type</typeparam>
/// <param name="provider"></param>
/// <param name="values"></param>
/// <param name="pipe"></param>
/// <param name="cancellationToken"></param>
/// <returns>The task which is completed once the Send is acknowledged by the broker</returns>
public static async Task Send<T>(this ISendEndpointProvider provider, object values, IPipe<SendContext> pipe,
CancellationToken cancellationToken = default)
where T : class
{
var message = TypeMetadataCache<T>.InitializeFromObject(values);
if (!EndpointConvention.TryGetDestinationAddress<T>(out var destinationAddress))
throw new ArgumentException($"A convention for the message type {TypeMetadataCache<T>.ShortName} was not found");
var endpoint = await provider.GetSendEndpoint(destinationAddress).ConfigureAwait(false);
await endpoint.Send(message, pipe, cancellationToken).ConfigureAwait(false);
}
}
}
| |
using System;
using System.Text;
namespace Lucene.Net.Index
{
using Lucene.Net.Util;
using System.IO;
/*
* 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 Analyzer = Lucene.Net.Analysis.Analyzer;
using Codec = Lucene.Net.Codecs.Codec;
using IndexingChain = Lucene.Net.Index.DocumentsWriterPerThread.IndexingChain;
using IndexReaderWarmer = Lucene.Net.Index.IndexWriter.IndexReaderWarmer;
using InfoStream = Lucene.Net.Util.InfoStream;
using PrintStreamInfoStream = Lucene.Net.Util.PrintStreamInfoStream;
using Similarity = Lucene.Net.Search.Similarities.Similarity;
/// <summary>
/// Holds all the configuration that is used to create an <seealso cref="IndexWriter"/>.
/// Once <seealso cref="IndexWriter"/> has been created with this object, changes to this
/// object will not affect the <seealso cref="IndexWriter"/> instance. For that, use
/// <seealso cref="LiveIndexWriterConfig"/> that is returned from <seealso cref="IndexWriter#getConfig()"/>.
///
/// <p>
/// All setter methods return <seealso cref="IndexWriterConfig"/> to allow chaining
/// settings conveniently, for example:
///
/// <pre class="prettyprint">
/// IndexWriterConfig conf = new IndexWriterConfig(analyzer);
/// conf.setter1().setter2();
/// </pre>
/// </summary>
/// <seealso cref= IndexWriter#getConfig()
///
/// @since 3.1 </seealso>
public sealed class IndexWriterConfig : LiveIndexWriterConfig, ICloneable
{
/// <summary>
/// Specifies the open mode for <seealso cref="IndexWriter"/>.
/// </summary>
public enum OpenMode_e
{
/// <summary>
/// Creates a new index or overwrites an existing one.
/// </summary>
CREATE,
/// <summary>
/// Opens an existing index.
/// </summary>
APPEND,
/// <summary>
/// Creates a new index if one does not exist,
/// otherwise it opens the index and documents will be appended.
/// </summary>
CREATE_OR_APPEND
}
/// <summary>
/// Default value is 32. Change using <seealso cref="#setTermIndexInterval(int)"/>. </summary>
public const int DEFAULT_TERM_INDEX_INTERVAL = 32; // TODO: this should be private to the codec, not settable here
/// <summary>
/// Denotes a flush trigger is disabled. </summary>
public const int DISABLE_AUTO_FLUSH = -1;
/// <summary>
/// Disabled by default (because IndexWriter flushes by RAM usage by default). </summary>
public const int DEFAULT_MAX_BUFFERED_DELETE_TERMS = DISABLE_AUTO_FLUSH;
/// <summary>
/// Disabled by default (because IndexWriter flushes by RAM usage by default). </summary>
public const int DEFAULT_MAX_BUFFERED_DOCS = DISABLE_AUTO_FLUSH;
/// <summary>
/// Default value is 16 MB (which means flush when buffered docs consume
/// approximately 16 MB RAM).
/// </summary>
public const double DEFAULT_RAM_BUFFER_SIZE_MB = 16.0;
/// <summary>
/// Default value for the write lock timeout (1,000 ms).
/// </summary>
/// <seealso cref= #setDefaultWriteLockTimeout(long) </seealso>
public static long WRITE_LOCK_TIMEOUT = 1000;
/// <summary>
/// Default setting for <seealso cref="#setReaderPooling"/>. </summary>
public const bool DEFAULT_READER_POOLING = false;
/// <summary>
/// Default value is 1. Change using <seealso cref="#setReaderTermsIndexDivisor(int)"/>. </summary>
public const int DEFAULT_READER_TERMS_INDEX_DIVISOR = DirectoryReader.DEFAULT_TERMS_INDEX_DIVISOR;
/// <summary>
/// Default value is 1945. Change using <seealso cref="#setRAMPerThreadHardLimitMB(int)"/> </summary>
public const int DEFAULT_RAM_PER_THREAD_HARD_LIMIT_MB = 1945;
/// <summary>
/// The maximum number of simultaneous threads that may be
/// indexing documents at once in IndexWriter; if more
/// than this many threads arrive they will wait for
/// others to finish. Default value is 8.
/// </summary>
public const int DEFAULT_MAX_THREAD_STATES = 8;
/// <summary>
/// Default value for compound file system for newly written segments
/// (set to <code>true</code>). For batch indexing with very large
/// ram buffers use <code>false</code>
/// </summary>
public const bool DEFAULT_USE_COMPOUND_FILE_SYSTEM = true;
/// <summary>
/// Default value for calling <seealso cref="AtomicReader#checkIntegrity()"/> before
/// merging segments (set to <code>false</code>). You can set this
/// to <code>true</code> for additional safety.
/// </summary>
public const bool DEFAULT_CHECK_INTEGRITY_AT_MERGE = false;
/// <summary>
/// Sets the default (for any instance) maximum time to wait for a write lock
/// (in milliseconds).
/// </summary>
public static long DefaultWriteLockTimeout
{
set
{
WRITE_LOCK_TIMEOUT = value;
}
get
{
return WRITE_LOCK_TIMEOUT;
}
}
// indicates whether this config instance is already attached to a writer.
// not final so that it can be cloned properly.
private SetOnce<IndexWriter> Writer = new SetOnce<IndexWriter>();
/// <summary>
/// Sets the <seealso cref="IndexWriter"/> this config is attached to.
/// </summary>
/// <exception cref="AlreadySetException">
/// if this config is already attached to a writer. </exception>
internal IndexWriterConfig SetIndexWriter(IndexWriter writer)
{
this.Writer.Set(writer);
return this;
}
/// <summary>
/// Creates a new config that with defaults that match the specified
/// <seealso cref="LuceneVersion"/> as well as the default {@link
/// Analyzer}. If matchVersion is >= {@link
/// Version#LUCENE_32}, <seealso cref="TieredMergePolicy"/> is used
/// for merging; else <seealso cref="LogByteSizeMergePolicy"/>.
/// Note that <seealso cref="TieredMergePolicy"/> is free to select
/// non-contiguous merges, which means docIDs may not
/// remain monotonic over time. If this is a problem you
/// should switch to <seealso cref="LogByteSizeMergePolicy"/> or
/// <seealso cref="LogDocMergePolicy"/>.
/// </summary>
public IndexWriterConfig(LuceneVersion matchVersion, Analyzer analyzer)
: base(analyzer, matchVersion)
{
}
public object Clone()
{
try
{
IndexWriterConfig clone = (IndexWriterConfig)this.MemberwiseClone();
clone.Writer = (SetOnce<IndexWriter>)Writer.Clone();
// Mostly shallow clone, but do a deepish clone of
// certain objects that have state that cannot be shared
// across IW instances:
clone.delPolicy = (IndexDeletionPolicy)delPolicy.Clone();
clone.flushPolicy = (FlushPolicy)flushPolicy.Clone();
clone.indexerThreadPool = (DocumentsWriterPerThreadPool)indexerThreadPool.Clone();
// we clone the infoStream because some impls might have state variables
// such as line numbers, message throughput, ...
clone.infoStream = (InfoStream)infoStream.Clone();
clone.mergePolicy = (MergePolicy)mergePolicy.Clone();
clone.mergeScheduler = mergeScheduler.Clone();
return clone;
}
catch
{
// .NET port: no need to deal with checked exceptions here
throw;
}
}
/// <summary>
/// Specifies <seealso cref="OpenMode"/> of the index.
///
/// <p>Only takes effect when IndexWriter is first created.
/// </summary>
public IndexWriterConfig SetOpenMode(OpenMode_e? openMode)
{
if (openMode == null)
{
throw new System.ArgumentException("openMode must not be null");
}
this.openMode = openMode;
return this;
}
public override OpenMode_e? OpenMode
{
get
{
return openMode;
}
}
/// <summary>
/// Expert: allows an optional <seealso cref="IndexDeletionPolicy"/> implementation to be
/// specified. You can use this to control when prior commits are deleted from
/// the index. The default policy is <seealso cref="KeepOnlyLastCommitDeletionPolicy"/>
/// which removes all prior commits as soon as a new commit is done (this
/// matches behavior before 2.2). Creating your own policy can allow you to
/// explicitly keep previous "point in time" commits alive in the index for
/// some time, to allow readers to refresh to the new commit without having the
/// old commit deleted out from under them. this is necessary on filesystems
/// like NFS that do not support "delete on last close" semantics, which
/// Lucene's "point in time" search normally relies on.
/// <p>
/// <b>NOTE:</b> the deletion policy cannot be null.
///
/// <p>Only takes effect when IndexWriter is first created.
/// </summary>
public IndexWriterConfig SetIndexDeletionPolicy(IndexDeletionPolicy deletionPolicy)
{
if (deletionPolicy == null)
{
throw new System.ArgumentException("indexDeletionPolicy must not be null");
}
this.delPolicy = deletionPolicy;
return this;
}
public override IndexDeletionPolicy DelPolicy
{
get
{
return delPolicy;
}
}
/// <summary>
/// Expert: allows to open a certain commit point. The default is null which
/// opens the latest commit point.
///
/// <p>Only takes effect when IndexWriter is first created.
/// </summary>
public IndexWriterConfig SetIndexCommit(IndexCommit commit)
{
this.Commit = commit;
return this;
}
public override IndexCommit IndexCommit
{
get
{
return Commit;
}
}
/// <summary>
/// Expert: set the <seealso cref="Similarity"/> implementation used by this IndexWriter.
/// <p>
/// <b>NOTE:</b> the similarity cannot be null.
///
/// <p>Only takes effect when IndexWriter is first created.
/// </summary>
public IndexWriterConfig SetSimilarity(Similarity similarity)
{
if (similarity == null)
{
throw new System.ArgumentException("similarity must not be null");
}
this.similarity = similarity;
return this;
}
public override Similarity Similarity
{
get
{
return similarity;
}
}
/// <summary>
/// Expert: sets the merge scheduler used by this writer. The default is
/// <seealso cref="ConcurrentMergeScheduler"/>.
/// <p>
/// <b>NOTE:</b> the merge scheduler cannot be null.
///
/// <p>Only takes effect when IndexWriter is first created.
/// </summary>
public IndexWriterConfig SetMergeScheduler(IMergeScheduler mergeScheduler)
{
if (mergeScheduler == null)
{
throw new System.ArgumentException("mergeScheduler must not be null");
}
this.mergeScheduler = mergeScheduler;
return this;
}
public override IMergeScheduler MergeScheduler
{
get
{
return mergeScheduler;
}
}
/// <summary>
/// Sets the maximum time to wait for a write lock (in milliseconds) for this
/// instance. You can change the default value for all instances by calling
/// <seealso cref="#setDefaultWriteLockTimeout(long)"/>.
///
/// <p>Only takes effect when IndexWriter is first created.
/// </summary>
public IndexWriterConfig SetWriteLockTimeout(long writeLockTimeout)
{
this.writeLockTimeout = writeLockTimeout;
return this;
}
public override long WriteLockTimeout
{
get
{
return writeLockTimeout;
}
}
/// <summary>
/// Expert: <seealso cref="MergePolicy"/> is invoked whenever there are changes to the
/// segments in the index. Its role is to select which merges to do, if any,
/// and return a <seealso cref="MergePolicy.MergeSpecification"/> describing the merges.
/// It also selects merges to do for forceMerge.
///
/// <p>Only takes effect when IndexWriter is first created.
/// </summary>
public IndexWriterConfig SetMergePolicy(MergePolicy mergePolicy)
{
if (mergePolicy == null)
{
throw new System.ArgumentException("mergePolicy must not be null");
}
this.mergePolicy = mergePolicy;
return this;
}
/// <summary>
/// Set the <seealso cref="Codec"/>.
///
/// <p>
/// Only takes effect when IndexWriter is first created.
/// </summary>
public IndexWriterConfig SetCodec(Codec codec)
{
if (codec == null)
{
throw new System.ArgumentException("codec must not be null");
}
this.codec = codec;
return this;
}
public override Codec Codec
{
get
{
return codec;
}
}
public override MergePolicy MergePolicy
{
get
{
return mergePolicy;
}
}
/// <summary>
/// Expert: Sets the <seealso cref="DocumentsWriterPerThreadPool"/> instance used by the
/// IndexWriter to assign thread-states to incoming indexing threads. If no
/// <seealso cref="DocumentsWriterPerThreadPool"/> is set <seealso cref="IndexWriter"/> will use
/// <seealso cref="ThreadAffinityDocumentsWriterThreadPool"/> with max number of
/// thread-states set to <seealso cref="#DEFAULT_MAX_THREAD_STATES"/> (see
/// <seealso cref="#DEFAULT_MAX_THREAD_STATES"/>).
/// </p>
/// <p>
/// NOTE: The given <seealso cref="DocumentsWriterPerThreadPool"/> instance must not be used with
/// other <seealso cref="IndexWriter"/> instances once it has been initialized / associated with an
/// <seealso cref="IndexWriter"/>.
/// </p>
/// <p>
/// NOTE: this only takes effect when IndexWriter is first created.</p>
/// </summary>
public IndexWriterConfig SetIndexerThreadPool(DocumentsWriterPerThreadPool threadPool)
{
if (threadPool == null)
{
throw new System.ArgumentException("threadPool must not be null");
}
this.indexerThreadPool = threadPool;
return this;
}
public override DocumentsWriterPerThreadPool IndexerThreadPool
{
get
{
return indexerThreadPool;
}
}
/// <summary>
/// Sets the max number of simultaneous threads that may be indexing documents
/// at once in IndexWriter. Values < 1 are invalid and if passed
/// <code>maxThreadStates</code> will be set to
/// <seealso cref="#DEFAULT_MAX_THREAD_STATES"/>.
///
/// <p>Only takes effect when IndexWriter is first created.
/// </summary>
public IndexWriterConfig SetMaxThreadStates(int maxThreadStates)
{
this.indexerThreadPool = new ThreadAffinityDocumentsWriterThreadPool(maxThreadStates);
return this;
}
public override int MaxThreadStates
{
get
{
try
{
return ((ThreadAffinityDocumentsWriterThreadPool)indexerThreadPool).MaxThreadStates;
}
catch (System.InvalidCastException cce)
{
throw new InvalidOperationException(cce.Message, cce);
}
}
}
/// <summary>
/// By default, IndexWriter does not pool the
/// SegmentReaders it must open for deletions and
/// merging, unless a near-real-time reader has been
/// obtained by calling <seealso cref="DirectoryReader#open(IndexWriter, boolean)"/>.
/// this method lets you enable pooling without getting a
/// near-real-time reader. NOTE: if you set this to
/// false, IndexWriter will still pool readers once
/// <seealso cref="DirectoryReader#open(IndexWriter, boolean)"/> is called.
///
/// <p>Only takes effect when IndexWriter is first created.
/// </summary>
public IndexWriterConfig SetReaderPooling(bool readerPooling)
{
this.readerPooling = readerPooling;
return this;
}
public override bool ReaderPooling
{
get
{
return readerPooling;
}
}
/// <summary>
/// Expert: sets the <seealso cref="DocConsumer"/> chain to be used to process documents.
///
/// <p>Only takes effect when IndexWriter is first created.
/// </summary>
public IndexWriterConfig SetIndexingChain(IndexingChain indexingChain)
{
if (indexingChain == null)
{
throw new System.ArgumentException("indexingChain must not be null");
}
this.indexingChain = indexingChain;
return this;
}
public override IndexingChain IndexingChain
{
get
{
return indexingChain;
}
}
/// <summary>
/// Expert: Controls when segments are flushed to disk during indexing.
/// The <seealso cref="FlushPolicy"/> initialized during <seealso cref="IndexWriter"/> instantiation and once initialized
/// the given instance is bound to this <seealso cref="IndexWriter"/> and should not be used with another writer. </summary>
/// <seealso cref= #setMaxBufferedDeleteTerms(int) </seealso>
/// <seealso cref= #setMaxBufferedDocs(int) </seealso>
/// <seealso cref= #setRAMBufferSizeMB(double) </seealso>
public IndexWriterConfig SetFlushPolicy(FlushPolicy flushPolicy)
{
if (flushPolicy == null)
{
throw new System.ArgumentException("flushPolicy must not be null");
}
this.flushPolicy = flushPolicy;
return this;
}
/// <summary>
/// Expert: Sets the maximum memory consumption per thread triggering a forced
/// flush if exceeded. A <seealso cref="DocumentsWriterPerThread"/> is forcefully flushed
/// once it exceeds this limit even if the <seealso cref="#getRAMBufferSizeMB()"/> has
/// not been exceeded. this is a safety limit to prevent a
/// <seealso cref="DocumentsWriterPerThread"/> from address space exhaustion due to its
/// internal 32 bit signed integer based memory addressing.
/// The given value must be less that 2GB (2048MB)
/// </summary>
/// <seealso cref= #DEFAULT_RAM_PER_THREAD_HARD_LIMIT_MB </seealso>
public IndexWriterConfig SetRAMPerThreadHardLimitMB(int perThreadHardLimitMB)
{
if (perThreadHardLimitMB <= 0 || perThreadHardLimitMB >= 2048)
{
throw new System.ArgumentException("PerThreadHardLimit must be greater than 0 and less than 2048MB");
}
this.PerThreadHardLimitMB = perThreadHardLimitMB;
return this;
}
public override int RAMPerThreadHardLimitMB
{
get
{
return PerThreadHardLimitMB;
}
}
public override FlushPolicy FlushPolicy
{
get
{
return flushPolicy;
}
}
public override InfoStream InfoStream
{
get
{
return infoStream;
}
}
public override Analyzer Analyzer
{
get
{
return base.Analyzer;
}
}
public override int MaxBufferedDeleteTerms
{
get
{
return base.MaxBufferedDeleteTerms;
}
}
public override int MaxBufferedDocs
{
get
{
return base.MaxBufferedDocs;
}
}
public override IndexReaderWarmer MergedSegmentWarmer
{
get
{
return base.MergedSegmentWarmer;
}
}
public override double RAMBufferSizeMB
{
get
{
return base.RAMBufferSizeMB;
}
}
public override int ReaderTermsIndexDivisor
{
get
{
return base.ReaderTermsIndexDivisor;
}
}
public override int TermIndexInterval
{
get
{
return base.TermIndexInterval;
}
}
/// <summary>
/// Information about merges, deletes and a
/// message when maxFieldLength is reached will be printed
/// to this. Must not be null, but <seealso cref="InfoStream#NO_OUTPUT"/>
/// may be used to supress output.
/// </summary>
public IndexWriterConfig SetInfoStream(InfoStream infoStream)
{
if (infoStream == null)
{
throw new System.ArgumentException("Cannot set InfoStream implementation to null. " + "To disable logging use InfoStream.NO_OUTPUT");
}
this.infoStream = infoStream;
return this;
}
/// <summary>
/// Convenience method that uses <seealso cref="PrintStreamInfoStream"/>. Must not be null.
/// </summary>
public IndexWriterConfig SetInfoStream(TextWriter printStream)
{
if (printStream == null)
{
throw new System.ArgumentException("printStream must not be null");
}
return SetInfoStream(new PrintStreamInfoStream(printStream));
}
public IndexWriterConfig SetMaxBufferedDeleteTerms(int maxBufferedDeleteTerms)
{
return (IndexWriterConfig)base.SetMaxBufferedDeleteTerms(maxBufferedDeleteTerms);
}
public IndexWriterConfig SetMaxBufferedDocs(int maxBufferedDocs)
{
return (IndexWriterConfig)base.SetMaxBufferedDocs(maxBufferedDocs);
}
public IndexWriterConfig SetMergedSegmentWarmer(IndexReaderWarmer mergeSegmentWarmer)
{
return (IndexWriterConfig)base.SetMergedSegmentWarmer(mergeSegmentWarmer);
}
public IndexWriterConfig SetRAMBufferSizeMB(double ramBufferSizeMB)
{
return (IndexWriterConfig)base.SetRAMBufferSizeMB(ramBufferSizeMB);
}
public IndexWriterConfig SetReaderTermsIndexDivisor(int divisor)
{
return (IndexWriterConfig)base.SetReaderTermsIndexDivisor(divisor);
}
public IndexWriterConfig SetTermIndexInterval(int interval)
{
return (IndexWriterConfig)base.SetTermIndexInterval(interval);
}
public IndexWriterConfig SetUseCompoundFile(bool useCompoundFile)
{
return (IndexWriterConfig)base.SetUseCompoundFile(useCompoundFile);
}
public IndexWriterConfig SetCheckIntegrityAtMerge(bool checkIntegrityAtMerge)
{
return (IndexWriterConfig)base.SetCheckIntegrityAtMerge(checkIntegrityAtMerge);
}
public override string ToString()
{
StringBuilder sb = new StringBuilder(base.ToString());
sb.Append("writer=").Append(Writer).Append("\n");
return sb.ToString();
}
}
}
| |
// 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 Android.App;
using Android.OS;
using Android.Views;
using Android.Widget;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Rasters;
using Esri.ArcGISRuntime.UI.Controls;
using System;
using System.Collections.Generic;
using ArcGISRuntime.Samples.Managers;
namespace ArcGISRuntime.Samples.ChangeBlendRenderer
{
[Activity (ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
[Shared.Attributes.OfflineData("7c4c679ab06a4df19dc497f577f111bd","caeef9aa78534760b07158bb8e068462")]
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Blend renderer",
category: "Layers",
description: "Blend a hillshade with a raster by specifying the elevation data. The resulting raster looks similar to the original raster, but with some terrain shading, giving it a textured look.",
instructions: "Choose and adjust the altitude, azimuth, slope type, and color ramp type settings to update the image.",
tags: new[] { "Elevation", "Hillshade", "RasterLayer", "color ramp", "elevation", "image", "visualization" })]
public class ChangeBlendRenderer : Activity
{
// Global reference to a label for Altitude
private TextView _Label_Altitude;
// Global reference to the slider (SeekBar) where the user can modify the Altitude
private SeekBar _Slider_Altitude;
// Global reference to a label for Azimuth
private TextView _Label_Azimuth;
// Global reference to the slider (SeekBar) where the user can modify the Azimuth
private SeekBar _Slider_Azimuth;
// Global reference to a label for SlopeTypes
private TextView _Label_SlopeTypes;
// Global reference to a label for ColorRamps
private TextView _Label_ColorRamps;
// Global reference to button the user clicks to change the stretch renderer on the raster
private Button _Button_UpdateRenderer;
// Global reference to the MapView used in the sample
private MapView _myMapView;
// Global variable for the SlopeType being used - changeable when the user make
// a selection, set the default value to "Degree"
private string _mySlopeTypeChoice = "Degree";
// Global variable for the ColorRamp being used - changeable when the user make
// a selection, set the default value to "Elevation"
private string _myColorRampChoice = "Elevation";
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
Title = "Blend renderer";
// Create the layout
CreateLayout();
// Initialize the app
Initialize();
}
private void CreateLayout()
{
// Create a stack layout
LinearLayout layout = new LinearLayout(this) { Orientation = Orientation.Vertical };
// Create label that displays Altitude
_Label_Altitude = new TextView(this)
{
Text = "Altitude"
};
layout.AddView(_Label_Altitude);
// Create a slider (SeekBar) that the user can modify the Altitude
_Slider_Altitude = new SeekBar(this);
layout.AddView(_Slider_Altitude);
// Create label that displays Azimuth
_Label_Azimuth = new TextView(this)
{
Text = "Azimuth"
};
layout.AddView(_Label_Azimuth);
// Create a slider (SeekBar) that the user can modify the Azimuth
_Slider_Azimuth = new SeekBar(this);
layout.AddView(_Slider_Azimuth);
// Create label that displays the SlopeType - set the default label to "Degree"
_Label_SlopeTypes = new TextView(this)
{
Text = _mySlopeTypeChoice
};
layout.AddView(_Label_SlopeTypes);
// Create button to choose a specific SlopeType
Button slopeTypesButton = new Button(this)
{
Text = "SlopeTypes"
};
slopeTypesButton.Click += SlopeTypesButton_Click;
layout.AddView(slopeTypesButton);
// Create label that displays the ColorRamp - set the default label to "Elevation"
_Label_ColorRamps = new TextView(this)
{
Text = _myColorRampChoice
};
layout.AddView(_Label_ColorRamps);
// Create button to choose a specific ColorRamp
Button colorRampsButton = new Button(this)
{
Text = "Color Ramps"
};
colorRampsButton.Click += ColorRampsButton_Click;
layout.AddView(colorRampsButton);
// Create button to change stretch renderer of the raster, wire-up the touch/click
// event handler for the button
_Button_UpdateRenderer = new Button(this)
{
Text = "Update Renderer"
};
_Button_UpdateRenderer.Click += OnUpdateRendererClicked;
layout.AddView(_Button_UpdateRenderer);
_Button_UpdateRenderer.Enabled = false;
// Create a map view and add it to the layout
_myMapView = new MapView(this);
layout.AddView(_myMapView);
// Set the layout as the sample view
SetContentView(layout);
}
private void ColorRampsButton_Click(object sender, EventArgs e)
{
// Create a local variable for the ColorRamps button
Button myButton_ColorRamps = (Button)sender;
// Create menu to show ColorRamp options
PopupMenu myPopupMenu_ColorRamps = new PopupMenu(this, myButton_ColorRamps);
myPopupMenu_ColorRamps.MenuItemClick += OnColorRampsMenuItemClicked;
// Create a string array of ColorRamp Enumerations the user can pick from
string[] myColorRamps = Enum.GetNames(typeof(PresetColorRampType));
// Create menu options from the array of ColorRamp choices
foreach (string myColorRamp in myColorRamps)
myPopupMenu_ColorRamps.Menu.Add(myColorRamp);
// Show the popup menu in the view
myPopupMenu_ColorRamps.Show();
}
private async void Initialize()
{
try
{
// Set the altitude slider min/max and initial value (minimum is always 0 - do
// not set _Altitude_Slider.Min = 0)
_Slider_Altitude.Max = 90;
_Slider_Altitude.Progress = 45;
// Set the azimuth slider min/max and initial value (minimum is always 0 - do
// not set _AZimuth_Slider.Min = 0)
_Slider_Azimuth.Max = 360;
_Slider_Azimuth.Progress = 180;
// Load the raster file using a path on disk
Raster myRasterImagery = new Raster(GetRasterPath_Imagery());
// Create the raster layer from the raster
RasterLayer myRasterLayerImagery = new RasterLayer(myRasterImagery);
// Create a new map using the raster layer as the base map
Map myMap = new Map(new Basemap(myRasterLayerImagery));
// Wait for the layer to load - this enabled being able to obtain the extent information
// of the raster layer
await myRasterLayerImagery.LoadAsync();
// Create a new EnvelopeBuilder from the full extent of the raster layer
EnvelopeBuilder myEnvelopBuilder = new EnvelopeBuilder(myRasterLayerImagery.FullExtent);
// Zoom in the extent just a bit so that raster layer encompasses the entire viewable
// area of the map
myEnvelopBuilder.Expand(0.75);
// Set the viewpoint of the map to the EnvelopeBuilder's extent
myMap.InitialViewpoint = new Viewpoint(myEnvelopBuilder.ToGeometry().Extent);
// Add map to the map view
_myMapView.Map = myMap;
// Wait for the map to load
await myMap.LoadAsync();
// Enable the 'Update Renderer' button now that the map has loaded
_Button_UpdateRenderer.Enabled = true;
}
catch (Exception ex)
{
new AlertDialog.Builder(this).SetMessage(ex.ToString()).SetTitle("Error").Show();
}
}
private void SlopeTypesButton_Click(object sender, EventArgs e)
{
// Create a local variable for the SlopeTypes button
Button myButton_SlopeTypes = (Button)sender;
// Create menu to show SlopeType options
PopupMenu myPopupMenu_SlopeTypes = new PopupMenu(this, myButton_SlopeTypes);
myPopupMenu_SlopeTypes.MenuItemClick += OnSlopeTypesMenuItemClicked;
// Create a string array of SlopeType Enumerations the user can pick from
string[] mySlopeTypes = Enum.GetNames(typeof(SlopeType));
// Create menu options from the array of SlopeType choices
foreach (string mySlopeType in mySlopeTypes)
myPopupMenu_SlopeTypes.Menu.Add(mySlopeType);
// Show the popup menu in the view
myPopupMenu_SlopeTypes.Show();
}
private void OnSlopeTypesMenuItemClicked(object sender, PopupMenu.MenuItemClickEventArgs e)
{
// Get user selected SlopeType choice title from the selected item
_mySlopeTypeChoice = e.Item.TitleCondensedFormatted.ToString();
// Set the text of the label to be the name of the SlopeType choice
_Label_SlopeTypes.Text = _mySlopeTypeChoice;
}
private void OnColorRampsMenuItemClicked(object sender, PopupMenu.MenuItemClickEventArgs e)
{
// Get user selected ColorRamp choice title from the selected item
_myColorRampChoice = e.Item.TitleCondensedFormatted.ToString();
// Set the text of the label to be the name of the ColorRamp choice
_Label_ColorRamps.Text = _myColorRampChoice;
}
private void OnUpdateRendererClicked(object sender, EventArgs e)
{
// Define the RasterLayer that will be used to display in the map
RasterLayer rasterLayer_ForDisplayInMap;
// Define the ColorRamp that will be used by the BlendRenderer
ColorRamp myColorRamp;
// Based on ColorRamp type chosen by the user, create a different
// RasterLayer and define the appropriate ColorRamp option
if (_myColorRampChoice == "None")
{
// The user chose not to use a specific ColorRamp, therefore
// need to create a RasterLayer based on general imagery (ie. Shasta.tif)
// for display in the map and use null for the ColorRamp as one of the
// parameters in the BlendRenderer constructor
// Load the raster file using a path on disk
Raster raster_Imagery = new Raster(GetRasterPath_Imagery());
// Create the raster layer from the raster
rasterLayer_ForDisplayInMap = new RasterLayer(raster_Imagery);
// Set up the ColorRamp as being null
myColorRamp = null;
}
else
{
// The user chose a specific ColorRamp (options: are Elevation, DemScreen, DemLight),
// therefore create a RasterLayer based on an imagery with elevation
// (ie. Shasta_Elevation.tif) for display in the map. Also create a ColorRamp
// based on the user choice, translated into an Enumeration, as one of the parameters
// in the BlendRenderer constructor
// Load the raster file using a path on disk
Raster raster_Elevation = new Raster(GetRasterPath_Elevation());
// Create the raster layer from the raster
rasterLayer_ForDisplayInMap = new RasterLayer(raster_Elevation);
// Create a ColorRamp based on the user choice, translated into an Enumeration
PresetColorRampType myPresetColorRampType = (PresetColorRampType)Enum.Parse(typeof(PresetColorRampType), _myColorRampChoice);
myColorRamp = ColorRamp.Create(myPresetColorRampType, 256);
}
// Define the parameters used by the BlendRenderer constructor
Raster raster_ForMakingBlendRenderer = new Raster(GetRasterPath_Elevation());
IEnumerable<double> myOutputMinValues = new List<double> { 9 };
IEnumerable<double> myOutputMaxValues = new List<double> { 255 };
IEnumerable<double> mySourceMinValues = new List<double>();
IEnumerable<double> mySourceMaxValues = new List<double>();
IEnumerable<double> myNoDataValues = new List<double>();
IEnumerable<double> myGammas = new List<double>();
SlopeType mySlopeType = (SlopeType)Enum.Parse(typeof(SlopeType), _mySlopeTypeChoice);
BlendRenderer myBlendRenderer = new BlendRenderer(
raster_ForMakingBlendRenderer, // elevationRaster - Raster based on a elevation source
myOutputMinValues, // outputMinValues - Output stretch values, one for each band
myOutputMaxValues, // outputMaxValues - Output stretch values, one for each band
mySourceMinValues, // sourceMinValues - Input stretch values, one for each band
mySourceMaxValues, // sourceMaxValues - Input stretch values, one for each band
myNoDataValues, // noDataValues - NoData values, one for each band
myGammas, // gammas - Gamma adjustment
myColorRamp, // colorRamp - ColorRamp object to use, could be null
_Slider_Altitude.Progress, // altitude - Altitude angle of the light source
_Slider_Azimuth.Progress, // azimuth - Azimuth angle of the light source, measured clockwise from north
1, // zfactor - Factor to convert z unit to x,y units, default is 1
mySlopeType, // slopeType - Slope Type
1, // pixelSizeFactor - Pixel size factor, default is 1
1, // pixelSizePower - Pixel size power value, default is 1
8); // outputBitDepth - Output bit depth, default is 8-bi
// Set the RasterLayer.Renderer to be the BlendRenderer
rasterLayer_ForDisplayInMap.Renderer = myBlendRenderer;
// Set the new base map to be the RasterLayer with the BlendRenderer applied
_myMapView.Map.Basemap = new Basemap(rasterLayer_ForDisplayInMap);
}
private static string GetRasterPath_Imagery()
{
return DataManager.GetDataFolder("7c4c679ab06a4df19dc497f577f111bd", "raster-file", "Shasta.tif");
}
private static string GetRasterPath_Elevation()
{
return DataManager.GetDataFolder("caeef9aa78534760b07158bb8e068462", "Shasta_Elevation.tif");
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web.RegularExpressions;
using System.Web.UI;
using System.Web.UI.Design;
using System.Web.UI.WebControls;
using GuruComponents.Netrix.ComInterop;
using GuruComponents.Netrix.Designer;
using GuruComponents.Netrix.Events;
using GuruComponents.Netrix.PlugIns;
using GuruComponents.Netrix.WebEditing.Elements;
using GuruComponents.Netrix.HtmlFormatting;
using GuruComponents.Netrix.HtmlFormatting.Elements;
using WebFormsReferenceManager = GuruComponents.Netrix.Designer.WebFormsReferenceManager;
namespace GuruComponents.Netrix.AspDotNetDesigner
{
/// <summary>
/// AspDotNet (ASP.NET) control designer extender provider.
/// </summary>
/// <remarks>
/// This plug-in extends NetRix so it can handle webcontrols, htmlcontrols and usercontrols from the ASP.NET namespaces.
/// <para>
/// The intention of this plug-in is providing a low level access to a design time environment to display ASP.NET controls,
/// user controls and types derived from System.Web.UI.WebControl. It's not intended to build a whole IDE like Visual
/// Studio.NET. Therefore a couple of rules are applying:
/// <list type="bullet">
/// <item>Documents loaded must appear as simple HTML documents, e.g. neither as ASPX nor ASCX.</item>
/// <item>Directives defined in the document header has to be stripped out and the directives has to be defined separatly.</item>
/// <item>The host application is responsible for any non-HTML parts of an document and is supposed to define a decument engine to handle embedded directives.</item>
/// </list>
/// The usage of user controls requires several steps, e.g. the registration of namespaces and control names, as well as
/// instructions for the formatter and registration of the type. The type is required to create objects on-the-fly and
/// use them internally. The assembly where the type is defined must be part of the app domain and loadable at runtime.
/// </para>
/// <para>
/// <b>Basic Steps to Show and Edit ASP.NET based Controls:</b><br/>
/// Before you can show ASP.NET controls and derived objects, like user controls, you must prepare several steps to get the
/// designer running:
/// <list type="bullet">
/// <item>Have an element class that you wish to use. For legacy ASP.NET controls this is already done, you can use types from .NET framework.</item>
/// <item>For private elements, implement a user control, derive from WebControl, and attach a designer.</item>
/// <item>Register the private element in both, the AspDotNetDesigner plugin as assembly and in HtmlEditor for formatting.</item>
/// <item></item>
/// </list>
/// Registering the element is a two-step procedure. Both steps take place before loading (or first time after constructor).
/// First, add a handler to get the right call from <see cref="RegisterDirectives"/> event:
/// <code>
/// aspDotNetDesigner1.RegisterDirectives += new EventHandler(aspDotNetDesigner1_RegisterDirectives);
/// </code>
/// Then, in the handler, add your element:
/// <code>
/// RegisterDirective directive = new RegisterDirective("uc", "MyUserControl", typeof(MyUserControl).AssemblyQualifiedName, typeof(MyUserControl), true);
/// aspDotNetDesigner1.RegisterDirective(directive, htmlEditor1);
/// AspTagInfo tagInfo = new AspTagInfo("uc:MyUserControl", FormattingFlags.Xml);
/// htmlEditor1.RegisterElement(tagInfo, typeof(MyUserControl));
/// </code>
/// In this example, "uc" is the alias used in the document for the element "MyUserControl". Also the class has the same name
/// "MyUserControl" (but it could have a different name). <see cref="AddRegisterDirective"/> registers the information usually
/// found in the <%@ Register %> statement in the document. If you're working with ASCX or ASPX documents it's necessary
/// to transform them first, following these steps:
/// <list type="bullet">
/// <item>Strip out any content above the HTML tag.</item>
/// <item>Add HTML, HEAD and BODY section if not already there (especially for ASCX files), and load content into BODY.</item>
/// <item>Scan any Register directives and call <see cref="AddRegisterDirective"/> as described below.</item>
/// <item>Remove any Control or Page directives. This is part of the host application and not supported by AspDotNetDesigner class.</item>
/// <item>Load the prepared document and call <see cref="AddRegisterDirective"/> during Loading event (see above).</item>
/// </list>
/// After document has been edited by user just get body content by calling InnerHtml and restore the document structure.
/// It's also possible to use the formatter separatly to format the content and get XHTML back.
/// </para>
/// <para>
/// Probably showing the webcontrols within the PropertyGrid is a good solution for a VS.NET like IDE. If you want to
/// do so, just connect the event HtmlElementChanged and handle the current control. However, to avoid conflicts
/// with <see cref="IElement"/> based objects, two properties allow access:
/// <code>
/// if (e.CurrentElement == null)
/// {
/// propertyGrid1.SelectedObject = e.CurrentControl;
/// }
/// else
/// {
/// propertyGrid1.SelectedObject = e.CurrentElement;
/// }
/// </code>
/// All elements handled internally by NetRix derive from <see cref="IElement"/>. Foreign sources for components,
/// derived from <see cref="IComponent"/> and subsequently implementing <see cref="Control"/> are handled properly
/// by the infrastructure, however, all internal procedures based on <see cref="IElement"/> can not handle this.
/// For that reason, some event argument classes provide distinguish access to "controls" and "native controls".
/// </para>
/// </remarks>
/// <seealso cref="IHtmlEditor"/>
/// <seealso cref="IHtmlEditor.RegisterElement">RegisterElement (IHtmlEditor)</seealso>
/// <seealso cref="AddRegisterDirective"/>
/// <seealso cref="AspTagInfo"/>
[ToolboxItem(true)]
[ToolboxBitmap(typeof(AspDotNetDesigner), "Resources.ToolBox.ico")]
[ProvideProperty("AspDotNetDesigner", "GuruComponents.Netrix.IHtmlEditor")]
public class AspDotNetDesigner : Component, IExtenderProvider, IPlugIn
{
private Hashtable properties;
private static readonly DirectiveRegex dirRegex = new DirectiveRegex();
private static readonly ServerTagsRegex tagRegex = new ServerTagsRegex();
private static readonly TagRegex usertagRegex = new TagRegex();
private static Dictionary<IHtmlEditor, List<IRegisterDirective>> preRegistered;
private static Dictionary<IHtmlEditor, List<IDirective>> pageDirectives;
private static Dictionary<IHtmlEditor, List<IDirective>> controlDirectives;
private static Dictionary<IHtmlEditor, string> basePath;
/// <summary>
/// Default Constructor supports design time behavior.
/// </summary>
public AspDotNetDesigner()
{
properties = new Hashtable();
preRegistered = new Dictionary<IHtmlEditor, List<IRegisterDirective>>();
pageDirectives = new Dictionary<IHtmlEditor, List<IDirective>>();
controlDirectives = new Dictionary<IHtmlEditor, List<IDirective>>();
basePath = new Dictionary<IHtmlEditor, string>();
}
/// <summary>
/// Default Constructor supports design time behavior
/// </summary>
/// <param name="parent"></param>
public AspDotNetDesigner(IContainer parent)
: this()
{
properties = new Hashtable();
if (parent != null)
{
parent.Add(this);
}
}
private DesignerProperties EnsurePropertiesExists(IHtmlEditor key)
{
DesignerProperties p = (DesignerProperties)properties[key];
if (p == null)
{
p = new DesignerProperties();
properties[key] = p;
}
return p;
}
# region +++++ Block: AspDotNetDesigner
/// <summary>
/// Returns the designer's properties at design time.
/// </summary>
/// <param name="htmlEditor"></param>
/// <returns></returns>
[ExtenderProvidedProperty(), Category("NetRix Component"), Description("AspDotNetDesigner Properties")]
[TypeConverter(typeof(ExpandableObjectConverter))]
public DesignerProperties GetAspDotNetDesigner(IHtmlEditor htmlEditor)
{
return this.EnsurePropertiesExists(htmlEditor);
}
/// <summary>
/// Sets the designer's properties at design time.
/// </summary>
/// <param name="htmlEditor"></param>
/// <param name="Properties"></param>
public void SetAspDotNetDesigner(IHtmlEditor htmlEditor, DesignerProperties Properties)
{
EnsurePropertiesExists(htmlEditor).LoadAscx = true;
EnsurePropertiesExists(htmlEditor).Active = Properties.Active;
EnsurePropertiesExists(htmlEditor).ExpandUserControls = Properties.ExpandUserControls;
EnsurePropertiesExists(htmlEditor).RequireServerAttribute = Properties.ExpandUserControls;
RegisterAll(htmlEditor);
// Commands
// activate behaviors when document is ready, otherwise it will fail
htmlEditor.Loading += new LoadEventHandler(htmlEditor_Loading);
// Register
htmlEditor.RegisterPlugIn(this);
}
private bool firstTimeRegistered = false;
/// <summary>
/// Called by Host to notify the document state. You should not call this from user code.
/// </summary>
/// <param name="htmlEditor"></param>
public void NotifyReadyStateCompleted(IHtmlEditor htmlEditor)
{
if (!firstTimeRegistered)
{
RegisterAll(htmlEditor);
firstTimeRegistered = true;
htmlEditor.AddEditDesigner(GlobalEvents.GetGlobalEventsFactory(htmlEditor));
}
}
// After ResetDesiredProperties/Initialize and before Loading!
void htmlEditor_Loading(object sender, LoadEventArgs e)
{
IHtmlEditor htmlEditor = (IHtmlEditor)sender;
RegisterAll(htmlEditor);
if (preRegistered.Count > 0)
{
// Register preregistered directives for the editor which invokes the loader
foreach (KeyValuePair<IHtmlEditor, List<IRegisterDirective>> kv in preRegistered)
{
if (htmlEditor.Equals(kv.Key))
{
foreach (IRegisterDirective directive in kv.Value)
{
AddRegisterDirective(directive, htmlEditor);
// Register ASCX
string f = String.Format("{0}:{1}", directive.TagPrefix, directive.TagName);
AscxTagInfo a = new AscxTagInfo(f, FormattingFlags.Xml, ElementType.Block);
htmlEditor.RegisterElement(a, typeof(UserControl));
}
break;
}
}
}
}
private void RegisterAll(IHtmlEditor htmlEditor)
{
RegisterDirectiveCollection directives = new RegisterDirectiveCollection();
// Register Services
if (htmlEditor.ServiceProvider.GetService(typeof(IWebFormReferenceManager)) == null)
{
// Directives gives as a hint how to persist the controls
IReferenceManager wrm = new WebFormsReferenceManager(htmlEditor, directives); //, EnsureBehavior(htmlEditor));
wrm.DirectiveAdded += new DirectiveEventHandler(wrm_DirectiveAdded);
htmlEditor.ServiceProvider.AddService(typeof(IWebFormReferenceManager), wrm);
}
if (htmlEditor.ServiceProvider.GetService(typeof(IUserControlTypeResolutionService)) == null)
htmlEditor.ServiceProvider.AddService(typeof(IUserControlTypeResolutionService), new UserControlTypeResolution(htmlEditor));
if (htmlEditor.ServiceProvider.GetService(typeof(INameCreationService)) == null)
htmlEditor.ServiceProvider.AddService(typeof(INameCreationService), new NameCreationService(htmlEditor));
DictionaryService ds = new DictionaryService();
if (htmlEditor.ServiceProvider.GetService(typeof(IDictionaryService)) != null)
{
htmlEditor.ServiceProvider.RemoveService(typeof(IDictionaryService));
}
htmlEditor.ServiceProvider.AddService(typeof(IDictionaryService), ds);
// Register Namespaces
if (EnsurePropertiesExists(htmlEditor).Active)
{
htmlEditor.RegisterNamespace("asp", typeof(DesignTimeBehavior));
// Register private namespaces for custom elements
if (EnsurePropertiesExists(htmlEditor).Namespaces != null)
{
foreach (string ns in EnsurePropertiesExists(htmlEditor).Namespaces)
{
string[] nsParts = ns.Split(',');
if (nsParts.Length == 2)
{
htmlEditor.RegisterNamespace(nsParts[0], nsParts[1], typeof(DesignTimeBehavior));
}
else
{
htmlEditor.RegisterNamespace(ns, typeof(DesignTimeBehavior));
}
}
}
}
// Register all standard asp:controls for formatter
Assembly webUI = typeof(Label).Assembly;
foreach (Type t in webUI.GetTypes())
{
if (t.IsClass && (t.IsSubclassOf(typeof(WebControl)) || t.IsSubclassOf(typeof(Control))) && !t.IsAbstract)
{
object[] at = t.GetCustomAttributes(true);
bool checkNonVisual = false; // at the moment we don't support non visuals
foreach (object a in at)
{
if (a is NonVisualControlAttribute)
{
checkNonVisual = true;
break;
}
}
if (checkNonVisual) continue;
AspTagInfo tagInfo;
tagInfo = new AspTagInfo(t.Name, FormattingFlags.None, WhiteSpaceType.NotSignificant, WhiteSpaceType.NotSignificant, ElementType.Any);
htmlEditor.RegisterElement(tagInfo, t);
}
}
// Ask the host to add more
InvokeRegisterDirectives();
}
void GlobalEvents_PreHandleEvent(object sender, ElementEventArgs e)
{
//System.Diagnostics.Debug.WriteLine(e.EventObj.type, ((System.Windows.Forms.UserControl) sender).Name);
}
void GlobalEvents_PostHandleEvent(object sender, ElementEventArgs e)
{
//System.Diagnostics.Debug.WriteLine(e.EventObj.type, ((System.Windows.Forms.UserControl) sender).Name);
}
void wrm_DirectiveAdded(object sender, DirectiveEventArgs e)
{
if (DirectiveAdded != null)
{
DirectiveAdded(sender, e);
}
}
/// <summary>
/// Assembly version
/// </summary>
[Browsable(true), ReadOnly(true)]
public string Version
{
get
{
return this.GetType().Assembly.GetName().Version.ToString();
}
}
/// <summary>
/// Supports property grid and VS designer
/// </summary>
/// <param name="htmlEditor"></param>
/// <returns></returns>
public bool ShouldSerializeAspDotNetDesigner(IHtmlEditor htmlEditor)
{
return true;
}
# endregion
#region IExtenderProvider Member
/// <summary>
/// Allows the extension of HTML Editor.
/// </summary>
/// <param name="extendee"></param>
/// <returns></returns>
public bool CanExtend(object extendee)
{
if (extendee is IHtmlEditor)
{
return true;
}
else
{
return false;
}
}
#endregion
/// <summary>
/// Overriden
/// </summary>
/// <returns></returns>
public override string ToString()
{
return "Click plus sign for details";
}
/// <summary>
/// Create a new element in the given editor control.
/// </summary>
/// <remarks>
/// Element types must be registered and well known before they could created. After creation the
/// element exists within the local element cache and the current document, but is not yet appended
/// to the DOM. It's recommended to add the element to the DOM using ElementDom functions like
/// AppendChild.
/// <para>
///
/// </para>
/// </remarks>
/// <param name="tagName">The tagname, including the alias (like 'asp:button').</param>
/// <param name="htmlEditor">The editor this element refers to.</param>
/// <returns>Returns the element or <c>null</c>, if creation fails. See remarks for reasons.</returns>
public Control CreateElement(string tagName, IHtmlEditor htmlEditor)
{
return CreateElement(tagName, htmlEditor, EnsurePropertiesExists(htmlEditor).RequireServerAttribute);
}
/// <summary>
/// Create a new element in the given editor control.
/// </summary>
/// <remarks>
/// Element types must be registered and well known before they could created. After creation the
/// element exists within the local element cache and the current document, but is not yet appended
/// to the DOM. It's recommended to add the element to the DOM using ElementDom functions like
/// AppendChild.
/// </remarks>
/// <param name="tagName">The tagname, including the alias (like 'asp:button').</param>
/// <param name="htmlEditor">The editor this element refers to.</param>
/// <param name="createRunatServerAttr">Creates the runat="server" attribute.</param>
/// <returns>Returns the element or <c>null</c>, if creation fails. See remarks for reasons.</returns>
public Control CreateElement(string tagName, IHtmlEditor htmlEditor, bool createRunatServerAttr)
{
Interop.IHTMLDocument2 doc = htmlEditor.GetActiveDocument(false);
Interop.IHTMLElement el = doc.CreateElement(tagName);
if (el != null)
{
INamespaceManager ns = (INamespaceManager)htmlEditor.ServiceProvider.GetService(typeof(INamespaceManager));
INameCreationService nc = (INameCreationService)htmlEditor.ServiceProvider.GetService(typeof(INameCreationService));
IDesignerHost dh = (IDesignerHost)htmlEditor.ServiceProvider.GetService(typeof(IDesignerHost));
DesignTimeBehavior behavior = (DesignTimeBehavior)ns.GetBehaviorOfElement(el);
//behavior.Element = el;
if (createRunatServerAttr)
{
el.SetAttribute("runat", "server", 0);
}
Control webcontrol = htmlEditor.GenericElementFactory.CreateElement(el);
// add a regular name
webcontrol.ID = nc.CreateName(dh.Container, webcontrol.GetType());
return webcontrol;
}
else
{
return null;
}
}
///// <summary>
///// Insert Element related to another element.
///// </summary>
///// <param name="method"></param>
///// <param name="element"></param>
//public void InsertAdjacentElement(InsertWhere method, IElement relative, Control ctrlToInsert, IHtmlEditor htmlEditor)
//{
// IElement element = GetNativeElement(ctrlToInsert, htmlEditor);
// if (element == null)
// {
// // not yet placed anywhere
// relative.InsertAdjacentHtml(method, GetNativeHtml(ctrlToInsert, htmlEditor));
// }
// else
// {
// // exists already, insert
// relative.InsertAdjacentElement(method, element);
// }
//}
//private IElement GetNativeElement(System.Web.UI.Control aspControl, IHtmlEditor htmlEditor)
//{
// IDesignerHost dh = (IDesignerHost)htmlEditor.ServiceProvider.GetService(typeof(IDesignerHost));
// IDesigner designer = dh.GetDesigner(aspControl);
// if (designer is System.Web.UI.Design.HtmlControlDesigner)
// {
// System.Web.UI.Design.IHtmlControlDesignerBehavior behavior = ((System.Web.UI.Design.HtmlControlDesigner)designer).Behavior;
// if (behavior != null && behavior is DesignTimeBehavior)
// {
// IElement nativeElement = ((DesignTimeBehavior)behavior).NativeElement;
// return nativeElement;
// }
// }
// return null;
//}
//private string GetNativeHtml(System.Web.UI.Control aspControl, IHtmlEditor htmlEditor)
//{
// IDesignerHost dh = (IDesignerHost)htmlEditor.ServiceProvider.GetService(typeof(IDesignerHost));
// IDesigner designer = dh.GetDesigner(aspControl);
// if (designer == null)
// {
// ((DesignerHost)dh).Add(aspControl, aspControl.ID);
// designer = dh.GetDesigner(aspControl);
// }
// if (designer is System.Web.UI.Design.HtmlControlDesigner)
// {
// System.Text.StringBuilder sb = new System.Text.StringBuilder();
// StringWriter sw = new StringWriter(sb);
// HtmlTextWriter tw = new HtmlTextWriter(sw);
// aspControl.RenderControl(tw);
// string s = sb.ToString();
// }
// return null;
//}
/// <summary>
/// Insert an element and returns the inserted object instance.
/// </summary>
/// <remarks>
/// Caller's are supposed to get the returned instance, because the parameter is orphaned (in fact, it's
/// disposed right now) and removed from DOM.
/// <para>
/// Inserting a huge number of elements is not recommended, because the function runs several internal steps
/// and therefore could result in performance flaw.
/// </para>
/// </remarks>
/// <exception cref="NotImplementedException">The element you're trying to create is not yet registered.</exception>
/// <param name="newElem">The element object being inserted.</param>
/// <param name="htmlEditor">The editor we reference to.</param>
/// <returns>Returns the new element instances after creation.</returns>
public Control InsertElementAtCaret(Control newElem, HtmlEditor htmlEditor)
{
if (newElem is IElement)
{
Interop.IHTMLElement element = ((IElement)newElem).GetBaseElement();
InsertElementAtCaret(element, htmlEditor.GetActiveDocument(false));
}
else
{
try
{
IReferenceManager wrm = GetReferenceManager(htmlEditor);
if (wrm != null)
{
// get full name (alias and name)
string tagPrefix = wrm.GetTagPrefix(newElem.GetType());
string tagName = newElem.GetType().Name;
string tag, id;
INameCreationService ns = (INameCreationService)htmlEditor.ServiceProvider.GetService(typeof(INameCreationService));
IContainer ec = (IContainer)htmlEditor.ServiceProvider.GetService(typeof(IContainer));
string name = (newElem.Site != null) ? newElem.Site.Name : ns.CreateName(ec, newElem.GetType());
if (String.IsNullOrEmpty(name))
{
id = String.Format("C{0}", Guid.NewGuid()).Replace("-", "");
}
else
{
id = name;
}
string saveId = newElem.ID;
tag = String.Format(@"<{0}:{1} id=""{2}"" {3}></{0}:{1}>",
tagPrefix,
tagName,
id,
EnsurePropertiesExists(htmlEditor).RequireServerAttribute ? @"runat=""server""" : "");
// insert at caret
htmlEditor.Document.InsertHtml(tag);
Interop.IHTMLElement el = null;
if (htmlEditor.GetActiveDocument(false) != null)
{
// get back the native instance
el = ((Interop.IHTMLDocument3)htmlEditor.GetActiveDocument(false)).GetElementById(id);
if (el != null)
{
if (String.IsNullOrEmpty(saveId))
{
//el.RemoveAttribute("id", 0);
}
else
{
el.SetAttribute("id", saveId, 0);
}
// take over all attributes of source element
IDesignerHost host = htmlEditor.ServiceProvider.GetService(typeof(IDesignerHost)) as IDesignerHost;
EmbeddedSerializer.SerializeControl(newElem, host, el);
}
}
// in case of success return the new instance and dispose the old one
if (el != null)
{
newElem.Dispose();
return htmlEditor.GenericElementFactory.CreateElement(el);
}
}
else
{
throw new NotImplementedException("Element not registered. Consider moving registration code to HtmlEditor's Loading event.");
}
}
catch (NotImplementedException)
{
throw;
}
catch
{
// failed for any reason
return null;
}
}
return null;
}
/// <summary>
/// Insert Element related to another element.
/// </summary>
/// <param name="method">Inserting method</param>
/// <param name="relative">Element relative to which the control is inserted.</param>
/// <param name="ctrlToInsert">Control to insert</param>
/// <param name="htmlEditor">Editor reference</param>
public Control InsertAdjacentElement(InsertWhere method, IElement relative, Control ctrlToInsert, IHtmlEditor htmlEditor)
{
IElement element = GetNativeElement(ctrlToInsert, htmlEditor);
if (element == null)
{
// not yet placed anywhere
//relative.InsertAdjacentHtml(method, GetNativeHtml(ctrlToInsert, htmlEditor));
Control newElem = ctrlToInsert;
try
{
IReferenceManager wrm = GetReferenceManager(htmlEditor);
if (wrm != null)
{
// get full name (alias and name)
string tagPrefix = wrm.GetTagPrefix(newElem.GetType());
string tagName = newElem.GetType().Name;
string tag, id;
if (String.IsNullOrEmpty(newElem.ID))
{
INameCreationService ns = (INameCreationService)htmlEditor.ServiceProvider.GetService(typeof(INameCreationService));
IContainer ec = (IContainer)htmlEditor.ServiceProvider.GetService(typeof(IContainer));
string name = ns.CreateName(ec, newElem.GetType());
if (String.IsNullOrEmpty(name))
{
id = String.Format("C{0}", Guid.NewGuid()).Replace("-", "");
}
else
{
id = name;
}
}
else
{
id = newElem.ID;
}
string saveId = id;
tag = String.Format(@"<{0}:{1} id=""{2}"" {3}></{0}:{1}>",
tagPrefix,
tagName,
id,
EnsurePropertiesExists(htmlEditor).RequireServerAttribute ? @"runat=""server""" : "");
// insert at caret
relative.InsertAdjacentHtml(method, tag);
Interop.IHTMLElement el = null;
if (htmlEditor.GetActiveDocument(false) != null)
{
// get back the native instance
el = ((Interop.IHTMLDocument3)htmlEditor.GetActiveDocument(false)).GetElementById(id);
if (el != null)
{
if (String.IsNullOrEmpty(saveId))
{
//el.RemoveAttribute("id", 0);
}
else
{
el.SetAttribute("id", saveId, 0);
}
// take over all attributes of source element
IDesignerHost host = htmlEditor.ServiceProvider.GetService(typeof(IDesignerHost)) as IDesignerHost;
EmbeddedSerializer.SerializeControl(newElem, host, el);
}
}
// in case of success return the new instance and dispose the old one
if (el != null)
{
newElem.Dispose();
return htmlEditor.GenericElementFactory.CreateElement(el);
}
}
else
{
throw new NotImplementedException("Element not registered. Consider moving registration code to HtmlEditor's Loading event.");
}
}
catch (NotImplementedException)
{
throw;
}
catch
{
// failed for any reason
return null;
}
}
else
{
// exists already, insert
relative.InsertAdjacentElement(method, element);
return element as Control;
}
return null;
}
private static Interop.IHTMLElement InsertElementAtCaret(Interop.IHTMLElement el, Interop.IHTMLDocument2 doc)
{
if (el == null) return null;
try
{
Interop.IMarkupServices ms;
Interop.IDisplayServices ds;
ds = (Interop.IDisplayServices)doc;
Interop.IDisplayPointer dp;
ds.CreateDisplayPointer(out dp);
Interop.IHTMLCaret cr;
ds.GetCaret(out cr);
cr.MoveDisplayPointerToCaret(dp);
ms = (Interop.IMarkupServices)doc;
Interop.IMarkupPointer sp; //, ep;
ms.CreateMarkupPointer(out sp); //Create a start markup pointer
dp.PositionMarkupPointer(sp);
ms.InsertElement(el, sp, null);
return el;
}
catch
{
}
return null;
}
/// <summary>
/// Register a user control assembly using a Directive object.
/// </summary>
/// <remarks>
/// In case of multiple editors on a form you must register your directive for any editor which should
/// display the content.
/// <seealso cref="IReferenceManager"/>
/// <seealso cref="IRegisterDirective"/>
/// <seealso cref="DirectiveAdded"/>
/// </remarks>
/// <param name="directive">The item contains information about the registered object.</param>
/// <param name="htmlEditor">Reference to HtmlEditor, this directive is related to.</param>
public void AddRegisterDirective(IRegisterDirective directive, IHtmlEditor htmlEditor)
{
IReferenceManager wrm = GetReferenceManager(htmlEditor);
if (wrm != null)
{
wrm.AddRegisterDirective(directive);
// This behavior provides the factory for element specific behaviors
htmlEditor.RegisterNamespace(directive.TagPrefix, typeof(DesignTimeBehavior));
}
// Directives per editor
if (!preRegistered.ContainsKey(htmlEditor))
{
List<IRegisterDirective> directives = new List<IRegisterDirective>();
directives.Add(directive);
preRegistered.Add(htmlEditor, directives);
}
else
{
if (!preRegistered[htmlEditor].Contains(directive))
{
preRegistered[htmlEditor].Add(directive);
}
}
}
/// <summary>
/// Returns the reference manager, which manages user controls.
/// </summary>
/// <remarks>
/// The reference manager is responsible for the relation between user controls in the code, recognized
/// by there prefix (namespace alias) and name, and the assembly which contains the type, which in turn
/// resolves the control and its designer.
/// <para>
/// The manager can be used simple by call <see cref="AddRegisterDirective"/> directly. The directive of type
/// <see cref="IRegisterDirective"/> will contain the necessary information. The reference manager is simple
/// some sort of container to provide the directive information to the renderer.
/// </para>
/// <seealso cref="AddRegisterDirective"/>
/// </remarks>
public IReferenceManager GetReferenceManager(IHtmlEditor htmlEditor)
{
return htmlEditor.ServiceProvider.GetService(typeof(IWebFormReferenceManager)) as IReferenceManager;
}
/// <summary>
/// The page which acts as the root component and forms the host for all components.
/// </summary>
/// <exception cref="NullReferenceException">Thrown if host service does not exists (Wrong usage).</exception>
/// <param name="rootComponent">An object derived from Page.</param>
/// <param name="htmlEditor"></param>
public void RegisterRootComponent(Page rootComponent, IHtmlEditor htmlEditor)
{
IDesignerHost host = htmlEditor.ServiceProvider.GetService(typeof(IDesignerHost)) as IDesignerHost;
if (host == null)
{
throw new NullReferenceException("The host does not exists or is not being loaded");
}
host.Container.Add(rootComponent);
}
/// <summary>
/// Fired if the host application adds a new directive.
/// </summary>f
public event DirectiveEventHandler DirectiveAdded;
/// <summary>
/// Fired during document load process to let host application register the directives.
/// </summary>
/// <remarks>
/// Host application should register usercontrol directives in this event to create
/// all internal references needed to resolve user types.
/// </remarks>
public event EventHandler RegisterDirectives;
private void InvokeRegisterDirectives()
{
if (RegisterDirectives != null)
{
RegisterDirectives(this, EventArgs.Empty);
}
}
#region IPlugIn Member
/// <summary>
/// Returns "AspDotNetDesigner".
/// </summary>
[Browsable(true), Category("NetRix")]
public string Name
{
get
{
return "AspDotNetDesigner";
}
}
/// <summary>
/// Declares that this is an extender provider. Returns <c>true</c>.
/// </summary>
[Browsable(false)]
public bool IsExtenderProvider
{
get
{
return true;
}
}
/// <summary>
/// The type.
/// </summary>
[Browsable(false)]
public Type Type
{
get
{
return this.GetType();
}
}
/// <summary>
/// Supported Features. This supports the plug-in infrastructure.
/// </summary>
[Browsable(true), Category("NetRix")]
public Feature Features
{
get
{
return Feature.CreateElements | Feature.EditDesigner | Feature.MultipleNamespaces | Feature.OwnNamespace | Feature.RegisterElements | Feature.DesignerHostSupport;
}
}
/// <summary>
/// returns http://asp.schema for the asp alias.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
[Browsable(false)]
public IDictionary GetSupportedNamespaces(IHtmlEditor key)
{
Hashtable ns = new Hashtable();
ns.Add("asp", "http://asp.schema");
return ns;
}
/// <summary>
/// List of element types, which the extender plugin extends.
/// </summary>
/// <remarks>
/// See <see cref="GuruComponents.Netrix.PlugIns.IPlugIn.GetElementExtenders"/> for background information.
/// </remarks>
public List<CommandExtender> GetElementExtenders(IElement component)
{
return null;
}
#endregion
/// <summary>
/// Load an aspx file from path.
/// </summary>
/// <param name="filepath">File path. Ignores if file not found.</param>
/// <param name="refEditor">The editor instance the contents is loaded into.</param>
public void LoadFile(string filepath, IHtmlEditor refEditor)
{
if (File.Exists(filepath))
{
basePath[refEditor] = Path.GetDirectoryName(filepath);
using (StreamReader fs = new StreamReader(filepath, true))
{
string s = fs.ReadToEnd();
LoadAspx(s, refEditor);
refEditor.Url = filepath;
}
}
}
/// <summary>
/// Load an aspx file from string.
/// </summary>
/// <remarks>
/// <%@ Control Language="C#" ClassName="SampleA1" %>
/// <%@ Register Assembly="Custom.Kernel.Web" Namespace="v.Kernel.Web.UI.WebControls.AspFields" TagPrefix="aspfield" %>
/// <%@ Register Assembly="Custom.Library.WebRenderFields" Namespace="Custom.Library.WebRenderFields" TagPrefix="aspField" %>
/// </remarks>
/// <param name="content">Content to be loaded.</param>
/// <param name="refEditor">The editor instance the contents is loaded into.</param>
public void LoadAspx(string content, IHtmlEditor refEditor)
{
preRegistered = new Dictionary<IHtmlEditor, List<IRegisterDirective>>();
pageDirectives = new Dictionary<IHtmlEditor, List<IDirective>>();
controlDirectives = new Dictionary<IHtmlEditor, List<IDirective>>();
// load
string wrapped = LoadControl(content, refEditor, EnsurePropertiesExists(refEditor));
refEditor.LoadHtml(wrapped);
}
internal static string LoadControl(string content, IHtmlEditor refEditor, DesignerProperties props)
{
IDesignerHost dh = refEditor.ServiceProvider.GetService(typeof(IDesignerHost)) as IDesignerHost;
IReferenceManager wrm = refEditor.ServiceProvider.GetService(typeof(IWebFormReferenceManager)) as IReferenceManager;
// Read directives
MatchCollection matches = tagRegex.Matches(content.Trim());
foreach (Match match in matches)
{
string text = match.Value.Replace(Environment.NewLine, "");
// remove this from content
content = content.Replace(text, "");
// Register directives
Match m = dirRegex.Match(match.Value);
if (m.Success)
{
string dirName = m.Groups[1].Captures[0].Value.ToLower().Trim();
IRegisterDirective rd;
switch (dirName)
{
case "page":
CaptureCollection cp = m.Groups[1].Captures;
Directive pd = PageDirective.GetDirectiveFromString(cp);
if (!pageDirectives.ContainsKey(refEditor))
{
List<IDirective> directives = new List<IDirective>();
directives.Add(pd);
pageDirectives.Add(refEditor, directives);
}
else
{
pageDirectives[refEditor].Add(pd);
}
break;
case "control":
CaptureCollection cc = m.Groups[1].Captures;
Directive cd = ControlDirective.GetDirectiveFromString(cc);
if (!controlDirectives.ContainsKey(refEditor))
{
List<IDirective> directives = new List<IDirective>();
directives.Add(cd);
controlDirectives.Add(refEditor, directives);
}
else
{
controlDirectives[refEditor].Add(cd);
}
break;
case "register":
CaptureCollection cr = m.Groups[1].Captures;
rd = (IRegisterDirective)GuruComponents.Netrix.Designer.RegisterDirective.GetDirectiveFromString(cr, dh);
((RegisterDirective)rd).ExpandUserControl = props.ExpandUserControls;
if (!preRegistered.ContainsKey(refEditor))
{
preRegistered.Add(refEditor, new List<IRegisterDirective>(new IRegisterDirective[] { rd }));
}
else
{
List<IRegisterDirective> existingRDs = preRegistered[refEditor];
if (existingRDs == null)
existingRDs = new List<IRegisterDirective>();
if (!existingRDs.Contains(rd))
{
existingRDs.Add(rd);
}
preRegistered[refEditor] = existingRDs;
}
// This behavior provides the factory for element specific behaviors
refEditor.RegisterNamespace(rd.TagPrefix, typeof(DesignTimeBehavior));
/* This block is to support automatically expanded user controls. It needs implementation
* of DesignTimeControlParser function in DesignTimeBehavior, which is not yet implemented.
* */
if (rd.IsUserControl)
{
// go recursively through nested user controls and look for register directives there as well
if (!String.IsNullOrEmpty(rd.AssemblyName))
{
AssemblyName name = new AssemblyName(rd.AssemblyName);
if (File.Exists(name.CodeBase))
{
Assembly a = Assembly.Load(new AssemblyName(rd.AssemblyName));
List<Type> types = new List<Type>(a.GetTypes());
Regex rr = new Regex(@"<(?<tagprefix>[\w:\:]+):(?<tagname>[\w:\.]+)(\s+(?<attrname>\w[-\w:]*)(\s*=\s*""(?<attrval>[^""]*)""|\s*=\s*'(?<attrval>[^']*)'|\s*=\s*(?<attrval><%#.*?%>)|\s*=\s*(?<attrval>[^\s=/>]*)|(?<attrval>\s*?)))*\s*(?<empty>/)?>");
MatchCollection usertagMatches = rr.Matches(content.Trim());
if (usertagMatches.Count > 0)
{
List<string> matchField = new List<string>();
foreach (Match user in usertagMatches)
{
if (user.Success && user.Groups["tagprefix"].Value == rd.TagPrefix && !matchField.Contains(user.Groups["tagname"].Value.ToLower()))
{
matchField.Add(user.Groups["tagname"].Value.ToLower());
}
}
// look for controls within the content
foreach (Type t in types)
{
if (matchField.Contains(t.Name.ToLower()))
{
((RegisterDirective)rd).ObjectType = t;
((RegisterDirective)rd).ExpandUserControl = props.ExpandUserControls;
break;
}
}
}
}
}
}
break;
}
}
}
// wrap content
string wrapped = String.Format("{0}", content.Trim());
return wrapped;
}
/// <summary>
/// Get the content as formatted aspx page. All directives are parsed and put to document's beginning.
/// </summary>
/// <param name="refEditor">The editor instance the contents is loaded from.</param>
/// <returns>String with content</returns>
public string SaveAspx(IHtmlEditor refEditor)
{
string content = "";
// get page directives first
if (pageDirectives.ContainsKey(refEditor))
{
foreach (Directive dir in pageDirectives[refEditor])
{
content += dir.ToString() + Environment.NewLine;
}
}
if (controlDirectives.ContainsKey(refEditor))
{
foreach (Directive dir in controlDirectives[refEditor])
{
content += dir.ToString() + Environment.NewLine;
}
}
// get referenced controls
IReferenceManager wrm = GetReferenceManager(refEditor);
if (wrm != null)
{
content += wrm.GetRegisterDirectives();
}
content += refEditor.GetRawHtml();
HtmlFormatter hf = new HtmlFormatter();
StringWriter sw = new StringWriter();
hf.Format(content, sw, refEditor.HtmlFormatterOptions);
return sw.ToString();
}
/// <summary>
/// Try to get the native (internal) generic element that represents the ASCX controls container.
/// </summary>
/// <param name="aspControl">Control what we're looking for. Must be part of document.</param>
/// <param name="htmlEditor1">Reference to editor</param>
/// <returns></returns>
public IElement GetNativeElement(System.Web.UI.Control aspControl, IHtmlEditor htmlEditor1)
{
IDesignerHost dh = (IDesignerHost)htmlEditor1.ServiceProvider.GetService(typeof(IDesignerHost));
IDesigner designer = dh.GetDesigner(aspControl);
if (designer is System.Web.UI.Design.HtmlControlDesigner)
{
System.Web.UI.Design.IHtmlControlDesignerBehavior behavior = ((System.Web.UI.Design.HtmlControlDesigner)designer).Behavior;
if (behavior != null && behavior is DesignTimeBehavior)
{
IElement nativeElement = ((DesignTimeBehavior)behavior).NativeElement;
return nativeElement;
}
}
return null;
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type WorkbookTableSortRequest.
/// </summary>
public partial class WorkbookTableSortRequest : BaseRequest, IWorkbookTableSortRequest
{
/// <summary>
/// Constructs a new WorkbookTableSortRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public WorkbookTableSortRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified WorkbookTableSort using POST.
/// </summary>
/// <param name="workbookTableSortToCreate">The WorkbookTableSort to create.</param>
/// <returns>The created WorkbookTableSort.</returns>
public System.Threading.Tasks.Task<WorkbookTableSort> CreateAsync(WorkbookTableSort workbookTableSortToCreate)
{
return this.CreateAsync(workbookTableSortToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified WorkbookTableSort using POST.
/// </summary>
/// <param name="workbookTableSortToCreate">The WorkbookTableSort to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created WorkbookTableSort.</returns>
public async System.Threading.Tasks.Task<WorkbookTableSort> CreateAsync(WorkbookTableSort workbookTableSortToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<WorkbookTableSort>(workbookTableSortToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified WorkbookTableSort.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified WorkbookTableSort.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<WorkbookTableSort>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified WorkbookTableSort.
/// </summary>
/// <returns>The WorkbookTableSort.</returns>
public System.Threading.Tasks.Task<WorkbookTableSort> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified WorkbookTableSort.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The WorkbookTableSort.</returns>
public async System.Threading.Tasks.Task<WorkbookTableSort> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<WorkbookTableSort>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified WorkbookTableSort using PATCH.
/// </summary>
/// <param name="workbookTableSortToUpdate">The WorkbookTableSort to update.</param>
/// <returns>The updated WorkbookTableSort.</returns>
public System.Threading.Tasks.Task<WorkbookTableSort> UpdateAsync(WorkbookTableSort workbookTableSortToUpdate)
{
return this.UpdateAsync(workbookTableSortToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified WorkbookTableSort using PATCH.
/// </summary>
/// <param name="workbookTableSortToUpdate">The WorkbookTableSort to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated WorkbookTableSort.</returns>
public async System.Threading.Tasks.Task<WorkbookTableSort> UpdateAsync(WorkbookTableSort workbookTableSortToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<WorkbookTableSort>(workbookTableSortToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookTableSortRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookTableSortRequest Expand(Expression<Func<WorkbookTableSort, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookTableSortRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookTableSortRequest Select(Expression<Func<WorkbookTableSort, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="workbookTableSortToInitialize">The <see cref="WorkbookTableSort"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(WorkbookTableSort workbookTableSortToInitialize)
{
}
}
}
| |
using System;
using System.Runtime.InteropServices;
namespace Craft.Net.Common
{
/// <summary>
/// Represents the location of an object in 3D space.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
public struct Vector3 : IEquatable<Vector3>
{
[FieldOffset(0)]
public double X;
[FieldOffset(8)]
public double Y;
[FieldOffset(16)]
public double Z;
public Vector3(double value)
{
X = Y = Z = value;
}
public Vector3(double x, double y, double z)
{
this.X = x;
this.Y = y;
this.Z = z;
}
public Vector3(Vector3 V)
{
this.X = V.X;
this.Y = V.Y;
this.Z = V.Z;
}
/// <summary>
/// Converts this Vector3 to a string in the format <x, y, z>.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format("<{0},{1},{2}>", X, Y, Z);
}
#region Math
/// <summary>
/// Truncates the decimal component of each part of this Vector3.
/// </summary>
public Vector3 Floor()
{
return new Vector3(Math.Floor(X), Math.Floor(Y), Math.Floor(Z));
}
/// <summary>
/// Calculates the distance between two Vector3 objects.
/// </summary>
public double DistanceTo(Vector3 other)
{
return Math.Sqrt(Square(other.X - X) +
Square(other.Y - Y) +
Square(other.Z - Z));
}
/// <summary>
/// Calculates the square of a num.
/// </summary>
private double Square(double num)
{
return num * num;
}
/// <summary>
/// Finds the distance of this vector from Vector3.Zero
/// </summary>
public double Distance
{
get
{
return DistanceTo(Zero);
}
}
public static Vector3 Min(Vector3 value1, Vector3 value2)
{
return new Vector3(
Math.Min(value1.X, value2.X),
Math.Min(value1.Y, value2.Y),
Math.Min(value1.Z, value2.Z)
);
}
public static Vector3 Max(Vector3 value1, Vector3 value2)
{
return new Vector3(
Math.Max(value1.X, value2.X),
Math.Max(value1.Y, value2.Y),
Math.Max(value1.Z, value2.Z)
);
}
#endregion
#region Operators
public static bool operator !=(Vector3 a, Vector3 b)
{
return !a.Equals(b);
}
public static bool operator ==(Vector3 a, Vector3 b)
{
return a.Equals(b);
}
public static Vector3 operator +(Vector3 a, Vector3 b)
{
return new Vector3(
a.X + b.X,
a.Y + b.Y,
a.Z + b.Z);
}
public static Vector3 operator -(Vector3 a, Vector3 b)
{
return new Vector3(
a.X - b.X,
a.Y - b.Y,
a.Z - b.Z);
}
public static Vector3 operator +(Vector3 a, Size b)
{
return new Vector3(
a.X + b.Width,
a.Y + b.Height,
a.Z + b.Depth);
}
public static Vector3 operator -(Vector3 a, Size b)
{
return new Vector3(
a.X - b.Width,
a.Y - b.Height,
a.Z - b.Depth);
}
public static Vector3 operator -(Vector3 a)
{
return new Vector3(
-a.X,
-a.Y,
-a.Z);
}
public static Vector3 operator *(Vector3 a, Vector3 b)
{
return new Vector3(
a.X * b.X,
a.Y * b.Y,
a.Z * b.Z);
}
public static Vector3 operator /(Vector3 a, Vector3 b)
{
return new Vector3(
a.X / b.X,
a.Y / b.Y,
a.Z / b.Z);
}
public static Vector3 operator +(Vector3 a, double b)
{
return new Vector3(
a.X + b,
a.Y + b,
a.Z + b);
}
public static Vector3 operator -(Vector3 a, double b)
{
return new Vector3(
a.X - b,
a.Y - b,
a.Z - b);
}
public static Vector3 operator *(Vector3 a, double b)
{
return new Vector3(
a.X * b,
a.Y * b,
a.Z * b);
}
public static Vector3 operator /(Vector3 a, double b)
{
return new Vector3(
a.X / b,
a.Y / b,
a.Z / b);
}
public static Vector3 operator +(double a, Vector3 b)
{
return new Vector3(
a + b.X,
a + b.Y,
a + b.Z);
}
public static Vector3 operator -(double a, Vector3 b)
{
return new Vector3(
a - b.X,
a - b.Y,
a - b.Z);
}
public static Vector3 operator *(double a, Vector3 b)
{
return new Vector3(
a * b.X,
a * b.Y,
a * b.Z);
}
public static Vector3 operator /(double a, Vector3 b)
{
return new Vector3(
a / b.X,
a / b.Y,
a / b.Z);
}
#endregion
#region Constants
public static Vector3 Zero
{
get { return new Vector3(0); }
}
public static Vector3 One
{
get { return new Vector3(1); }
}
public static Vector3 Up
{
get { return new Vector3(0, 1, 0); }
}
public static Vector3 Down
{
get { return new Vector3(0, -1, 0); }
}
public static Vector3 Left
{
get { return new Vector3(-1, 0, 0); }
}
public static Vector3 Right
{
get { return new Vector3(1, 0, 0); }
}
public static Vector3 Backwards
{
get { return new Vector3(0, 0, -1); }
}
public static Vector3 Forwards
{
get { return new Vector3(0, 0, 1); }
}
public static Vector3 South
{
get { return new Vector3(0, 0, 1); }
}
public static Vector3 North
{
get { return new Vector3(0, 0, -1); }
}
public static Vector3 West
{
get { return new Vector3(-1, 0, 0); }
}
public static Vector3 East
{
get { return new Vector3(1, 0, 0); }
}
#endregion
public bool Equals(Vector3 other)
{
return other.X.Equals(X) && other.Y.Equals(Y) && other.Z.Equals(Z);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (obj.GetType() != typeof(Vector3)) return false;
return Equals((Vector3)obj);
}
public override int GetHashCode()
{
unchecked
{
int result = X.GetHashCode();
result = (result * 397) ^ Y.GetHashCode();
result = (result * 397) ^ Z.GetHashCode();
return result;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace TestFlask.API.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// LzmaEncoder.cs
using System;
namespace SevenZip.Compression.LZMA
{
using RangeCoder;
public class Encoder : ICoder, ISetCoderProperties, IWriteCoderProperties
{
private enum EMatchFinderType
{
BT2,
BT4,
};
private const UInt32 kIfinityPrice = 0xFFFFFFF;
private static Byte[] g_FastPos = new Byte[1 << 11];
static Encoder()
{
const Byte kFastSlots = 22;
int c = 2;
g_FastPos[0] = 0;
g_FastPos[1] = 1;
for (Byte slotFast = 2; slotFast < kFastSlots; slotFast++)
{
UInt32 k = ((UInt32)1 << ((slotFast >> 1) - 1));
for (UInt32 j = 0; j < k; j++, c++)
g_FastPos[c] = slotFast;
}
}
private static UInt32 GetPosSlot(UInt32 pos)
{
if (pos < (1 << 11))
return g_FastPos[pos];
if (pos < (1 << 21))
return (UInt32)(g_FastPos[pos >> 10] + 20);
return (UInt32)(g_FastPos[pos >> 20] + 40);
}
private static UInt32 GetPosSlot2(UInt32 pos)
{
if (pos < (1 << 17))
return (UInt32)(g_FastPos[pos >> 6] + 12);
if (pos < (1 << 27))
return (UInt32)(g_FastPos[pos >> 16] + 32);
return (UInt32)(g_FastPos[pos >> 26] + 52);
}
private Base.State _state = new Base.State();
private Byte _previousByte;
private UInt32[] _repDistances = new UInt32[Base.kNumRepDistances];
private void BaseInit()
{
_state.Init();
_previousByte = 0;
for (UInt32 i = 0; i < Base.kNumRepDistances; i++)
_repDistances[i] = 0;
}
private const int kDefaultDictionaryLogSize = 22;
private const UInt32 kNumFastBytesDefault = 0x20;
private class LiteralEncoder
{
public struct Encoder2
{
private BitEncoder[] m_Encoders;
public void Create()
{
m_Encoders = new BitEncoder[0x300];
}
public void Init()
{
for (int i = 0; i < 0x300; i++) m_Encoders[i].Init();
}
public void Encode(RangeCoder.Encoder rangeEncoder, byte symbol)
{
uint context = 1;
for (int i = 7; i >= 0; i--)
{
uint bit = (uint)((symbol >> i) & 1);
m_Encoders[context].Encode(rangeEncoder, bit);
context = (context << 1) | bit;
}
}
public void EncodeMatched(RangeCoder.Encoder rangeEncoder, byte matchByte, byte symbol)
{
uint context = 1;
bool same = true;
for (int i = 7; i >= 0; i--)
{
uint bit = (uint)((symbol >> i) & 1);
uint state = context;
if (same)
{
uint matchBit = (uint)((matchByte >> i) & 1);
state += ((1 + matchBit) << 8);
same = (matchBit == bit);
}
m_Encoders[state].Encode(rangeEncoder, bit);
context = (context << 1) | bit;
}
}
public uint GetPrice(bool matchMode, byte matchByte, byte symbol)
{
uint price = 0;
uint context = 1;
int i = 7;
if (matchMode)
{
for (; i >= 0; i--)
{
uint matchBit = (uint)(matchByte >> i) & 1;
uint bit = (uint)(symbol >> i) & 1;
price += m_Encoders[((1 + matchBit) << 8) + context].GetPrice(bit);
context = (context << 1) | bit;
if (matchBit != bit)
{
i--;
break;
}
}
}
for (; i >= 0; i--)
{
uint bit = (uint)(symbol >> i) & 1;
price += m_Encoders[context].GetPrice(bit);
context = (context << 1) | bit;
}
return price;
}
}
private Encoder2[] m_Coders;
private int m_NumPrevBits;
private int m_NumPosBits;
private uint m_PosMask;
public void Create(int numPosBits, int numPrevBits)
{
if (m_Coders != null && m_NumPrevBits == numPrevBits && m_NumPosBits == numPosBits)
return;
m_NumPosBits = numPosBits;
m_PosMask = ((uint)1 << numPosBits) - 1;
m_NumPrevBits = numPrevBits;
uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits);
m_Coders = new Encoder2[numStates];
for (uint i = 0; i < numStates; i++)
m_Coders[i].Create();
}
public void Init()
{
uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits);
for (uint i = 0; i < numStates; i++)
m_Coders[i].Init();
}
public Encoder2 GetSubCoder(UInt32 pos, Byte prevByte)
{ return m_Coders[((pos & m_PosMask) << m_NumPrevBits) + (uint)(prevByte >> (8 - m_NumPrevBits))]; }
}
private class LenEncoder
{
private RangeCoder.BitEncoder _choice = new RangeCoder.BitEncoder();
private RangeCoder.BitEncoder _choice2 = new RangeCoder.BitEncoder();
private RangeCoder.BitTreeEncoder[] _lowCoder = new RangeCoder.BitTreeEncoder[Base.kNumPosStatesEncodingMax];
private RangeCoder.BitTreeEncoder[] _midCoder = new RangeCoder.BitTreeEncoder[Base.kNumPosStatesEncodingMax];
private RangeCoder.BitTreeEncoder _highCoder = new RangeCoder.BitTreeEncoder(Base.kNumHighLenBits);
public LenEncoder()
{
for (UInt32 posState = 0; posState < Base.kNumPosStatesEncodingMax; posState++)
{
_lowCoder[posState] = new RangeCoder.BitTreeEncoder(Base.kNumLowLenBits);
_midCoder[posState] = new RangeCoder.BitTreeEncoder(Base.kNumMidLenBits);
}
}
public void Init(UInt32 numPosStates)
{
_choice.Init();
_choice2.Init();
for (UInt32 posState = 0; posState < numPosStates; posState++)
{
_lowCoder[posState].Init();
_midCoder[posState].Init();
}
_highCoder.Init();
}
public void Encode(RangeCoder.Encoder rangeEncoder, UInt32 symbol, UInt32 posState)
{
if (symbol < Base.kNumLowLenSymbols)
{
_choice.Encode(rangeEncoder, 0);
_lowCoder[posState].Encode(rangeEncoder, symbol);
}
else
{
symbol -= Base.kNumLowLenSymbols;
_choice.Encode(rangeEncoder, 1);
if (symbol < Base.kNumMidLenSymbols)
{
_choice2.Encode(rangeEncoder, 0);
_midCoder[posState].Encode(rangeEncoder, symbol);
}
else
{
_choice2.Encode(rangeEncoder, 1);
_highCoder.Encode(rangeEncoder, symbol - Base.kNumMidLenSymbols);
}
}
}
public void SetPrices(UInt32 posState, UInt32 numSymbols, UInt32[] prices, UInt32 st)
{
UInt32 a0 = _choice.GetPrice0();
UInt32 a1 = _choice.GetPrice1();
UInt32 b0 = a1 + _choice2.GetPrice0();
UInt32 b1 = a1 + _choice2.GetPrice1();
UInt32 i = 0;
for (i = 0; i < Base.kNumLowLenSymbols; i++)
{
if (i >= numSymbols)
return;
prices[st + i] = a0 + _lowCoder[posState].GetPrice(i);
}
for (; i < Base.kNumLowLenSymbols + Base.kNumMidLenSymbols; i++)
{
if (i >= numSymbols)
return;
prices[st + i] = b0 + _midCoder[posState].GetPrice(i - Base.kNumLowLenSymbols);
}
for (; i < numSymbols; i++)
prices[st + i] = b1 + _highCoder.GetPrice(i - Base.kNumLowLenSymbols - Base.kNumMidLenSymbols);
}
};
private const UInt32 kNumLenSpecSymbols = Base.kNumLowLenSymbols + Base.kNumMidLenSymbols;
private class LenPriceTableEncoder : LenEncoder
{
private UInt32[] _prices = new UInt32[Base.kNumLenSymbols << Base.kNumPosStatesBitsEncodingMax];
private UInt32 _tableSize;
private UInt32[] _counters = new UInt32[Base.kNumPosStatesEncodingMax];
public void SetTableSize(UInt32 tableSize)
{
_tableSize = tableSize;
}
public UInt32 GetPrice(UInt32 symbol, UInt32 posState)
{
return _prices[posState * Base.kNumLenSymbols + symbol];
}
private void UpdateTable(UInt32 posState)
{
SetPrices(posState, _tableSize, _prices, posState * Base.kNumLenSymbols);
_counters[posState] = _tableSize;
}
public void UpdateTables(UInt32 numPosStates)
{
for (UInt32 posState = 0; posState < numPosStates; posState++)
UpdateTable(posState);
}
public new void Encode(RangeCoder.Encoder rangeEncoder, UInt32 symbol, UInt32 posState)
{
base.Encode(rangeEncoder, symbol, posState);
if (--_counters[posState] == 0)
UpdateTable(posState);
}
}
private const UInt32 kNumOpts = 1 << 12;
private class Optimal
{
public Base.State State;
public bool Prev1IsChar;
public bool Prev2;
public UInt32 PosPrev2;
public UInt32 BackPrev2;
public UInt32 Price;
public UInt32 PosPrev;
public UInt32 BackPrev;
public UInt32 Backs0;
public UInt32 Backs1;
public UInt32 Backs2;
public UInt32 Backs3;
public void MakeAsChar()
{
BackPrev = 0xFFFFFFFF; Prev1IsChar = false;
}
public void MakeAsShortRep()
{
BackPrev = 0; ; Prev1IsChar = false;
}
public bool IsShortRep()
{
return (BackPrev == 0);
}
};
private Optimal[] _optimum = new Optimal[kNumOpts];
private LZ.IMatchFinder _matchFinder = null;
private RangeCoder.Encoder _rangeEncoder = new RangeCoder.Encoder();
private RangeCoder.BitEncoder[] _isMatch = new RangeCoder.BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax];
private RangeCoder.BitEncoder[] _isRep = new RangeCoder.BitEncoder[Base.kNumStates];
private RangeCoder.BitEncoder[] _isRepG0 = new RangeCoder.BitEncoder[Base.kNumStates];
private RangeCoder.BitEncoder[] _isRepG1 = new RangeCoder.BitEncoder[Base.kNumStates];
private RangeCoder.BitEncoder[] _isRepG2 = new RangeCoder.BitEncoder[Base.kNumStates];
private RangeCoder.BitEncoder[] _isRep0Long = new RangeCoder.BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax];
private RangeCoder.BitTreeEncoder[] _posSlotEncoder = new RangeCoder.BitTreeEncoder[Base.kNumLenToPosStates];
private RangeCoder.BitEncoder[] _posEncoders = new RangeCoder.BitEncoder[Base.kNumFullDistances - Base.kEndPosModelIndex];
private RangeCoder.BitTreeEncoder _posAlignEncoder = new RangeCoder.BitTreeEncoder(Base.kNumAlignBits);
private LenPriceTableEncoder _lenEncoder = new LenPriceTableEncoder();
private LenPriceTableEncoder _repMatchLenEncoder = new LenPriceTableEncoder();
private LiteralEncoder _literalEncoder = new LiteralEncoder();
private UInt32[] _matchDistances = new UInt32[Base.kMatchMaxLen * 2 + 2];
private UInt32 _numFastBytes = kNumFastBytesDefault;
private UInt32 _longestMatchLength;
private UInt32 _numDistancePairs;
private UInt32 _additionalOffset;
private UInt32 _optimumEndIndex;
private UInt32 _optimumCurrentIndex;
private bool _longestMatchWasFound;
private UInt32[] _posSlotPrices = new UInt32[1 << (Base.kNumPosSlotBits + Base.kNumLenToPosStatesBits)];
private UInt32[] _distancesPrices = new UInt32[Base.kNumFullDistances << Base.kNumLenToPosStatesBits];
private UInt32[] _alignPrices = new UInt32[Base.kAlignTableSize];
private UInt32 _alignPriceCount;
private UInt32 _distTableSize = (kDefaultDictionaryLogSize * 2);
private int _posStateBits = 2;
private UInt32 _posStateMask = (4 - 1);
private int _numLiteralPosStateBits = 0;
private int _numLiteralContextBits = 3;
private UInt32 _dictionarySize = (1 << kDefaultDictionaryLogSize);
private UInt32 _dictionarySizePrev = 0xFFFFFFFF;
private UInt32 _numFastBytesPrev = 0xFFFFFFFF;
private Int64 nowPos64;
private bool _finished;
private System.IO.Stream _inStream;
private EMatchFinderType _matchFinderType = EMatchFinderType.BT4;
private bool _writeEndMark = false;
private bool _needReleaseMFStream;
private void Create()
{
if (_matchFinder == null)
{
LZ.BinTree bt = new LZ.BinTree();
int numHashBytes = 4;
if (_matchFinderType == EMatchFinderType.BT2)
numHashBytes = 2;
bt.SetType(numHashBytes);
_matchFinder = bt;
}
_literalEncoder.Create(_numLiteralPosStateBits, _numLiteralContextBits);
if (_dictionarySize == _dictionarySizePrev && _numFastBytesPrev == _numFastBytes)
return;
_matchFinder.Create(_dictionarySize, kNumOpts, _numFastBytes, Base.kMatchMaxLen + 1);
_dictionarySizePrev = _dictionarySize;
_numFastBytesPrev = _numFastBytes;
}
public Encoder()
{
for (int i = 0; i < kNumOpts; i++)
_optimum[i] = new Optimal();
for (int i = 0; i < Base.kNumLenToPosStates; i++)
_posSlotEncoder[i] = new RangeCoder.BitTreeEncoder(Base.kNumPosSlotBits);
}
private void SetWriteEndMarkerMode(bool writeEndMarker)
{
_writeEndMark = writeEndMarker;
}
private void Init()
{
BaseInit();
_rangeEncoder.Init();
uint i;
for (i = 0; i < Base.kNumStates; i++)
{
for (uint j = 0; j <= _posStateMask; j++)
{
uint complexState = (i << Base.kNumPosStatesBitsMax) + j;
_isMatch[complexState].Init();
_isRep0Long[complexState].Init();
}
_isRep[i].Init();
_isRepG0[i].Init();
_isRepG1[i].Init();
_isRepG2[i].Init();
}
_literalEncoder.Init();
for (i = 0; i < Base.kNumLenToPosStates; i++)
_posSlotEncoder[i].Init();
for (i = 0; i < Base.kNumFullDistances - Base.kEndPosModelIndex; i++)
_posEncoders[i].Init();
_lenEncoder.Init((UInt32)1 << _posStateBits);
_repMatchLenEncoder.Init((UInt32)1 << _posStateBits);
_posAlignEncoder.Init();
_longestMatchWasFound = false;
_optimumEndIndex = 0;
_optimumCurrentIndex = 0;
_additionalOffset = 0;
}
private void ReadMatchDistances(out UInt32 lenRes, out UInt32 numDistancePairs)
{
lenRes = 0;
numDistancePairs = _matchFinder.GetMatches(_matchDistances);
if (numDistancePairs > 0)
{
lenRes = _matchDistances[numDistancePairs - 2];
if (lenRes == _numFastBytes)
lenRes += _matchFinder.GetMatchLen((int)lenRes - 1, _matchDistances[numDistancePairs - 1],
Base.kMatchMaxLen - lenRes);
}
_additionalOffset++;
}
private void MovePos(UInt32 num)
{
if (num > 0)
{
_matchFinder.Skip(num);
_additionalOffset += num;
}
}
private UInt32 GetRepLen1Price(Base.State state, UInt32 posState)
{
return _isRepG0[state.Index].GetPrice0() +
_isRep0Long[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0();
}
private UInt32 GetPureRepPrice(UInt32 repIndex, Base.State state, UInt32 posState)
{
UInt32 price;
if (repIndex == 0)
{
price = _isRepG0[state.Index].GetPrice0();
price += _isRep0Long[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1();
}
else
{
price = _isRepG0[state.Index].GetPrice1();
if (repIndex == 1)
price += _isRepG1[state.Index].GetPrice0();
else
{
price += _isRepG1[state.Index].GetPrice1();
price += _isRepG2[state.Index].GetPrice(repIndex - 2);
}
}
return price;
}
private UInt32 GetRepPrice(UInt32 repIndex, UInt32 len, Base.State state, UInt32 posState)
{
UInt32 price = _repMatchLenEncoder.GetPrice(len - Base.kMatchMinLen, posState);
return price + GetPureRepPrice(repIndex, state, posState);
}
private UInt32 GetPosLenPrice(UInt32 pos, UInt32 len, UInt32 posState)
{
UInt32 price;
UInt32 lenToPosState = Base.GetLenToPosState(len);
if (pos < Base.kNumFullDistances)
price = _distancesPrices[(lenToPosState * Base.kNumFullDistances) + pos];
else
price = _posSlotPrices[(lenToPosState << Base.kNumPosSlotBits) + GetPosSlot2(pos)] +
_alignPrices[pos & Base.kAlignMask];
return price + _lenEncoder.GetPrice(len - Base.kMatchMinLen, posState);
}
private UInt32 Backward(out UInt32 backRes, UInt32 cur)
{
_optimumEndIndex = cur;
UInt32 posMem = _optimum[cur].PosPrev;
UInt32 backMem = _optimum[cur].BackPrev;
do
{
if (_optimum[cur].Prev1IsChar)
{
_optimum[posMem].MakeAsChar();
_optimum[posMem].PosPrev = posMem - 1;
if (_optimum[cur].Prev2)
{
_optimum[posMem - 1].Prev1IsChar = false;
_optimum[posMem - 1].PosPrev = _optimum[cur].PosPrev2;
_optimum[posMem - 1].BackPrev = _optimum[cur].BackPrev2;
}
}
UInt32 posPrev = posMem;
UInt32 backCur = backMem;
backMem = _optimum[posPrev].BackPrev;
posMem = _optimum[posPrev].PosPrev;
_optimum[posPrev].BackPrev = backCur;
_optimum[posPrev].PosPrev = cur;
cur = posPrev;
}
while (cur > 0);
backRes = _optimum[0].BackPrev;
_optimumCurrentIndex = _optimum[0].PosPrev;
return _optimumCurrentIndex;
}
private UInt32[] reps = new UInt32[Base.kNumRepDistances];
private UInt32[] repLens = new UInt32[Base.kNumRepDistances];
private UInt32 GetOptimum(UInt32 position, out UInt32 backRes)
{
if (_optimumEndIndex != _optimumCurrentIndex)
{
UInt32 lenRes = _optimum[_optimumCurrentIndex].PosPrev - _optimumCurrentIndex;
backRes = _optimum[_optimumCurrentIndex].BackPrev;
_optimumCurrentIndex = _optimum[_optimumCurrentIndex].PosPrev;
return lenRes;
}
_optimumCurrentIndex = _optimumEndIndex = 0;
UInt32 lenMain, numDistancePairs;
if (!_longestMatchWasFound)
{
ReadMatchDistances(out lenMain, out numDistancePairs);
}
else
{
lenMain = _longestMatchLength;
numDistancePairs = _numDistancePairs;
_longestMatchWasFound = false;
}
UInt32 numAvailableBytes = _matchFinder.GetNumAvailableBytes() + 1;
if (numAvailableBytes < 2)
{
backRes = 0xFFFFFFFF;
return 1;
}
if (numAvailableBytes > Base.kMatchMaxLen)
numAvailableBytes = Base.kMatchMaxLen;
UInt32 repMaxIndex = 0;
UInt32 i;
for (i = 0; i < Base.kNumRepDistances; i++)
{
reps[i] = _repDistances[i];
repLens[i] = _matchFinder.GetMatchLen(0 - 1, reps[i], Base.kMatchMaxLen);
if (repLens[i] > repLens[repMaxIndex])
repMaxIndex = i;
}
if (repLens[repMaxIndex] >= _numFastBytes)
{
backRes = repMaxIndex;
UInt32 lenRes = repLens[repMaxIndex];
MovePos(lenRes - 1);
return lenRes;
}
if (lenMain >= _numFastBytes)
{
backRes = _matchDistances[numDistancePairs - 1] + Base.kNumRepDistances;
MovePos(lenMain - 1);
return lenMain;
}
Byte currentByte = _matchFinder.GetIndexByte(0 - 1);
Byte matchByte = _matchFinder.GetIndexByte((Int32)(0 - _repDistances[0] - 1 - 1));
if (lenMain < 2 && currentByte != matchByte && repLens[repMaxIndex] < 2)
{
backRes = (UInt32)0xFFFFFFFF;
return 1;
}
_optimum[0].State = _state;
UInt32 posState = (position & _posStateMask);
_optimum[1].Price = _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0() +
_literalEncoder.GetSubCoder(position, _previousByte).GetPrice(!_state.IsCharState(), matchByte, currentByte);
_optimum[1].MakeAsChar();
UInt32 matchPrice = _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1();
UInt32 repMatchPrice = matchPrice + _isRep[_state.Index].GetPrice1();
if (matchByte == currentByte)
{
UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(_state, posState);
if (shortRepPrice < _optimum[1].Price)
{
_optimum[1].Price = shortRepPrice;
_optimum[1].MakeAsShortRep();
}
}
UInt32 lenEnd = ((lenMain >= repLens[repMaxIndex]) ? lenMain : repLens[repMaxIndex]);
if (lenEnd < 2)
{
backRes = _optimum[1].BackPrev;
return 1;
}
_optimum[1].PosPrev = 0;
_optimum[0].Backs0 = reps[0];
_optimum[0].Backs1 = reps[1];
_optimum[0].Backs2 = reps[2];
_optimum[0].Backs3 = reps[3];
UInt32 len = lenEnd;
do
_optimum[len--].Price = kIfinityPrice;
while (len >= 2);
for (i = 0; i < Base.kNumRepDistances; i++)
{
UInt32 repLen = repLens[i];
if (repLen < 2)
continue;
UInt32 price = repMatchPrice + GetPureRepPrice(i, _state, posState);
do
{
UInt32 curAndLenPrice = price + _repMatchLenEncoder.GetPrice(repLen - 2, posState);
Optimal optimum = _optimum[repLen];
if (curAndLenPrice < optimum.Price)
{
optimum.Price = curAndLenPrice;
optimum.PosPrev = 0;
optimum.BackPrev = i;
optimum.Prev1IsChar = false;
}
}
while (--repLen >= 2);
}
UInt32 normalMatchPrice = matchPrice + _isRep[_state.Index].GetPrice0();
len = ((repLens[0] >= 2) ? repLens[0] + 1 : 2);
if (len <= lenMain)
{
UInt32 offs = 0;
while (len > _matchDistances[offs])
offs += 2;
for (; ; len++)
{
UInt32 distance = _matchDistances[offs + 1];
UInt32 curAndLenPrice = normalMatchPrice + GetPosLenPrice(distance, len, posState);
Optimal optimum = _optimum[len];
if (curAndLenPrice < optimum.Price)
{
optimum.Price = curAndLenPrice;
optimum.PosPrev = 0;
optimum.BackPrev = distance + Base.kNumRepDistances;
optimum.Prev1IsChar = false;
}
if (len == _matchDistances[offs])
{
offs += 2;
if (offs == numDistancePairs)
break;
}
}
}
UInt32 cur = 0;
while (true)
{
cur++;
if (cur == lenEnd)
return Backward(out backRes, cur);
UInt32 newLen;
ReadMatchDistances(out newLen, out numDistancePairs);
if (newLen >= _numFastBytes)
{
_numDistancePairs = numDistancePairs;
_longestMatchLength = newLen;
_longestMatchWasFound = true;
return Backward(out backRes, cur);
}
position++;
UInt32 posPrev = _optimum[cur].PosPrev;
Base.State state;
if (_optimum[cur].Prev1IsChar)
{
posPrev--;
if (_optimum[cur].Prev2)
{
state = _optimum[_optimum[cur].PosPrev2].State;
if (_optimum[cur].BackPrev2 < Base.kNumRepDistances)
state.UpdateRep();
else
state.UpdateMatch();
}
else
state = _optimum[posPrev].State;
state.UpdateChar();
}
else
state = _optimum[posPrev].State;
if (posPrev == cur - 1)
{
if (_optimum[cur].IsShortRep())
state.UpdateShortRep();
else
state.UpdateChar();
}
else
{
UInt32 pos;
if (_optimum[cur].Prev1IsChar && _optimum[cur].Prev2)
{
posPrev = _optimum[cur].PosPrev2;
pos = _optimum[cur].BackPrev2;
state.UpdateRep();
}
else
{
pos = _optimum[cur].BackPrev;
if (pos < Base.kNumRepDistances)
state.UpdateRep();
else
state.UpdateMatch();
}
Optimal opt = _optimum[posPrev];
if (pos < Base.kNumRepDistances)
{
if (pos == 0)
{
reps[0] = opt.Backs0;
reps[1] = opt.Backs1;
reps[2] = opt.Backs2;
reps[3] = opt.Backs3;
}
else if (pos == 1)
{
reps[0] = opt.Backs1;
reps[1] = opt.Backs0;
reps[2] = opt.Backs2;
reps[3] = opt.Backs3;
}
else if (pos == 2)
{
reps[0] = opt.Backs2;
reps[1] = opt.Backs0;
reps[2] = opt.Backs1;
reps[3] = opt.Backs3;
}
else
{
reps[0] = opt.Backs3;
reps[1] = opt.Backs0;
reps[2] = opt.Backs1;
reps[3] = opt.Backs2;
}
}
else
{
reps[0] = (pos - Base.kNumRepDistances);
reps[1] = opt.Backs0;
reps[2] = opt.Backs1;
reps[3] = opt.Backs2;
}
}
_optimum[cur].State = state;
_optimum[cur].Backs0 = reps[0];
_optimum[cur].Backs1 = reps[1];
_optimum[cur].Backs2 = reps[2];
_optimum[cur].Backs3 = reps[3];
UInt32 curPrice = _optimum[cur].Price;
currentByte = _matchFinder.GetIndexByte(0 - 1);
matchByte = _matchFinder.GetIndexByte((Int32)(0 - reps[0] - 1 - 1));
posState = (position & _posStateMask);
UInt32 curAnd1Price = curPrice +
_isMatch[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0() +
_literalEncoder.GetSubCoder(position, _matchFinder.GetIndexByte(0 - 2)).
GetPrice(!state.IsCharState(), matchByte, currentByte);
Optimal nextOptimum = _optimum[cur + 1];
bool nextIsChar = false;
if (curAnd1Price < nextOptimum.Price)
{
nextOptimum.Price = curAnd1Price;
nextOptimum.PosPrev = cur;
nextOptimum.MakeAsChar();
nextIsChar = true;
}
matchPrice = curPrice + _isMatch[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1();
repMatchPrice = matchPrice + _isRep[state.Index].GetPrice1();
if (matchByte == currentByte &&
!(nextOptimum.PosPrev < cur && nextOptimum.BackPrev == 0))
{
UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(state, posState);
if (shortRepPrice <= nextOptimum.Price)
{
nextOptimum.Price = shortRepPrice;
nextOptimum.PosPrev = cur;
nextOptimum.MakeAsShortRep();
nextIsChar = true;
}
}
UInt32 numAvailableBytesFull = _matchFinder.GetNumAvailableBytes() + 1;
numAvailableBytesFull = Math.Min(kNumOpts - 1 - cur, numAvailableBytesFull);
numAvailableBytes = numAvailableBytesFull;
if (numAvailableBytes < 2)
continue;
if (numAvailableBytes > _numFastBytes)
numAvailableBytes = _numFastBytes;
if (!nextIsChar && matchByte != currentByte)
{
// try Literal + rep0
UInt32 t = Math.Min(numAvailableBytesFull - 1, _numFastBytes);
UInt32 lenTest2 = _matchFinder.GetMatchLen(0, reps[0], t);
if (lenTest2 >= 2)
{
Base.State state2 = state;
state2.UpdateChar();
UInt32 posStateNext = (position + 1) & _posStateMask;
UInt32 nextRepMatchPrice = curAnd1Price +
_isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1() +
_isRep[state2.Index].GetPrice1();
{
UInt32 offset = cur + 1 + lenTest2;
while (lenEnd < offset)
_optimum[++lenEnd].Price = kIfinityPrice;
UInt32 curAndLenPrice = nextRepMatchPrice + GetRepPrice(
0, lenTest2, state2, posStateNext);
Optimal optimum = _optimum[offset];
if (curAndLenPrice < optimum.Price)
{
optimum.Price = curAndLenPrice;
optimum.PosPrev = cur + 1;
optimum.BackPrev = 0;
optimum.Prev1IsChar = true;
optimum.Prev2 = false;
}
}
}
}
UInt32 startLen = 2; // speed optimization
for (UInt32 repIndex = 0; repIndex < Base.kNumRepDistances; repIndex++)
{
UInt32 lenTest = _matchFinder.GetMatchLen(0 - 1, reps[repIndex], numAvailableBytes);
if (lenTest < 2)
continue;
UInt32 lenTestTemp = lenTest;
do
{
while (lenEnd < cur + lenTest)
_optimum[++lenEnd].Price = kIfinityPrice;
UInt32 curAndLenPrice = repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState);
Optimal optimum = _optimum[cur + lenTest];
if (curAndLenPrice < optimum.Price)
{
optimum.Price = curAndLenPrice;
optimum.PosPrev = cur;
optimum.BackPrev = repIndex;
optimum.Prev1IsChar = false;
}
}
while (--lenTest >= 2);
lenTest = lenTestTemp;
if (repIndex == 0)
startLen = lenTest + 1;
// if (_maxMode)
if (lenTest < numAvailableBytesFull)
{
UInt32 t = Math.Min(numAvailableBytesFull - 1 - lenTest, _numFastBytes);
UInt32 lenTest2 = _matchFinder.GetMatchLen((Int32)lenTest, reps[repIndex], t);
if (lenTest2 >= 2)
{
Base.State state2 = state;
state2.UpdateRep();
UInt32 posStateNext = (position + lenTest) & _posStateMask;
UInt32 curAndLenCharPrice =
repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState) +
_isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice0() +
_literalEncoder.GetSubCoder(position + lenTest,
_matchFinder.GetIndexByte((Int32)lenTest - 1 - 1)).GetPrice(true,
_matchFinder.GetIndexByte((Int32)((Int32)lenTest - 1 - (Int32)(reps[repIndex] + 1))),
_matchFinder.GetIndexByte((Int32)lenTest - 1));
state2.UpdateChar();
posStateNext = (position + lenTest + 1) & _posStateMask;
UInt32 nextMatchPrice = curAndLenCharPrice + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1();
UInt32 nextRepMatchPrice = nextMatchPrice + _isRep[state2.Index].GetPrice1();
// for(; lenTest2 >= 2; lenTest2--)
{
UInt32 offset = lenTest + 1 + lenTest2;
while (lenEnd < cur + offset)
_optimum[++lenEnd].Price = kIfinityPrice;
UInt32 curAndLenPrice = nextRepMatchPrice + GetRepPrice(0, lenTest2, state2, posStateNext);
Optimal optimum = _optimum[cur + offset];
if (curAndLenPrice < optimum.Price)
{
optimum.Price = curAndLenPrice;
optimum.PosPrev = cur + lenTest + 1;
optimum.BackPrev = 0;
optimum.Prev1IsChar = true;
optimum.Prev2 = true;
optimum.PosPrev2 = cur;
optimum.BackPrev2 = repIndex;
}
}
}
}
}
if (newLen > numAvailableBytes)
{
newLen = numAvailableBytes;
for (numDistancePairs = 0; newLen > _matchDistances[numDistancePairs]; numDistancePairs += 2) ;
_matchDistances[numDistancePairs] = newLen;
numDistancePairs += 2;
}
if (newLen >= startLen)
{
normalMatchPrice = matchPrice + _isRep[state.Index].GetPrice0();
while (lenEnd < cur + newLen)
_optimum[++lenEnd].Price = kIfinityPrice;
UInt32 offs = 0;
while (startLen > _matchDistances[offs])
offs += 2;
for (UInt32 lenTest = startLen; ; lenTest++)
{
UInt32 curBack = _matchDistances[offs + 1];
UInt32 curAndLenPrice = normalMatchPrice + GetPosLenPrice(curBack, lenTest, posState);
Optimal optimum = _optimum[cur + lenTest];
if (curAndLenPrice < optimum.Price)
{
optimum.Price = curAndLenPrice;
optimum.PosPrev = cur;
optimum.BackPrev = curBack + Base.kNumRepDistances;
optimum.Prev1IsChar = false;
}
if (lenTest == _matchDistances[offs])
{
if (lenTest < numAvailableBytesFull)
{
UInt32 t = Math.Min(numAvailableBytesFull - 1 - lenTest, _numFastBytes);
UInt32 lenTest2 = _matchFinder.GetMatchLen((Int32)lenTest, curBack, t);
if (lenTest2 >= 2)
{
Base.State state2 = state;
state2.UpdateMatch();
UInt32 posStateNext = (position + lenTest) & _posStateMask;
UInt32 curAndLenCharPrice = curAndLenPrice +
_isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice0() +
_literalEncoder.GetSubCoder(position + lenTest,
_matchFinder.GetIndexByte((Int32)lenTest - 1 - 1)).
GetPrice(true,
_matchFinder.GetIndexByte((Int32)lenTest - (Int32)(curBack + 1) - 1),
_matchFinder.GetIndexByte((Int32)lenTest - 1));
state2.UpdateChar();
posStateNext = (position + lenTest + 1) & _posStateMask;
UInt32 nextMatchPrice = curAndLenCharPrice + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1();
UInt32 nextRepMatchPrice = nextMatchPrice + _isRep[state2.Index].GetPrice1();
UInt32 offset = lenTest + 1 + lenTest2;
while (lenEnd < cur + offset)
_optimum[++lenEnd].Price = kIfinityPrice;
curAndLenPrice = nextRepMatchPrice + GetRepPrice(0, lenTest2, state2, posStateNext);
optimum = _optimum[cur + offset];
if (curAndLenPrice < optimum.Price)
{
optimum.Price = curAndLenPrice;
optimum.PosPrev = cur + lenTest + 1;
optimum.BackPrev = 0;
optimum.Prev1IsChar = true;
optimum.Prev2 = true;
optimum.PosPrev2 = cur;
optimum.BackPrev2 = curBack + Base.kNumRepDistances;
}
}
}
offs += 2;
if (offs == numDistancePairs)
break;
}
}
}
}
}
private bool ChangePair(UInt32 smallDist, UInt32 bigDist)
{
const int kDif = 7;
return (smallDist < ((UInt32)(1) << (32 - kDif)) && bigDist >= (smallDist << kDif));
}
private void WriteEndMarker(UInt32 posState)
{
if (!_writeEndMark)
return;
_isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].Encode(_rangeEncoder, 1);
_isRep[_state.Index].Encode(_rangeEncoder, 0);
_state.UpdateMatch();
UInt32 len = Base.kMatchMinLen;
_lenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState);
UInt32 posSlot = (1 << Base.kNumPosSlotBits) - 1;
UInt32 lenToPosState = Base.GetLenToPosState(len);
_posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot);
int footerBits = 30;
UInt32 posReduced = (((UInt32)1) << footerBits) - 1;
_rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits);
_posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask);
}
private void Flush(UInt32 nowPos)
{
ReleaseMFStream();
WriteEndMarker(nowPos & _posStateMask);
_rangeEncoder.FlushData();
_rangeEncoder.FlushStream();
}
public void CodeOneBlock(out Int64 inSize, out Int64 outSize, out bool finished)
{
inSize = 0;
outSize = 0;
finished = true;
if (_inStream != null)
{
_matchFinder.SetStream(_inStream);
_matchFinder.Init();
_needReleaseMFStream = true;
_inStream = null;
if (_trainSize > 0)
_matchFinder.Skip(_trainSize);
}
if (_finished)
return;
_finished = true;
Int64 progressPosValuePrev = nowPos64;
if (nowPos64 == 0)
{
if (_matchFinder.GetNumAvailableBytes() == 0)
{
Flush((UInt32)nowPos64);
return;
}
UInt32 len, numDistancePairs; // it's not used
ReadMatchDistances(out len, out numDistancePairs);
UInt32 posState = (UInt32)(nowPos64) & _posStateMask;
_isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].Encode(_rangeEncoder, 0);
_state.UpdateChar();
Byte curByte = _matchFinder.GetIndexByte((Int32)(0 - _additionalOffset));
_literalEncoder.GetSubCoder((UInt32)(nowPos64), _previousByte).Encode(_rangeEncoder, curByte);
_previousByte = curByte;
_additionalOffset--;
nowPos64++;
}
if (_matchFinder.GetNumAvailableBytes() == 0)
{
Flush((UInt32)nowPos64);
return;
}
while (true)
{
UInt32 pos;
UInt32 len = GetOptimum((UInt32)nowPos64, out pos);
UInt32 posState = ((UInt32)nowPos64) & _posStateMask;
UInt32 complexState = (_state.Index << Base.kNumPosStatesBitsMax) + posState;
if (len == 1 && pos == 0xFFFFFFFF)
{
_isMatch[complexState].Encode(_rangeEncoder, 0);
Byte curByte = _matchFinder.GetIndexByte((Int32)(0 - _additionalOffset));
LiteralEncoder.Encoder2 subCoder = _literalEncoder.GetSubCoder((UInt32)nowPos64, _previousByte);
if (!_state.IsCharState())
{
Byte matchByte = _matchFinder.GetIndexByte((Int32)(0 - _repDistances[0] - 1 - _additionalOffset));
subCoder.EncodeMatched(_rangeEncoder, matchByte, curByte);
}
else
subCoder.Encode(_rangeEncoder, curByte);
_previousByte = curByte;
_state.UpdateChar();
}
else
{
_isMatch[complexState].Encode(_rangeEncoder, 1);
if (pos < Base.kNumRepDistances)
{
_isRep[_state.Index].Encode(_rangeEncoder, 1);
if (pos == 0)
{
_isRepG0[_state.Index].Encode(_rangeEncoder, 0);
if (len == 1)
_isRep0Long[complexState].Encode(_rangeEncoder, 0);
else
_isRep0Long[complexState].Encode(_rangeEncoder, 1);
}
else
{
_isRepG0[_state.Index].Encode(_rangeEncoder, 1);
if (pos == 1)
_isRepG1[_state.Index].Encode(_rangeEncoder, 0);
else
{
_isRepG1[_state.Index].Encode(_rangeEncoder, 1);
_isRepG2[_state.Index].Encode(_rangeEncoder, pos - 2);
}
}
if (len == 1)
_state.UpdateShortRep();
else
{
_repMatchLenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState);
_state.UpdateRep();
}
UInt32 distance = _repDistances[pos];
if (pos != 0)
{
for (UInt32 i = pos; i >= 1; i--)
_repDistances[i] = _repDistances[i - 1];
_repDistances[0] = distance;
}
}
else
{
_isRep[_state.Index].Encode(_rangeEncoder, 0);
_state.UpdateMatch();
_lenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState);
pos -= Base.kNumRepDistances;
UInt32 posSlot = GetPosSlot(pos);
UInt32 lenToPosState = Base.GetLenToPosState(len);
_posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot);
if (posSlot >= Base.kStartPosModelIndex)
{
int footerBits = (int)((posSlot >> 1) - 1);
UInt32 baseVal = ((2 | (posSlot & 1)) << footerBits);
UInt32 posReduced = pos - baseVal;
if (posSlot < Base.kEndPosModelIndex)
RangeCoder.BitTreeEncoder.ReverseEncode(_posEncoders,
baseVal - posSlot - 1, _rangeEncoder, footerBits, posReduced);
else
{
_rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits);
_posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask);
_alignPriceCount++;
}
}
UInt32 distance = pos;
for (UInt32 i = Base.kNumRepDistances - 1; i >= 1; i--)
_repDistances[i] = _repDistances[i - 1];
_repDistances[0] = distance;
_matchPriceCount++;
}
_previousByte = _matchFinder.GetIndexByte((Int32)(len - 1 - _additionalOffset));
}
_additionalOffset -= len;
nowPos64 += len;
if (_additionalOffset == 0)
{
// if (!_fastMode)
if (_matchPriceCount >= (1 << 7))
FillDistancesPrices();
if (_alignPriceCount >= Base.kAlignTableSize)
FillAlignPrices();
inSize = nowPos64;
outSize = _rangeEncoder.GetProcessedSizeAdd();
if (_matchFinder.GetNumAvailableBytes() == 0)
{
Flush((UInt32)nowPos64);
return;
}
if (nowPos64 - progressPosValuePrev >= (1 << 12))
{
_finished = false;
finished = false;
return;
}
}
}
}
private void ReleaseMFStream()
{
if (_matchFinder != null && _needReleaseMFStream)
{
_matchFinder.ReleaseStream();
_needReleaseMFStream = false;
}
}
private void SetOutStream(System.IO.Stream outStream)
{ _rangeEncoder.SetStream(outStream); }
private void ReleaseOutStream()
{ _rangeEncoder.ReleaseStream(); }
private void ReleaseStreams()
{
ReleaseMFStream();
ReleaseOutStream();
}
private void SetStreams(System.IO.Stream inStream, System.IO.Stream outStream,
Int64 inSize, Int64 outSize)
{
_inStream = inStream;
_finished = false;
Create();
SetOutStream(outStream);
Init();
// if (!_fastMode)
{
FillDistancesPrices();
FillAlignPrices();
}
_lenEncoder.SetTableSize(_numFastBytes + 1 - Base.kMatchMinLen);
_lenEncoder.UpdateTables((UInt32)1 << _posStateBits);
_repMatchLenEncoder.SetTableSize(_numFastBytes + 1 - Base.kMatchMinLen);
_repMatchLenEncoder.UpdateTables((UInt32)1 << _posStateBits);
nowPos64 = 0;
}
public void Code(System.IO.Stream inStream, System.IO.Stream outStream,
Int64 inSize, Int64 outSize, ICodeProgress progress)
{
_needReleaseMFStream = false;
try
{
SetStreams(inStream, outStream, inSize, outSize);
while (true)
{
Int64 processedInSize;
Int64 processedOutSize;
bool finished;
CodeOneBlock(out processedInSize, out processedOutSize, out finished);
if (finished)
return;
if (progress != null)
{
progress.SetProgress(processedInSize, processedOutSize);
}
}
}
finally
{
ReleaseStreams();
}
}
private const int kPropSize = 5;
private Byte[] properties = new Byte[kPropSize];
public void WriteCoderProperties(System.IO.Stream outStream)
{
properties[0] = (Byte)((_posStateBits * 5 + _numLiteralPosStateBits) * 9 + _numLiteralContextBits);
for (int i = 0; i < 4; i++)
properties[1 + i] = (Byte)((_dictionarySize >> (8 * i)) & 0xFF);
outStream.Write(properties, 0, kPropSize);
}
private UInt32[] tempPrices = new UInt32[Base.kNumFullDistances];
private UInt32 _matchPriceCount;
private void FillDistancesPrices()
{
for (UInt32 i = Base.kStartPosModelIndex; i < Base.kNumFullDistances; i++)
{
UInt32 posSlot = GetPosSlot(i);
int footerBits = (int)((posSlot >> 1) - 1);
UInt32 baseVal = ((2 | (posSlot & 1)) << footerBits);
tempPrices[i] = BitTreeEncoder.ReverseGetPrice(_posEncoders,
baseVal - posSlot - 1, footerBits, i - baseVal);
}
for (UInt32 lenToPosState = 0; lenToPosState < Base.kNumLenToPosStates; lenToPosState++)
{
UInt32 posSlot;
RangeCoder.BitTreeEncoder encoder = _posSlotEncoder[lenToPosState];
UInt32 st = (lenToPosState << Base.kNumPosSlotBits);
for (posSlot = 0; posSlot < _distTableSize; posSlot++)
_posSlotPrices[st + posSlot] = encoder.GetPrice(posSlot);
for (posSlot = Base.kEndPosModelIndex; posSlot < _distTableSize; posSlot++)
_posSlotPrices[st + posSlot] += ((((posSlot >> 1) - 1) - Base.kNumAlignBits) << RangeCoder.BitEncoder.kNumBitPriceShiftBits);
UInt32 st2 = lenToPosState * Base.kNumFullDistances;
UInt32 i;
for (i = 0; i < Base.kStartPosModelIndex; i++)
_distancesPrices[st2 + i] = _posSlotPrices[st + i];
for (; i < Base.kNumFullDistances; i++)
_distancesPrices[st2 + i] = _posSlotPrices[st + GetPosSlot(i)] + tempPrices[i];
}
_matchPriceCount = 0;
}
private void FillAlignPrices()
{
for (UInt32 i = 0; i < Base.kAlignTableSize; i++)
_alignPrices[i] = _posAlignEncoder.ReverseGetPrice(i);
_alignPriceCount = 0;
}
private static string[] kMatchFinderIDs =
{
"BT2",
"BT4",
};
private static int FindMatchFinder(string s)
{
for (int m = 0; m < kMatchFinderIDs.Length; m++)
if (s == kMatchFinderIDs[m])
return m;
return -1;
}
public void SetCoderProperties(CoderPropID[] propIDs, object[] properties)
{
for (UInt32 i = 0; i < properties.Length; i++)
{
object prop = properties[i];
switch (propIDs[i])
{
case CoderPropID.NumFastBytes:
{
if (!(prop is Int32))
throw new InvalidParamException();
Int32 numFastBytes = (Int32)prop;
if (numFastBytes < 5 || numFastBytes > Base.kMatchMaxLen)
throw new InvalidParamException();
_numFastBytes = (UInt32)numFastBytes;
break;
}
case CoderPropID.Algorithm:
{
/*
if (!(prop is Int32))
throw new InvalidParamException();
Int32 maximize = (Int32)prop;
_fastMode = (maximize == 0);
_maxMode = (maximize >= 2);
*/
break;
}
case CoderPropID.MatchFinder:
{
if (!(prop is String))
throw new InvalidParamException();
EMatchFinderType matchFinderIndexPrev = _matchFinderType;
int m = FindMatchFinder(((string)prop).ToUpper());
if (m < 0)
throw new InvalidParamException();
_matchFinderType = (EMatchFinderType)m;
if (_matchFinder != null && matchFinderIndexPrev != _matchFinderType)
{
_dictionarySizePrev = 0xFFFFFFFF;
_matchFinder = null;
}
break;
}
case CoderPropID.DictionarySize:
{
const int kDicLogSizeMaxCompress = 30;
if (!(prop is Int32))
throw new InvalidParamException(); ;
Int32 dictionarySize = (Int32)prop;
if (dictionarySize < (UInt32)(1 << Base.kDicLogSizeMin) ||
dictionarySize > (UInt32)(1 << kDicLogSizeMaxCompress))
throw new InvalidParamException();
_dictionarySize = (UInt32)dictionarySize;
int dicLogSize;
for (dicLogSize = 0; dicLogSize < (UInt32)kDicLogSizeMaxCompress; dicLogSize++)
if (dictionarySize <= ((UInt32)(1) << dicLogSize))
break;
_distTableSize = (UInt32)dicLogSize * 2;
break;
}
case CoderPropID.PosStateBits:
{
if (!(prop is Int32))
throw new InvalidParamException();
Int32 v = (Int32)prop;
if (v < 0 || v > (UInt32)Base.kNumPosStatesBitsEncodingMax)
throw new InvalidParamException();
_posStateBits = (int)v;
_posStateMask = (((UInt32)1) << (int)_posStateBits) - 1;
break;
}
case CoderPropID.LitPosBits:
{
if (!(prop is Int32))
throw new InvalidParamException();
Int32 v = (Int32)prop;
if (v < 0 || v > (UInt32)Base.kNumLitPosStatesBitsEncodingMax)
throw new InvalidParamException();
_numLiteralPosStateBits = (int)v;
break;
}
case CoderPropID.LitContextBits:
{
if (!(prop is Int32))
throw new InvalidParamException();
Int32 v = (Int32)prop;
if (v < 0 || v > (UInt32)Base.kNumLitContextBitsMax)
throw new InvalidParamException(); ;
_numLiteralContextBits = (int)v;
break;
}
case CoderPropID.EndMarker:
{
if (!(prop is Boolean))
throw new InvalidParamException();
SetWriteEndMarkerMode((Boolean)prop);
break;
}
default:
throw new InvalidParamException();
}
}
}
private uint _trainSize = 0;
public void SetTrainSize(uint trainSize)
{
_trainSize = trainSize;
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.HSSF.UserModel
{
using System;
using NPOI.HSSF.Record;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using System.Collections.Generic;
/// <summary>
/// High level representation of the style of a cell in a sheet of a workbook.
/// @author Andrew C. Oliver (acoliver at apache dot org)
/// @author Jason Height (jheight at chariot dot net dot au)
/// </summary>
public class HSSFCellStyle : ICellStyle
{
private ExtendedFormatRecord _format = null;
private short index = 0;
private NPOI.HSSF.Model.InternalWorkbook _workbook = null;
/// <summary>
/// Initializes a new instance of the <see cref="HSSFCellStyle"/> class.
/// </summary>
/// <param name="index">The index.</param>
/// <param name="rec">The record.</param>
/// <param name="workbook">The workbook.</param>
public HSSFCellStyle(short index, ExtendedFormatRecord rec, HSSFWorkbook workbook)
:this(index, rec, workbook.Workbook)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="HSSFCellStyle"/> class.
/// </summary>
/// <param name="index">The index.</param>
/// <param name="rec">The record.</param>
/// <param name="workbook">The workbook.</param>
public HSSFCellStyle(short index, ExtendedFormatRecord rec, NPOI.HSSF.Model.InternalWorkbook workbook)
{
this._workbook = workbook;
this.index = index;
_format = rec;
}
/// <summary>
/// Get the index within the HSSFWorkbook (sequence within the collection of ExtnededFormat objects)
/// </summary>
/// <value>Unique index number of the Underlying record this style represents (probably you don't care
/// Unless you're comparing which one is which)</value>
public short Index
{
get { return index; }
}
/// <summary>
/// Gets the parent style.
/// </summary>
/// <value>the parent style for this cell style.
/// In most cases this will be null, but in a few
/// cases there'll be a fully defined parent.</value>
public HSSFCellStyle ParentStyle
{
get
{
short parentIndex = _format.ParentIndex;
// parentIndex equal 0xFFF indicates no inheritance from a cell style XF (See 2.4.353 XF)
if ( parentIndex == 0|| parentIndex == 0xFFF)
{
return null;
}
return new HSSFCellStyle(
parentIndex,
_workbook.GetExFormatAt(parentIndex),
_workbook
);
}
}
/// <summary>
/// Get the index of the format
/// </summary>
/// <value>The data format.</value>
public short DataFormat
{
get { return _format.FormatIndex; }
set { _format.FormatIndex = (value); }
}
private static short lastDateFormat = short.MinValue;
private static List<FormatRecord> lastFormats = null;
private static String getDataFormatStringCache = null;
/// <summary>
/// Get the contents of the format string, by looking up
/// the DataFormat against the bound workbook
/// </summary>
/// <returns></returns>
public String GetDataFormatString()
{
//HSSFDataFormat format = new HSSFDataFormat(workbook);
//return format.GetFormat(DataFormat);
if (getDataFormatStringCache != null)
{
if (lastDateFormat == DataFormat && _workbook.Formats.Equals(lastFormats))
{
return getDataFormatStringCache;
}
}
lastFormats = _workbook.Formats;
lastDateFormat = DataFormat;
getDataFormatStringCache = GetDataFormatString(_workbook);
return getDataFormatStringCache;
}
/// <summary>
/// Get the contents of the format string, by looking up the DataFormat against the supplied workbook
/// </summary>
/// <param name="workbook">The workbook</param>
/// <returns>the format string or "General" if not found</returns>
public String GetDataFormatString(IWorkbook workbook)
{
HSSFDataFormat format = new HSSFDataFormat(((HSSFWorkbook)workbook).Workbook);
int idx = DataFormat;
return idx == -1 ? "General" : format.GetFormat(DataFormat);
}
/// <summary>
/// Get the contents of the format string, by looking up
/// the DataFormat against the supplied workbook
/// </summary>
/// <param name="workbook">The internal workbook.</param>
/// <returns></returns>
public String GetDataFormatString(NPOI.HSSF.Model.InternalWorkbook workbook)
{
HSSFDataFormat format = new HSSFDataFormat(workbook);
return format.GetFormat(DataFormat);
}
/// <summary>
/// Set the font for this style
/// </summary>
/// <param name="font">a font object Created or retreived from the HSSFWorkbook object</param>
public void SetFont(NPOI.SS.UserModel.IFont font)
{
_format.IsIndentNotParentFont=(true);
short fontindex = font.Index;
_format.FontIndex=(fontindex);
}
/// <summary>
/// Gets the index of the font for this style.
/// </summary>
/// <value>The index of the font.</value>
public short FontIndex
{
get { return _format.FontIndex; }
}
/// <summary>
/// Gets the font for this style
/// </summary>
/// <param name="parentWorkbook">The parent workbook that this style belongs to.</param>
/// <returns></returns>
public IFont GetFont(IWorkbook parentWorkbook)
{
return ((HSSFWorkbook)parentWorkbook).GetFontAt(FontIndex);
}
/// <summary>
/// Get whether the cell's using this style are to be hidden
/// </summary>
/// <value>whether the cell using this style should be hidden</value>
public bool IsHidden
{
get { return _format.IsHidden; }
set
{
_format.IsIndentNotParentCellOptions=(true);
_format.IsHidden=(value);
}
}
/// <summary>
/// Get whether the cell's using this style are to be locked
/// </summary>
/// <value>whether the cell using this style should be locked</value>
public bool IsLocked
{
get { return _format.IsLocked; }
set
{
_format.IsIndentNotParentCellOptions=(true);
_format.IsLocked=(value);
}
}
/// <summary>
/// Get the type of horizontal alignment for the cell
/// </summary>
/// <value> the type of alignment</value>
public HorizontalAlignment Alignment
{
get { return (HorizontalAlignment)_format.Alignment; }
set
{
_format.IsIndentNotParentAlignment=(true);
_format.Alignment=(short)value;
}
}
/// <summary>
/// Gets or sets a value indicating whether the text should be wrapped
/// </summary>
/// <value><c>true</c> if [wrap text]; otherwise, <c>false</c>.</value>
public bool WrapText
{
get
{
return _format.WrapText;
}
set
{
_format.IsIndentNotParentAlignment = (true);
_format.WrapText = (value);
}
}
/// <summary>
/// Gets or sets the vertical alignment for the cell.
/// </summary>
/// <value>the type of alignment</value>
public VerticalAlignment VerticalAlignment
{
get
{
return (VerticalAlignment)_format.VerticalAlignment;
}
set { _format.VerticalAlignment=(short)value; }
}
/// <summary>
/// Gets or sets the degree of rotation for the text in the cell
/// </summary>
/// <value>The rotation degrees (between -90 and 90 degrees).</value>
public short Rotation
{
get
{
short rotation = _format.Rotation;
if (rotation == 0xff)
{
return rotation;
}
if (rotation > 90)
//This is actually the 4th quadrant
rotation = (short)(90 - rotation);
return rotation;
}
set
{
short rotation = value;
if (rotation == 0xff)
{
}else if ((value < 0) && (value >= -90))
{
//Take care of the funny 4th quadrant Issue
//The 4th quadrant (-1 to -90) is stored as (91 to 180)
rotation = (short)(90 - value);
}
else if ((value < -90) || (value > 90))
{
//Do not allow an incorrect rotation to be Set
throw new ArgumentException("The rotation must be between -90 and 90 degrees, or 0xff");
}
_format.Rotation=(rotation);
}
}
/// <summary>
/// Verifies that this style belongs to the supplied Workbook.
/// Will throw an exception if it belongs to a different one.
/// This is normally called when trying to assign a style to a
/// cell, to ensure the cell and the style are from the same
/// workbook (if they're not, it won't work)
/// </summary>
/// <param name="wb">The workbook.</param>
public void VerifyBelongsToWorkbook(HSSFWorkbook wb)
{
if (wb.Workbook != _workbook)
{
throw new ArgumentException("This Style does not belong to the supplied Workbook. Are you trying to assign a style from one workbook to the cell of a differnt workbook?");
}
}
/// <summary>
/// Gets or sets the number of spaces to indent the text in the cell
/// </summary>
/// <value>number of spaces</value>
public short Indention
{
get{return _format.Indent;}
set { _format.Indent = (value); }
}
/// <summary>
/// Gets or sets the type of border to use for the left border of the cell
/// </summary>
/// <value>The border type.</value>
public BorderStyle BorderLeft
{
get { return (BorderStyle)_format.BorderLeft; }
set
{
_format.IsIndentNotParentBorder=(true);
_format.BorderLeft=(short)value;
}
}
/// <summary>
/// Gets or sets the type of border to use for the right border of the cell
/// </summary>
/// <value>The border type.</value>
public BorderStyle BorderRight
{
get { return (BorderStyle)_format.BorderRight; }
set
{
_format.IsIndentNotParentBorder = (true);
_format.BorderRight = (short)value;
}
}
/// <summary>
/// Gets or sets the type of border to use for the top border of the cell
/// </summary>
/// <value>The border type.</value>
public BorderStyle BorderTop
{
get { return (BorderStyle)_format.BorderTop; }
set
{
_format.IsIndentNotParentBorder = (true);
_format.BorderTop = (short)value;
}
}
/// <summary>
/// Gets or sets the type of border to use for the bottom border of the cell
/// </summary>
/// <value>The border type.</value>
public BorderStyle BorderBottom
{
get { return (BorderStyle)_format.BorderBottom; }
set
{
_format.IsIndentNotParentBorder = true;
_format.BorderBottom = (short)value;
}
}
/// <summary>
/// Gets or sets the color to use for the left border
/// </summary>
/// <value>The index of the color definition</value>
public short LeftBorderColor
{
get { return _format.LeftBorderPaletteIdx; }
set { _format.LeftBorderPaletteIdx = (value); }
}
/// <summary>
/// Gets or sets the color to use for the left border.
/// </summary>
/// <value>The index of the color definition</value>
public short RightBorderColor
{
get { return _format.RightBorderPaletteIdx; }
set { _format.RightBorderPaletteIdx = (value); }
}
/// <summary>
/// Gets or sets the color to use for the top border
/// </summary>
/// <value>The index of the color definition.</value>
public short TopBorderColor
{
get { return _format.TopBorderPaletteIdx; }
set { _format.TopBorderPaletteIdx = (value); }
}
/// <summary>
/// Gets or sets the color to use for the left border
/// </summary>
/// <value>The index of the color definition.</value>
public short BottomBorderColor
{
get { return _format.BottomBorderPaletteIdx; }
set { _format.BottomBorderPaletteIdx = (value); }
}
/// <summary>
/// Gets or sets the color to use for the diagional border
/// </summary>
/// <value>The index of the color definition.</value>
public short BorderDiagonalColor
{
get { return _format.AdtlDiagBorderPaletteIdx; }
set { _format.AdtlDiagBorderPaletteIdx = value; }
}
/// <summary>
/// Gets or sets the line type to use for the diagional border
/// </summary>
/// <value>The line type.</value>
public BorderStyle BorderDiagonalLineStyle
{
get { return (BorderStyle)_format.AdtlDiagLineStyle; }
set { _format.AdtlDiagLineStyle=(short)value; }
}
/// <summary>
/// Gets or sets the type of diagional border
/// </summary>.
/// <value>The border diagional type.</value>
public BorderDiagonal BorderDiagonal
{
get { return (BorderDiagonal)_format.Diagonal; }
set { _format.Diagonal = (short)value; }
}
/// <summary>
/// Gets or sets whether the cell is shrink-to-fit
/// </summary>
public bool ShrinkToFit
{
get { return _format.ShrinkToFit; }
set { _format.ShrinkToFit = value; }
}
/**
* Get or set the reading order, for RTL/LTR ordering of
* the text.
* <p>0 means Context (Default), 1 means Left To Right,
* and 2 means Right to Left</p>
*
* @return order - the reading order (0,1,2)
*/
public short ReadingOrder
{
get
{
return _format.ReadingOrder;
}
set
{
_format.ReadingOrder = (value);
}
}
/// <summary>
/// Gets or sets the fill pattern. - Set to 1 to Fill with foreground color
/// </summary>
/// <value>The fill pattern.</value>
public FillPattern FillPattern
{
get
{
return (FillPattern)_format.AdtlFillPattern;
}
set { _format.AdtlFillPattern=(short)value; }
}
/// <summary>
/// Checks if the background and foreground Fills are Set correctly when one
/// or the other is Set to the default color.
/// Works like the logic table below:
/// BACKGROUND FOREGROUND
/// NONE AUTOMATIC
/// 0x41 0x40
/// NONE RED/ANYTHING
/// 0x40 0xSOMETHING
/// </summary>
private void CheckDefaultBackgroundFills()
{
if (_format.FillForeground == HSSFColor.Automatic.Index)
{
//JMH: Why +1, hell why not. I guess it made some sense to someone at the time. Doesnt
//to me now.... But experience has shown that when the fore is Set to AUTOMATIC then the
//background needs to be incremented......
if (_format.FillBackground != (HSSFColor.Automatic.Index + 1))
FillBackgroundColor = HSSFColor.Automatic.Index + 1;
}
else if (_format.FillBackground == HSSFColor.Automatic.Index + 1)
//Now if the forground Changes to a non-AUTOMATIC color the background Resets itself!!!
if (_format.FillForeground != HSSFColor.Automatic.Index)
FillBackgroundColor=(HSSFColor.Automatic.Index);
}
/**
* Clones all the style information from another
* HSSFCellStyle, onto this one. This
* HSSFCellStyle will then have all the same
* properties as the source, but the two may
* be edited independently.
* Any stylings on this HSSFCellStyle will be lost!
*
* The source HSSFCellStyle could be from another
* HSSFWorkbook if you like. This allows you to
* copy styles from one HSSFWorkbook to another.
*/
public void CloneStyleFrom(ICellStyle source)
{
if (source is HSSFCellStyle)
{
this.CloneStyleFrom((HSSFCellStyle)source);
}
else
{
throw new ArgumentException("Can only clone from one HSSFCellStyle to another, not between HSSFCellStyle and XSSFCellStyle");
}
}
/// <summary>
/// Clones all the style information from another
/// HSSFCellStyle, onto this one. This
/// HSSFCellStyle will then have all the same
/// properties as the source, but the two may
/// be edited independently.
/// Any stylings on this HSSFCellStyle will be lost!
/// The source HSSFCellStyle could be from another
/// HSSFWorkbook if you like. This allows you to
/// copy styles from one HSSFWorkbook to another.
/// </summary>
/// <param name="source">The source.</param>
public void CloneStyleFrom(HSSFCellStyle source)
{
// First we need to clone the extended format
// record
_format.CloneStyleFrom(source._format);
// Handle matching things if we cross workbooks
if (_workbook != source._workbook)
{
lastDateFormat = short.MinValue;
lastFormats = null;
getDataFormatStringCache = null;
// Then we need to clone the format string,
// and update the format record for this
short fmt = (short)_workbook.CreateFormat(
source.GetDataFormatString()
);
this.DataFormat=(fmt);
// Finally we need to clone the font,
// and update the format record for this
FontRecord fr = _workbook.CreateNewFont();
fr.CloneStyleFrom(
source._workbook.GetFontRecordAt(
source.FontIndex
)
);
HSSFFont font = new HSSFFont(
(short)_workbook.GetFontIndex(fr), fr
);
this.SetFont(font);
}
}
/// <summary>
/// Gets or sets the color of the fill background.
/// </summary>
/// <value>The color of the fill background.</value>
/// Set the background Fill color.
/// <example>
/// cs.SetFillPattern(HSSFCellStyle.FINE_DOTS );
/// cs.SetFillBackgroundColor(new HSSFColor.RED().Index);
/// optionally a Foreground and background Fill can be applied:
/// Note: Ensure Foreground color is Set prior to background
/// cs.SetFillPattern(HSSFCellStyle.FINE_DOTS );
/// cs.SetFillForegroundColor(new HSSFColor.BLUE().Index);
/// cs.SetFillBackgroundColor(new HSSFColor.RED().Index);
/// or, for the special case of SOLID_Fill:
/// cs.SetFillPattern(HSSFCellStyle.SOLID_FOREGROUND );
/// cs.SetFillForegroundColor(new HSSFColor.RED().Index);
/// It is necessary to Set the Fill style in order
/// for the color to be shown in the cell.
/// </example>
public short FillBackgroundColor
{
get
{
short result = _format.FillBackground;
//JMH: Do this ridiculous conversion, and let HSSFCellStyle
//internally migrate back and forth
if (result == (HSSFColor.Automatic.Index + 1))
return HSSFColor.Automatic.Index;
else return result;
}
set
{
_format.FillBackground=value;
CheckDefaultBackgroundFills();
}
}
public IColor FillBackgroundColorColor
{
get
{
HSSFPalette pallette = new HSSFPalette(_workbook.CustomPalette);
return pallette.GetColor(FillBackgroundColor);
}
}
/// <summary>
/// Gets or sets the foreground Fill color
/// </summary>
/// <value>Fill color.</value>
/// @see org.apache.poi.hssf.usermodel.HSSFPalette#GetColor(short)
public short FillForegroundColor
{
get{return _format.FillForeground;}
set
{
_format.FillForeground = value;
CheckDefaultBackgroundFills();
}
}
public IColor FillForegroundColorColor
{
get
{
HSSFPalette pallette = new HSSFPalette(_workbook.CustomPalette);
return pallette.GetColor(FillForegroundColor);
}
}
/**
* Gets the name of the user defined style.
* Returns null for built in styles, and
* styles where no name has been defined
*/
public String UserStyleName
{
get
{
StyleRecord sr = _workbook.GetStyleRecord(index);
if (sr == null)
{
return null;
}
if (sr.IsBuiltin)
{
return null;
}
return sr.Name;
}
set
{
StyleRecord sr = _workbook.GetStyleRecord(index);
if (sr == null)
{
sr = _workbook.CreateStyleRecord(index);
}
// All Style records start as "builtin", but generally
// only 20 and below really need to be
if (sr.IsBuiltin && index <= 20)
{
throw new ArgumentException("Unable to set user specified style names for built in styles!");
}
sr.Name = value;
}
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"/>.
/// </returns>
public override int GetHashCode()
{
int prime = 31;
int result = 1;
result = prime * result + ((_format == null) ? 0 : _format.GetHashCode());
result = prime * result + index;
return result;
}
/// <summary>
/// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>.
/// </summary>
/// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param>
/// <returns>
/// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false.
/// </returns>
/// <exception cref="T:System.NullReferenceException">
/// The <paramref name="obj"/> parameter is null.
/// </exception>
public override bool Equals(Object obj)
{
if (this == obj) return true;
if (obj == null) return false;
if (obj is HSSFCellStyle)
{
HSSFCellStyle other = (HSSFCellStyle)obj;
if (_format == null)
{
if (other._format != null)
return false;
}
else if (!_format.Equals(other._format))
return false;
if (index != other.index)
return false;
return true;
}
return false;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace PomfSharpApi.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="XmlDiffViewNodes.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Xml;
using System.IO;
using System.Diagnostics;
namespace Microsoft.XmlDiffPatch {
internal abstract class XmlDiffViewNode {
internal class ChangeInfo {
internal string _localName;
internal string _prefix; // publicId if DocumentType node
internal string _ns; // systemId if DocumentType node
internal string _value; // internal subset if DocumentType node
}
// node type
internal XmlNodeType _nodeType;
// tree pointers
internal XmlDiffViewNode _nextSibbling = null;
internal XmlDiffViewNode _parent = null;
// diff operation
internal XmlDiffViewOperation _op = XmlDiffViewOperation.Match;
internal int _opid = 0; // operation id
// a place to store change information (only if _op == XmlDiffViewOperation.Change)
internal ChangeInfo _changeInfo = null;
internal XmlDiffViewNode( XmlNodeType nodeType ) {
_nodeType = nodeType;
}
internal abstract string OuterXml { get; }
internal virtual XmlDiffViewNode FirstChildNode { get { return null; } }
internal abstract XmlDiffViewNode Clone( bool bDeep );
internal abstract void DrawHtml( XmlWriter writer, int indent );
internal void DrawHtmlNoChange( XmlWriter writer, int indent ) {
Debug.Assert( _nodeType != XmlNodeType.Element && _nodeType != XmlNodeType.Attribute );
Debug.Assert( _op != XmlDiffViewOperation.Change );
XmlDiffView.HtmlStartRow( writer );
for ( int i = 0; i < 2; i++ ) {
XmlDiffView.HtmlStartCell( writer, indent );
if ( XmlDiffView.HtmlWriteToPane[(int)_op,i] ) {
bool bCloseElement = OutputNavigation( writer );
XmlDiffView.HtmlWriteString( writer, _op, OuterXml );
if ( bCloseElement ) {
writer.WriteEndElement();
}
}
else {
XmlDiffView.HtmlWriteEmptyString( writer );
}
XmlDiffView.HtmlEndCell( writer );
}
XmlDiffView.HtmlEndRow( writer );
}
protected bool OutputNavigation( XmlWriter writer ) {
if ( _parent == null || _parent._op != _op ) {
switch ( _op ) {
case XmlDiffViewOperation.MoveFrom:
writer.WriteStartElement( "a" );
writer.WriteAttributeString( "name", "move_from_" + _opid );
writer.WriteEndElement();
writer.WriteStartElement( "a" );
writer.WriteAttributeString( "href", "#move_to_" + _opid );
return true;
case XmlDiffViewOperation.MoveTo:
writer.WriteStartElement( "a" );
writer.WriteAttributeString( "name", "move_to_" + _opid );
writer.WriteEndElement();
writer.WriteStartElement( "a" );
writer.WriteAttributeString( "href", "#move_from_" + _opid );
return true;
}
}
return false;
}
}
internal abstract class XmlDiffViewParentNode : XmlDiffViewNode
{
// child nodes
internal XmlDiffViewNode _childNodes;
// number of source child nodes
internal int _sourceChildNodesCount;
// source nodes indexed by their relative position
XmlDiffViewNode[] _sourceChildNodesIndex;
internal XmlDiffViewParentNode( XmlNodeType nodeType ) : base( nodeType ) {}
internal override XmlDiffViewNode FirstChildNode{ get { return _childNodes; } }
internal XmlDiffViewNode GetSourceChildNode( int index ) {
if (index < 0 || index >= _sourceChildNodesCount || _sourceChildNodesCount == 0)
throw new ArgumentException( "index" );
if ( _sourceChildNodesCount == 0 )
return null;
if ( _sourceChildNodesIndex == null )
CreateSourceNodesIndex();
return _sourceChildNodesIndex[index];
}
internal void CreateSourceNodesIndex()
{
if (_sourceChildNodesIndex != null || _sourceChildNodesCount == 0)
return;
_sourceChildNodesIndex = new XmlDiffViewNode[_sourceChildNodesCount];
XmlDiffViewNode curChild = _childNodes;
for ( int i = 0; i < _sourceChildNodesCount; i++, curChild = curChild._nextSibbling ) {
Debug.Assert( curChild != null );
_sourceChildNodesIndex[i] = curChild;
}
Debug.Assert( curChild == null );
}
internal void InsertChildAfter( XmlDiffViewNode newChild, XmlDiffViewNode referenceChild, bool bSourceNode ) {
Debug.Assert( newChild != null );
if ( referenceChild == null ) {
newChild._nextSibbling = _childNodes;
_childNodes = newChild;
}
else {
newChild._nextSibbling = referenceChild._nextSibbling;
referenceChild._nextSibbling = newChild;
}
if ( bSourceNode )
_sourceChildNodesCount++;
newChild._parent = this;
}
internal void HtmlDrawChildNodes( XmlWriter writer, int indent ) {
XmlDiffViewNode curChild = _childNodes;
while ( curChild != null ) {
curChild.DrawHtml( writer, indent );
curChild = curChild._nextSibbling;
}
}
}
internal class XmlDiffViewDocument : XmlDiffViewParentNode
{
internal XmlDiffViewDocument() : base( XmlNodeType.Document ) {
}
internal override string OuterXml {
get {
throw new Exception( "OuterXml is not supported on XmlDiffViewElement." );
}
}
internal override XmlDiffViewNode Clone( bool bDeep ) {
throw new Exception( "Clone method should never be called on a document node." );
}
internal override void DrawHtml( XmlWriter writer, int indent ) {
HtmlDrawChildNodes( writer, indent );
}
}
internal class XmlDiffViewElement : XmlDiffViewParentNode
{
// name
internal string _localName;
internal string _prefix;
internal string _ns;
internal string _name;
// attributes
internal XmlDiffViewAttribute _attributes;
bool _ignorePrefixes;
internal XmlDiffViewElement( string localName, string prefix, string ns, bool ignorePrefixes ) : base( XmlNodeType.Element ) {
_localName = localName;
_prefix = prefix;
_ns = ns;
if ( _prefix != string.Empty )
_name = _prefix + ":" + _localName;
else
_name = _localName;
_ignorePrefixes = ignorePrefixes;
}
internal XmlDiffViewAttribute GetAttribute( string name ) {
XmlDiffViewAttribute curAttr = _attributes;
while ( curAttr != null ) {
if ( curAttr._name == name && curAttr._op == XmlDiffViewOperation.Match )
return curAttr;
curAttr = (XmlDiffViewAttribute)curAttr._nextSibbling;
}
return null;
}
internal void InsertAttributeAfter( XmlDiffViewAttribute newAttr, XmlDiffViewAttribute refAttr ) {
Debug.Assert( newAttr != null );
if ( refAttr == null ) {
newAttr._nextSibbling = _attributes;
_attributes = newAttr;
}
else {
newAttr._nextSibbling = refAttr._nextSibbling;
refAttr._nextSibbling = newAttr;
}
newAttr._parent = this;
}
internal override string OuterXml {
get {
throw new Exception( "OuterXml is not supported on XmlDiffViewElement." );
}
}
internal override XmlDiffViewNode Clone( bool bDeep ) {
XmlDiffViewElement newElement = new XmlDiffViewElement( _localName, _prefix, _ns, _ignorePrefixes );
// attributes
{
XmlDiffViewAttribute curAttr = _attributes;
XmlDiffViewAttribute lastNewAtt = null;
while ( curAttr != null ) {
XmlDiffViewAttribute newAttr = (XmlDiffViewAttribute)curAttr.Clone( true );
newElement.InsertAttributeAfter( newAttr, lastNewAtt );
lastNewAtt = newAttr;
curAttr = (XmlDiffViewAttribute)curAttr._nextSibbling;
}
}
if ( !bDeep )
return newElement;
// child nodes
{
XmlDiffViewNode curChild = _childNodes;
XmlDiffViewNode lastNewChild = null;
while ( curChild != null ) {
XmlDiffViewNode newChild = curChild.Clone( true );
newElement.InsertChildAfter( newChild, lastNewChild, false );
lastNewChild = newChild;
curChild = curChild._nextSibbling;
}
}
return newElement;
}
internal override void DrawHtml( XmlWriter writer, int indent ) {
XmlDiffViewOperation opForColor = _op;
bool bCloseElement = false;
XmlDiffView.HtmlStartRow( writer );
for ( int i = 0; i < 2; i++ ) {
XmlDiffView.HtmlStartCell( writer, indent );
if ( XmlDiffView.HtmlWriteToPane[(int)_op,i] ) {
bCloseElement = OutputNavigation( writer );
if ( _op == XmlDiffViewOperation.Change ) {
opForColor = XmlDiffViewOperation.Match;
XmlDiffView.HtmlWriteString( writer, opForColor, "<" );
if ( i == 0 )
DrawHtmlNameChange( writer, _localName, _prefix );
else
DrawHtmlNameChange( writer, _changeInfo._localName, _changeInfo._prefix );
}
else {
DrawHtmlName( writer, opForColor, "<", string.Empty );
}
if ( bCloseElement ) {
writer.WriteEndElement();
bCloseElement = false;
}
// attributes
DrawHtmlAttributes( writer, i );
// close start tag
if ( _childNodes != null )
XmlDiffView.HtmlWriteString( writer, opForColor, ">" );
else
XmlDiffView.HtmlWriteString( writer, opForColor, "/>" );
}
else
XmlDiffView.HtmlWriteEmptyString( writer );
XmlDiffView.HtmlEndCell( writer );
}
XmlDiffView.HtmlEndRow( writer );
// child nodes
if ( _childNodes != null ) {
HtmlDrawChildNodes( writer, indent + XmlDiffView.DeltaIndent );
// end element
XmlDiffView.HtmlStartRow( writer );
for ( int i = 0; i < 2; i++ ) {
XmlDiffView.HtmlStartCell( writer, indent );
if ( XmlDiffView.HtmlWriteToPane[(int)_op,i] ) {
if ( _op == XmlDiffViewOperation.Change ) {
Debug.Assert( opForColor == XmlDiffViewOperation.Match );
XmlDiffView.HtmlWriteString( writer, opForColor, "</" );
if ( i == 0 )
DrawHtmlNameChange( writer, _localName, _prefix );
else
DrawHtmlNameChange( writer, _changeInfo._localName, _changeInfo._prefix );
XmlDiffView.HtmlWriteString( writer, opForColor, ">" );
}
else {
DrawHtmlName( writer, opForColor, "</", ">" );
}
}
else
XmlDiffView.HtmlWriteEmptyString( writer );
XmlDiffView.HtmlEndCell( writer );
}
XmlDiffView.HtmlEndRow( writer );
}
}
private void DrawHtmlAttributes( XmlWriter writer, int paneNo ) {
if ( _attributes == null )
return;
string attrIndent = string.Empty;
if ( _attributes._nextSibbling != null ) {
attrIndent = XmlDiffView.GetIndent( _name.Length + 2 );
}
XmlDiffViewAttribute curAttr = _attributes;
while ( curAttr != null ) {
if ( XmlDiffView.HtmlWriteToPane[(int)curAttr._op, paneNo ] ) {
if ( curAttr == _attributes )
writer.WriteString( " " );
else
writer.WriteRaw( attrIndent );
if ( curAttr._op == XmlDiffViewOperation.Change ) {
if ( paneNo == 0 )
DrawHtmlAttributeChange( writer, curAttr, curAttr._localName, curAttr._prefix, curAttr._value );
else
DrawHtmlAttributeChange( writer, curAttr, curAttr._changeInfo._localName, curAttr._changeInfo._prefix,
curAttr._changeInfo._value );
}
else {
DrawHtmlAttribute( writer, curAttr, curAttr._op );
}
}
else
XmlDiffView.HtmlWriteEmptyString( writer );
curAttr = (XmlDiffViewAttribute)curAttr._nextSibbling;
if ( curAttr != null )
XmlDiffView.HtmlBr( writer );
}
}
private void DrawHtmlNameChange( XmlWriter writer, string localName, string prefix ) {
if ( prefix != string.Empty ) {
XmlDiffView.HtmlWriteString( writer, _ignorePrefixes ? XmlDiffViewOperation.Ignore :
(_prefix == _changeInfo._prefix) ? XmlDiffViewOperation.Match : XmlDiffViewOperation.Change,
prefix + ":" );
}
XmlDiffView.HtmlWriteString( writer,
(_localName == _changeInfo._localName) ? XmlDiffViewOperation.Match : XmlDiffViewOperation.Change,
localName );
}
private void DrawHtmlName( XmlWriter writer, XmlDiffViewOperation opForColor, string tagStart, string tagEnd ) {
if ( _prefix != string.Empty && _ignorePrefixes ) {
XmlDiffView.HtmlWriteString( writer, opForColor, tagStart );
XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Ignore, _prefix + ":" );
XmlDiffView.HtmlWriteString( writer, opForColor, _localName + tagEnd );
}
else {
XmlDiffView.HtmlWriteString( writer, opForColor, tagStart + _name + tagEnd );
}
}
private void DrawHtmlAttributeChange( XmlWriter writer, XmlDiffViewAttribute attr, string localName, string prefix, string value ) {
if ( prefix != string.Empty ) {
XmlDiffView.HtmlWriteString( writer,
_ignorePrefixes ? XmlDiffViewOperation.Ignore :
(attr._prefix == attr._changeInfo._prefix) ? XmlDiffViewOperation.Match : XmlDiffViewOperation.Change,
prefix + ":" );
}
XmlDiffView.HtmlWriteString( writer,
(attr._localName == attr._changeInfo._localName) ? XmlDiffViewOperation.Match : XmlDiffViewOperation.Change,
localName );
if ( attr._value != attr._changeInfo._value ) {
XmlDiffView.HtmlWriteString( writer, "=\"" );
XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Change, value );
XmlDiffView.HtmlWriteString( writer, "\"" );
}
else {
XmlDiffView.HtmlWriteString( writer, "=\"" + value + "\"" );
}
}
private void DrawHtmlAttribute( XmlWriter writer, XmlDiffViewAttribute attr, XmlDiffViewOperation opForColor ) {
if ( _ignorePrefixes ) {
if ( attr._prefix == "xmlns" || ( attr._localName == "xmlns" && attr._prefix == string.Empty ) ) {
XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Ignore, attr._name );
XmlDiffView.HtmlWriteString( writer, opForColor , "=\"" + attr._value + "\"" );
return;
}
else if ( attr._prefix != string.Empty ) {
XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Ignore, attr._prefix + ":" );
XmlDiffView.HtmlWriteString( writer, opForColor , attr._localName + "=\"" + attr._value + "\"" );
return;
}
}
XmlDiffView.HtmlWriteString( writer, opForColor , attr._name + "=\"" + attr._value + "\"" );
}
}
internal class XmlDiffViewAttribute : XmlDiffViewNode
{
// name
internal string _localName;
internal string _prefix;
internal string _ns;
internal string _name; // == _prefix + ":" + _localName;
// value
internal string _value;
internal XmlDiffViewAttribute( string localName, string prefix, string ns, string name, string value ) : base( XmlNodeType.Attribute ) {
_localName = localName;
_prefix = prefix;
_ns = ns;
_value = value;
_name = name;
}
internal XmlDiffViewAttribute( string localName, string prefix, string ns, string value ) : base( XmlNodeType.Attribute ) {
_localName = localName;
_prefix = prefix;
_ns = ns;
_value = value;
if ( prefix == string.Empty )
_name = _localName;
else
_name = _prefix + ":" + _localName;
}
internal override string OuterXml {
get {
string outerXml = string.Empty;
if ( _prefix != string.Empty )
outerXml = _prefix + ":";
outerXml += _localName + "=\"" + _value + "\"";
return outerXml;
}
}
internal override XmlDiffViewNode Clone( bool bDeep ) {
return new XmlDiffViewAttribute( _localName, _prefix, _name, _ns, _value );
}
internal override void DrawHtml( XmlWriter writer, int indent ) {
throw new Exception( "This methods should never be called." );
}
}
internal class XmlDiffViewCharData : XmlDiffViewNode
{
internal string _value;
internal XmlDiffViewCharData( string value, XmlNodeType nodeType ) : base( nodeType ) {
_value = value;
}
internal override string OuterXml {
get {
switch ( _nodeType )
{
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
return _value;
case XmlNodeType.Comment:
return "<!--" + _value + "-->";
case XmlNodeType.CDATA:
return "<!CDATA[" + _value + "]]>";
default:
Debug.Assert( false, "Invalid node type." );
return string.Empty;
}
}
}
internal override XmlDiffViewNode Clone( bool bDeep ) {
return new XmlDiffViewCharData( _value, _nodeType );
}
internal override void DrawHtml( XmlWriter writer, int indent ) {
if ( _op == XmlDiffViewOperation.Change ) {
string openString = string.Empty;
string closeString = string.Empty;
if ( _nodeType == XmlNodeType.CDATA ) {
openString = "<!CDATA[";
closeString = "]]>";
}
else if ( _nodeType == XmlNodeType.Comment ) {
openString = "<!--";
closeString = "-->";
}
XmlDiffView.HtmlStartRow( writer );
XmlDiffView.HtmlStartCell( writer, indent );
if ( openString != string.Empty ) {
XmlDiffView.HtmlWriteString( writer, openString );
XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Change, _value );
XmlDiffView.HtmlWriteString( writer, closeString );
}
else
XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Change, _value );
XmlDiffView.HtmlEndCell( writer );
XmlDiffView.HtmlStartCell( writer, indent );
if ( openString != string.Empty ) {
XmlDiffView.HtmlWriteString( writer, openString );
XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Change, _changeInfo._value );
XmlDiffView.HtmlWriteString( writer, closeString );
}
else
XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Change, _changeInfo._value );
XmlDiffView.HtmlEndCell( writer );
XmlDiffView.HtmlEndRow( writer );
}
else {
DrawHtmlNoChange( writer, indent );
}
}
}
internal class XmlDiffViewPI : XmlDiffViewCharData
{
internal string _name;
internal XmlDiffViewPI( string name, string value ) : base( value, XmlNodeType.ProcessingInstruction ) {
_name = name;
}
internal override string OuterXml {
get { return "<?" + _name + " " + _value + "?>"; }
}
internal override XmlDiffViewNode Clone( bool bDeep ) {
return new XmlDiffViewPI( _name, _value );
}
internal override void DrawHtml( XmlWriter writer, int indent ) {
if ( _op == XmlDiffViewOperation.Change ) {
XmlDiffViewOperation nameOp = (_name == _changeInfo._localName) ? XmlDiffViewOperation.Match : XmlDiffViewOperation.Change;
XmlDiffViewOperation valueOp = (_value == _changeInfo._value) ? XmlDiffViewOperation.Match : XmlDiffViewOperation.Change;
XmlDiffView.HtmlStartRow( writer );
XmlDiffView.HtmlStartCell( writer, indent );
XmlDiffView.HtmlWriteString( writer, "<?" );
XmlDiffView.HtmlWriteString( writer, nameOp, _name );
XmlDiffView.HtmlWriteString( writer, " " );
XmlDiffView.HtmlWriteString( writer, valueOp, _value );
XmlDiffView.HtmlWriteString( writer, "?>" );
XmlDiffView.HtmlEndCell( writer );
XmlDiffView.HtmlStartCell( writer, indent );
XmlDiffView.HtmlWriteString( writer, "<?" );
XmlDiffView.HtmlWriteString( writer, nameOp, _changeInfo._localName );
XmlDiffView.HtmlWriteString( writer, " " );
XmlDiffView.HtmlWriteString( writer, valueOp, _changeInfo._value );
XmlDiffView.HtmlWriteString( writer, "?>" );
XmlDiffView.HtmlEndCell( writer );
XmlDiffView.HtmlEndRow( writer );
}
else {
DrawHtmlNoChange( writer, indent );
}
}
}
internal class XmlDiffViewER : XmlDiffViewNode
{
string _name;
internal XmlDiffViewER( string name ) : base( XmlNodeType.EntityReference ) {
_name = name;
}
internal override string OuterXml {
get { return "&" + _name + ";"; }
}
internal override XmlDiffViewNode Clone( bool bDeep ) {
return new XmlDiffViewER( _name );
}
internal override void DrawHtml( XmlWriter writer, int indent ) {
if ( _op == XmlDiffViewOperation.Change ) {
Debug.Assert( _name != _changeInfo._localName );
XmlDiffView.HtmlStartRow( writer );
XmlDiffView.HtmlStartCell( writer, indent );
XmlDiffView.HtmlWriteString( writer, "&" );
XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Change, _name );
XmlDiffView.HtmlWriteString( writer, ";" );
XmlDiffView.HtmlEndCell( writer );
XmlDiffView.HtmlStartCell( writer, indent );
XmlDiffView.HtmlWriteString( writer, "&" );
XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Change, _changeInfo._localName );
XmlDiffView.HtmlWriteString( writer, ";" );
XmlDiffView.HtmlEndCell( writer );
XmlDiffView.HtmlEndRow( writer );
}
else {
DrawHtmlNoChange( writer, indent );
}
}
}
internal class XmlDiffViewDocumentType : XmlDiffViewNode
{
internal string _name;
internal string _systemId;
internal string _publicId;
internal string _subset;
internal XmlDiffViewDocumentType( string name, string publicId, string systemId, string subset ) : base( XmlNodeType.DocumentType ) {
_name = name;
_publicId = ( publicId == null ) ? string.Empty : publicId;
_systemId = ( systemId == null ) ? string.Empty : systemId;
_subset = subset;
}
internal override string OuterXml {
get {
string dtd = "<!DOCTYPE " + _name + " ";
if ( _publicId != string.Empty ) {
dtd += "PUBLIC \"" + _publicId + "\" ";
}
else if ( _systemId != string.Empty ) {
dtd += "SYSTEM \"" + _systemId + "\" ";
}
if ( _subset != string.Empty )
dtd += "[" + _subset + "]";
dtd += ">";
return dtd;
}
}
internal override XmlDiffViewNode Clone( bool bDeep ) {
Debug.Assert( false, "Clone method should never be called on document type node." );
return null;
}
internal override void DrawHtml( XmlWriter writer, int indent ) {
if ( _op == XmlDiffViewOperation.Change ) {
XmlDiffView.HtmlStartRow( writer );
for ( int i = 0; i < 2; i++ ) {
XmlDiffView.HtmlStartCell( writer, indent );
// name
XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Match, "<!DOCTYPE " );
if ( i == 0 )
XmlDiffView.HtmlWriteString( writer, ( _name == _changeInfo._localName) ? XmlDiffViewOperation.Match : XmlDiffViewOperation.Change, _name );
else
XmlDiffView.HtmlWriteString( writer, ( _name == _changeInfo._localName) ? XmlDiffViewOperation.Match : XmlDiffViewOperation.Change, _changeInfo._localName );
XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Match, " " );
string systemString = "SYSTEM ";
// public id
if ( _publicId == _changeInfo._prefix ) {
// match
if ( _publicId != string.Empty ) {
XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Match, "PUBLIC \"" + _publicId + "\" " );
systemString = string.Empty;
}
}
else {
// add
if ( _publicId == string.Empty ) {
if ( i == 1 ) {
XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Add, "PUBLIC \"" + _changeInfo._prefix + "\" " );
systemString = string.Empty;
}
}
// remove
else if ( _changeInfo._prefix == string.Empty ) {
if ( i == 0 ) {
XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Remove, "PUBLIC \"" + _publicId + "\" " );
systemString = string.Empty;
}
}
// change
else {
XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Change, "PUBLIC \"" + ( ( i == 0 ) ? _publicId : _changeInfo._prefix )+ "\" " );
systemString = string.Empty;
}
}
// system id
if ( _systemId == _changeInfo._ns ) {
if ( _systemId != string.Empty ) {
XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Match, systemString + "\"" + _systemId + "\" " );
}
}
else {
// add
if ( _systemId == string.Empty ) {
if ( i == 1 ) {
XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Add, systemString + "\"" + _changeInfo._ns + "\" " );
}
}
// remove
else if ( _changeInfo._prefix == string.Empty ) {
if ( i == 0 ) {
XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Remove, systemString + "\"" + _systemId + "\" " );
}
}
// change
else {
XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Change, systemString + "\"" + ( ( i == 0 ) ? _systemId : _changeInfo._ns ) + "\" " );
}
}
// internal subset
if ( _subset == _changeInfo._value ) {
if ( _subset != string.Empty ) {
XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Match, "[" + _subset + "]" );
}
}
else {
// add
if ( _subset == string.Empty ) {
if ( i == 1 ) {
XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Add, "[" + _changeInfo._value + "]" );
}
}
// remove
else if ( _changeInfo._value == string.Empty ) {
if ( i == 0 ) {
XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Remove, "[" + _subset + "]" );
}
}
// change
else {
XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Change, "[" + ( ( i == 0 ) ? _subset : _changeInfo._value ) + "]" );
}
}
// close start tag
XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Match, ">" );
XmlDiffView.HtmlEndCell( writer );
}
XmlDiffView.HtmlEndRow( writer );
}
else {
DrawHtmlNoChange( writer, indent );
}
}
}
internal class XmlDiffViewXmlDeclaration : XmlDiffViewNode
{
string _value;
internal XmlDiffViewXmlDeclaration( string value ) : base( XmlNodeType.XmlDeclaration ) {
_value = value;
}
internal override string OuterXml {
get { return "<?xml " + _value + "?>"; }
}
internal override XmlDiffViewNode Clone( bool bDeep ) {
return new XmlDiffViewXmlDeclaration( _value );
}
internal override void DrawHtml( XmlWriter writer, int indent ) {
if ( _op == XmlDiffViewOperation.Change ) {
Debug.Assert( _value != _changeInfo._value );
XmlDiffView.HtmlStartRow( writer );
XmlDiffView.HtmlStartCell( writer, indent );
XmlDiffView.HtmlWriteString( writer, "<?xml " );
XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Change, _value );
XmlDiffView.HtmlWriteString( writer, "?>" );
XmlDiffView.HtmlEndCell( writer );
XmlDiffView.HtmlStartCell( writer, indent );
XmlDiffView.HtmlWriteString( writer, "<?xml " );
XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Change, _changeInfo._value );
XmlDiffView.HtmlWriteString( writer, "?>" );
XmlDiffView.HtmlEndCell( writer );
XmlDiffView.HtmlEndRow( writer );
}
else {
DrawHtmlNoChange( writer, indent );
}
}
}
}
| |
//
// 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.Azure.Management.Sql;
using Microsoft.Azure.Management.Sql.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Sql
{
/// <summary>
/// Represents all the operations to manage Azure SQL Database and Database
/// Server Audit policy. Contains operations to: Create, Retrieve and
/// Update audit policy.
/// </summary>
internal partial class AuditingPolicyOperations : IServiceOperations<SqlManagementClient>, IAuditingPolicyOperations
{
/// <summary>
/// Initializes a new instance of the AuditingPolicyOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal AuditingPolicyOperations(SqlManagementClient client)
{
this._client = client;
}
private SqlManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Sql.SqlManagementClient.
/// </summary>
public SqlManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Creates or updates an Azure SQL Database auditing policy.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the auditing
/// policy applies.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for createing or updating a Azure
/// SQL Database auditing policy.
/// </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> CreateOrUpdateDatabasePolicyAsync(string resourceGroupName, string serverName, string databaseName, DatabaseAuditingPolicyCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateDatabasePolicyAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/databases/";
url = url + Uri.EscapeDataString(databaseName);
url = url + "/auditingPolicies/Default";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject databaseAuditingPolicyCreateOrUpdateParametersValue = new JObject();
requestDoc = databaseAuditingPolicyCreateOrUpdateParametersValue;
JObject propertiesValue = new JObject();
databaseAuditingPolicyCreateOrUpdateParametersValue["properties"] = propertiesValue;
if (parameters.Properties.UseServerDefault != null)
{
propertiesValue["useServerDefault"] = parameters.Properties.UseServerDefault;
}
if (parameters.Properties.AuditingState != null)
{
propertiesValue["auditingState"] = parameters.Properties.AuditingState;
}
if (parameters.Properties.EventTypesToAudit != null)
{
propertiesValue["eventTypesToAudit"] = parameters.Properties.EventTypesToAudit;
}
if (parameters.Properties.StorageAccountName != null)
{
propertiesValue["storageAccountName"] = parameters.Properties.StorageAccountName;
}
if (parameters.Properties.StorageAccountKey != null)
{
propertiesValue["storageAccountKey"] = parameters.Properties.StorageAccountKey;
}
if (parameters.Properties.StorageAccountSecondaryKey != null)
{
propertiesValue["storageAccountSecondaryKey"] = parameters.Properties.StorageAccountSecondaryKey;
}
if (parameters.Properties.StorageTableEndpoint != null)
{
propertiesValue["storageTableEndpoint"] = parameters.Properties.StorageTableEndpoint;
}
if (parameters.Properties.StorageAccountResourceGroupName != null)
{
propertiesValue["storageAccountResourceGroupName"] = parameters.Properties.StorageAccountResourceGroupName;
}
if (parameters.Properties.StorageAccountSubscriptionId != null)
{
propertiesValue["storageAccountSubscriptionId"] = parameters.Properties.StorageAccountSubscriptionId;
}
if (parameters.Properties.RetentionDays != null)
{
propertiesValue["retentionDays"] = parameters.Properties.RetentionDays;
}
if (parameters.Properties.AuditLogsTableName != null)
{
propertiesValue["auditLogsTableName"] = parameters.Properties.AuditLogsTableName;
}
if (parameters.Properties.FullAuditLogsTableName != null)
{
propertiesValue["fullAuditLogsTableName"] = parameters.Properties.FullAuditLogsTableName;
}
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
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Creates or updates an Azure SQL Database Server auditing policy.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for createing or updating a Azure
/// SQL Database Server auditing policy.
/// </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> CreateOrUpdateServerPolicyAsync(string resourceGroupName, string serverName, ServerAuditingPolicyCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateServerPolicyAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/auditingPolicies/Default";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject serverAuditingPolicyCreateOrUpdateParametersValue = new JObject();
requestDoc = serverAuditingPolicyCreateOrUpdateParametersValue;
JObject propertiesValue = new JObject();
serverAuditingPolicyCreateOrUpdateParametersValue["properties"] = propertiesValue;
if (parameters.Properties.AuditingState != null)
{
propertiesValue["auditingState"] = parameters.Properties.AuditingState;
}
if (parameters.Properties.EventTypesToAudit != null)
{
propertiesValue["eventTypesToAudit"] = parameters.Properties.EventTypesToAudit;
}
if (parameters.Properties.StorageAccountName != null)
{
propertiesValue["storageAccountName"] = parameters.Properties.StorageAccountName;
}
if (parameters.Properties.StorageAccountKey != null)
{
propertiesValue["storageAccountKey"] = parameters.Properties.StorageAccountKey;
}
if (parameters.Properties.StorageAccountSecondaryKey != null)
{
propertiesValue["storageAccountSecondaryKey"] = parameters.Properties.StorageAccountSecondaryKey;
}
if (parameters.Properties.StorageTableEndpoint != null)
{
propertiesValue["storageTableEndpoint"] = parameters.Properties.StorageTableEndpoint;
}
if (parameters.Properties.StorageAccountResourceGroupName != null)
{
propertiesValue["storageAccountResourceGroupName"] = parameters.Properties.StorageAccountResourceGroupName;
}
if (parameters.Properties.StorageAccountSubscriptionId != null)
{
propertiesValue["storageAccountSubscriptionId"] = parameters.Properties.StorageAccountSubscriptionId;
}
if (parameters.Properties.RetentionDays != null)
{
propertiesValue["retentionDays"] = parameters.Properties.RetentionDays;
}
if (parameters.Properties.AuditLogsTableName != null)
{
propertiesValue["auditLogsTableName"] = parameters.Properties.AuditLogsTableName;
}
if (parameters.Properties.FullAuditLogsTableName != null)
{
propertiesValue["fullAuditLogsTableName"] = parameters.Properties.FullAuditLogsTableName;
}
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
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Returns an Azure SQL Database auditing policy.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the auditing
/// policy applies.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a get database auditing policy request.
/// </returns>
public async Task<DatabaseAuditingPolicyGetResponse> GetDatabasePolicyAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
TracingAdapter.Enter(invocationId, this, "GetDatabasePolicyAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/databases/";
url = url + Uri.EscapeDataString(databaseName);
url = url + "/auditingPolicies/Default";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// 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
DatabaseAuditingPolicyGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DatabaseAuditingPolicyGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
DatabaseAuditingPolicy auditingPolicyInstance = new DatabaseAuditingPolicy();
result.AuditingPolicy = auditingPolicyInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
DatabaseAuditingPolicyProperties propertiesInstance = new DatabaseAuditingPolicyProperties();
auditingPolicyInstance.Properties = propertiesInstance;
JToken useServerDefaultValue = propertiesValue["useServerDefault"];
if (useServerDefaultValue != null && useServerDefaultValue.Type != JTokenType.Null)
{
string useServerDefaultInstance = ((string)useServerDefaultValue);
propertiesInstance.UseServerDefault = useServerDefaultInstance;
}
JToken auditingStateValue = propertiesValue["auditingState"];
if (auditingStateValue != null && auditingStateValue.Type != JTokenType.Null)
{
string auditingStateInstance = ((string)auditingStateValue);
propertiesInstance.AuditingState = auditingStateInstance;
}
JToken eventTypesToAuditValue = propertiesValue["eventTypesToAudit"];
if (eventTypesToAuditValue != null && eventTypesToAuditValue.Type != JTokenType.Null)
{
string eventTypesToAuditInstance = ((string)eventTypesToAuditValue);
propertiesInstance.EventTypesToAudit = eventTypesToAuditInstance;
}
JToken storageAccountNameValue = propertiesValue["storageAccountName"];
if (storageAccountNameValue != null && storageAccountNameValue.Type != JTokenType.Null)
{
string storageAccountNameInstance = ((string)storageAccountNameValue);
propertiesInstance.StorageAccountName = storageAccountNameInstance;
}
JToken storageAccountKeyValue = propertiesValue["storageAccountKey"];
if (storageAccountKeyValue != null && storageAccountKeyValue.Type != JTokenType.Null)
{
string storageAccountKeyInstance = ((string)storageAccountKeyValue);
propertiesInstance.StorageAccountKey = storageAccountKeyInstance;
}
JToken storageAccountSecondaryKeyValue = propertiesValue["storageAccountSecondaryKey"];
if (storageAccountSecondaryKeyValue != null && storageAccountSecondaryKeyValue.Type != JTokenType.Null)
{
string storageAccountSecondaryKeyInstance = ((string)storageAccountSecondaryKeyValue);
propertiesInstance.StorageAccountSecondaryKey = storageAccountSecondaryKeyInstance;
}
JToken storageTableEndpointValue = propertiesValue["storageTableEndpoint"];
if (storageTableEndpointValue != null && storageTableEndpointValue.Type != JTokenType.Null)
{
string storageTableEndpointInstance = ((string)storageTableEndpointValue);
propertiesInstance.StorageTableEndpoint = storageTableEndpointInstance;
}
JToken storageAccountResourceGroupNameValue = propertiesValue["storageAccountResourceGroupName"];
if (storageAccountResourceGroupNameValue != null && storageAccountResourceGroupNameValue.Type != JTokenType.Null)
{
string storageAccountResourceGroupNameInstance = ((string)storageAccountResourceGroupNameValue);
propertiesInstance.StorageAccountResourceGroupName = storageAccountResourceGroupNameInstance;
}
JToken storageAccountSubscriptionIdValue = propertiesValue["storageAccountSubscriptionId"];
if (storageAccountSubscriptionIdValue != null && storageAccountSubscriptionIdValue.Type != JTokenType.Null)
{
string storageAccountSubscriptionIdInstance = ((string)storageAccountSubscriptionIdValue);
propertiesInstance.StorageAccountSubscriptionId = storageAccountSubscriptionIdInstance;
}
JToken retentionDaysValue = propertiesValue["retentionDays"];
if (retentionDaysValue != null && retentionDaysValue.Type != JTokenType.Null)
{
string retentionDaysInstance = ((string)retentionDaysValue);
propertiesInstance.RetentionDays = retentionDaysInstance;
}
JToken auditLogsTableNameValue = propertiesValue["auditLogsTableName"];
if (auditLogsTableNameValue != null && auditLogsTableNameValue.Type != JTokenType.Null)
{
string auditLogsTableNameInstance = ((string)auditLogsTableNameValue);
propertiesInstance.AuditLogsTableName = auditLogsTableNameInstance;
}
JToken fullAuditLogsTableNameValue = propertiesValue["fullAuditLogsTableName"];
if (fullAuditLogsTableNameValue != null && fullAuditLogsTableNameValue.Type != JTokenType.Null)
{
string fullAuditLogsTableNameInstance = ((string)fullAuditLogsTableNameValue);
propertiesInstance.FullAuditLogsTableName = fullAuditLogsTableNameInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
auditingPolicyInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
auditingPolicyInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
auditingPolicyInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
auditingPolicyInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
auditingPolicyInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Returns an Azure SQL Database server auditing policy.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a get database auditing policy request.
/// </returns>
public async Task<ServerAuditingPolicyGetResponse> GetServerPolicyAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
TracingAdapter.Enter(invocationId, this, "GetServerPolicyAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/auditingPolicies/Default";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// 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
ServerAuditingPolicyGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServerAuditingPolicyGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ServerAuditingPolicy auditingPolicyInstance = new ServerAuditingPolicy();
result.AuditingPolicy = auditingPolicyInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ServerAuditingPolicyProperties propertiesInstance = new ServerAuditingPolicyProperties();
auditingPolicyInstance.Properties = propertiesInstance;
JToken auditingStateValue = propertiesValue["auditingState"];
if (auditingStateValue != null && auditingStateValue.Type != JTokenType.Null)
{
string auditingStateInstance = ((string)auditingStateValue);
propertiesInstance.AuditingState = auditingStateInstance;
}
JToken eventTypesToAuditValue = propertiesValue["eventTypesToAudit"];
if (eventTypesToAuditValue != null && eventTypesToAuditValue.Type != JTokenType.Null)
{
string eventTypesToAuditInstance = ((string)eventTypesToAuditValue);
propertiesInstance.EventTypesToAudit = eventTypesToAuditInstance;
}
JToken storageAccountNameValue = propertiesValue["storageAccountName"];
if (storageAccountNameValue != null && storageAccountNameValue.Type != JTokenType.Null)
{
string storageAccountNameInstance = ((string)storageAccountNameValue);
propertiesInstance.StorageAccountName = storageAccountNameInstance;
}
JToken storageAccountKeyValue = propertiesValue["storageAccountKey"];
if (storageAccountKeyValue != null && storageAccountKeyValue.Type != JTokenType.Null)
{
string storageAccountKeyInstance = ((string)storageAccountKeyValue);
propertiesInstance.StorageAccountKey = storageAccountKeyInstance;
}
JToken storageAccountSecondaryKeyValue = propertiesValue["storageAccountSecondaryKey"];
if (storageAccountSecondaryKeyValue != null && storageAccountSecondaryKeyValue.Type != JTokenType.Null)
{
string storageAccountSecondaryKeyInstance = ((string)storageAccountSecondaryKeyValue);
propertiesInstance.StorageAccountSecondaryKey = storageAccountSecondaryKeyInstance;
}
JToken storageTableEndpointValue = propertiesValue["storageTableEndpoint"];
if (storageTableEndpointValue != null && storageTableEndpointValue.Type != JTokenType.Null)
{
string storageTableEndpointInstance = ((string)storageTableEndpointValue);
propertiesInstance.StorageTableEndpoint = storageTableEndpointInstance;
}
JToken storageAccountResourceGroupNameValue = propertiesValue["storageAccountResourceGroupName"];
if (storageAccountResourceGroupNameValue != null && storageAccountResourceGroupNameValue.Type != JTokenType.Null)
{
string storageAccountResourceGroupNameInstance = ((string)storageAccountResourceGroupNameValue);
propertiesInstance.StorageAccountResourceGroupName = storageAccountResourceGroupNameInstance;
}
JToken storageAccountSubscriptionIdValue = propertiesValue["storageAccountSubscriptionId"];
if (storageAccountSubscriptionIdValue != null && storageAccountSubscriptionIdValue.Type != JTokenType.Null)
{
string storageAccountSubscriptionIdInstance = ((string)storageAccountSubscriptionIdValue);
propertiesInstance.StorageAccountSubscriptionId = storageAccountSubscriptionIdInstance;
}
JToken retentionDaysValue = propertiesValue["retentionDays"];
if (retentionDaysValue != null && retentionDaysValue.Type != JTokenType.Null)
{
string retentionDaysInstance = ((string)retentionDaysValue);
propertiesInstance.RetentionDays = retentionDaysInstance;
}
JToken auditLogsTableNameValue = propertiesValue["auditLogsTableName"];
if (auditLogsTableNameValue != null && auditLogsTableNameValue.Type != JTokenType.Null)
{
string auditLogsTableNameInstance = ((string)auditLogsTableNameValue);
propertiesInstance.AuditLogsTableName = auditLogsTableNameInstance;
}
JToken fullAuditLogsTableNameValue = propertiesValue["fullAuditLogsTableName"];
if (fullAuditLogsTableNameValue != null && fullAuditLogsTableNameValue.Type != JTokenType.Null)
{
string fullAuditLogsTableNameInstance = ((string)fullAuditLogsTableNameValue);
propertiesInstance.FullAuditLogsTableName = fullAuditLogsTableNameInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
auditingPolicyInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
auditingPolicyInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
auditingPolicyInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
auditingPolicyInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
auditingPolicyInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
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 postalcodefinder.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;
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Archiver.Codecs {
public class ChallengeEncoder
{
public const ushort BLOCK_LENGTH = 20;
public const ushort TEMPLATE_ID = 59;
public const ushort SCHEMA_ID = 101;
public const ushort SCHEMA_VERSION = 6;
private ChallengeEncoder _parentMessage;
private IMutableDirectBuffer _buffer;
protected int _offset;
protected int _limit;
public ChallengeEncoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IMutableDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public ChallengeEncoder Wrap(IMutableDirectBuffer buffer, int offset)
{
this._buffer = buffer;
this._offset = offset;
Limit(offset + BLOCK_LENGTH);
return this;
}
public ChallengeEncoder WrapAndApplyHeader(
IMutableDirectBuffer buffer, int offset, MessageHeaderEncoder headerEncoder)
{
headerEncoder
.Wrap(buffer, offset)
.BlockLength(BLOCK_LENGTH)
.TemplateId(TEMPLATE_ID)
.SchemaId(SCHEMA_ID)
.Version(SCHEMA_VERSION);
return Wrap(buffer, offset + MessageHeaderEncoder.ENCODED_LENGTH);
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int ControlSessionIdEncodingOffset()
{
return 0;
}
public static int ControlSessionIdEncodingLength()
{
return 8;
}
public static long ControlSessionIdNullValue()
{
return -9223372036854775808L;
}
public static long ControlSessionIdMinValue()
{
return -9223372036854775807L;
}
public static long ControlSessionIdMaxValue()
{
return 9223372036854775807L;
}
public ChallengeEncoder ControlSessionId(long value)
{
_buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian);
return this;
}
public static int CorrelationIdEncodingOffset()
{
return 8;
}
public static int CorrelationIdEncodingLength()
{
return 8;
}
public static long CorrelationIdNullValue()
{
return -9223372036854775808L;
}
public static long CorrelationIdMinValue()
{
return -9223372036854775807L;
}
public static long CorrelationIdMaxValue()
{
return 9223372036854775807L;
}
public ChallengeEncoder CorrelationId(long value)
{
_buffer.PutLong(_offset + 8, value, ByteOrder.LittleEndian);
return this;
}
public static int VersionEncodingOffset()
{
return 16;
}
public static int VersionEncodingLength()
{
return 4;
}
public static int VersionNullValue()
{
return 0;
}
public static int VersionMinValue()
{
return 2;
}
public static int VersionMaxValue()
{
return 16777215;
}
public ChallengeEncoder Version(int value)
{
_buffer.PutInt(_offset + 16, value, ByteOrder.LittleEndian);
return this;
}
public static int EncodedChallengeId()
{
return 4;
}
public static string EncodedChallengeMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int EncodedChallengeHeaderLength()
{
return 4;
}
public ChallengeEncoder PutEncodedChallenge(IDirectBuffer src, int srcOffset, int length)
{
if (length > 1073741824)
{
throw new InvalidOperationException("length > maxValue for type: " + length);
}
int headerLength = 4;
int limit = _parentMessage.Limit();
_parentMessage.Limit(limit + headerLength + length);
_buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian);
_buffer.PutBytes(limit + headerLength, src, srcOffset, length);
return this;
}
public ChallengeEncoder PutEncodedChallenge(byte[] src, int srcOffset, int length)
{
if (length > 1073741824)
{
throw new InvalidOperationException("length > maxValue for type: " + length);
}
int headerLength = 4;
int limit = _parentMessage.Limit();
_parentMessage.Limit(limit + headerLength + length);
_buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian);
_buffer.PutBytes(limit + headerLength, src, srcOffset, length);
return this;
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
ChallengeDecoder writer = new ChallengeDecoder();
writer.Wrap(_buffer, _offset, BLOCK_LENGTH, SCHEMA_VERSION);
return writer.AppendTo(builder);
}
}
}
| |
// 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.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics.QualifyMemberAccess;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics.SimplifyTypeNames
{
internal abstract class SimplifyTypeNamesDiagnosticAnalyzerBase<TLanguageKindEnum> : DiagnosticAnalyzer, IBuiltInAnalyzer where TLanguageKindEnum : struct
{
private static readonly LocalizableString s_localizableMessage = new LocalizableResourceString(nameof(WorkspacesResources.Name_can_be_simplified), WorkspacesResources.ResourceManager, typeof(WorkspacesResources));
private static readonly LocalizableString s_localizableTitleSimplifyNames = new LocalizableResourceString(nameof(FeaturesResources.Simplify_Names), FeaturesResources.ResourceManager, typeof(FeaturesResources));
private static readonly DiagnosticDescriptor s_descriptorSimplifyNames = new DiagnosticDescriptor(IDEDiagnosticIds.SimplifyNamesDiagnosticId,
s_localizableTitleSimplifyNames,
s_localizableMessage,
DiagnosticCategory.Style,
DiagnosticSeverity.Hidden,
isEnabledByDefault: true,
customTags: DiagnosticCustomTags.Unnecessary);
private static readonly LocalizableString s_localizableTitleSimplifyMemberAccess = new LocalizableResourceString(nameof(FeaturesResources.Simplify_Member_Access), FeaturesResources.ResourceManager, typeof(FeaturesResources));
private static readonly DiagnosticDescriptor s_descriptorSimplifyMemberAccess = new DiagnosticDescriptor(IDEDiagnosticIds.SimplifyMemberAccessDiagnosticId,
s_localizableTitleSimplifyMemberAccess,
s_localizableMessage,
DiagnosticCategory.Style,
DiagnosticSeverity.Hidden,
isEnabledByDefault: true,
customTags: DiagnosticCustomTags.Unnecessary);
private static readonly LocalizableString s_localizableTitleRemoveThisOrMe = new LocalizableResourceString(nameof(FeaturesResources.Remove_qualification), FeaturesResources.ResourceManager, typeof(FeaturesResources));
private static readonly DiagnosticDescriptor s_descriptorRemoveThisOrMeHidden = new DiagnosticDescriptor(IDEDiagnosticIds.RemoveQualificationDiagnosticId,
s_localizableTitleRemoveThisOrMe,
s_localizableMessage,
DiagnosticCategory.Style,
DiagnosticSeverity.Hidden,
isEnabledByDefault: true,
customTags: DiagnosticCustomTags.Unnecessary);
private static readonly DiagnosticDescriptor s_descriptorRemoveThisOrMeInfo = new DiagnosticDescriptor(IDEDiagnosticIds.RemoveQualificationDiagnosticId,
s_localizableTitleRemoveThisOrMe,
s_localizableMessage,
DiagnosticCategory.Style,
DiagnosticSeverity.Info,
isEnabledByDefault: true,
customTags: DiagnosticCustomTags.Unnecessary);
private static readonly DiagnosticDescriptor s_descriptorRemoveThisOrMeWarning = new DiagnosticDescriptor(IDEDiagnosticIds.RemoveQualificationDiagnosticId,
s_localizableTitleRemoveThisOrMe,
s_localizableMessage,
DiagnosticCategory.Style,
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
customTags: DiagnosticCustomTags.Unnecessary);
private static readonly DiagnosticDescriptor s_descriptorRemoveThisOrMeError = new DiagnosticDescriptor(IDEDiagnosticIds.RemoveQualificationDiagnosticId,
s_localizableTitleRemoveThisOrMe,
s_localizableMessage,
DiagnosticCategory.Style,
DiagnosticSeverity.Error,
isEnabledByDefault: true,
customTags: DiagnosticCustomTags.Unnecessary);
private static readonly DiagnosticDescriptor s_descriptorPreferIntrinsicTypeInDeclarations = new DiagnosticDescriptor(IDEDiagnosticIds.PreferIntrinsicPredefinedTypeInDeclarationsDiagnosticId,
s_localizableTitleSimplifyNames,
s_localizableMessage,
DiagnosticCategory.Style,
DiagnosticSeverity.Hidden,
isEnabledByDefault: true,
customTags: DiagnosticCustomTags.Unnecessary);
private static readonly DiagnosticDescriptor s_descriptorPreferIntrinsicTypeInMemberAccess = new DiagnosticDescriptor(IDEDiagnosticIds.PreferIntrinsicPredefinedTypeInMemberAccessDiagnosticId,
s_localizableTitleSimplifyNames,
s_localizableMessage,
DiagnosticCategory.Style,
DiagnosticSeverity.Hidden,
isEnabledByDefault: true,
customTags: DiagnosticCustomTags.Unnecessary);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(
s_descriptorSimplifyNames,
s_descriptorSimplifyMemberAccess,
s_descriptorRemoveThisOrMeHidden,
s_descriptorRemoveThisOrMeInfo,
s_descriptorRemoveThisOrMeWarning,
s_descriptorRemoveThisOrMeError,
s_descriptorPreferIntrinsicTypeInDeclarations,
s_descriptorPreferIntrinsicTypeInMemberAccess);
}
}
public bool RunInProcess => true;
protected abstract void AnalyzeNode(SyntaxNodeAnalysisContext context);
protected abstract bool CanSimplifyTypeNameExpressionCore(SemanticModel model, SyntaxNode node, OptionSet optionSet, out TextSpan issueSpan, out string diagnosticId, CancellationToken cancellationToken);
protected abstract string GetLanguageName();
protected bool TrySimplifyTypeNameExpression(SemanticModel model, SyntaxNode node, AnalyzerOptions analyzerOptions, out Diagnostic diagnostic, CancellationToken cancellationToken)
{
diagnostic = default(Diagnostic);
var optionSet = analyzerOptions.GetOptionSet();
string diagnosticId;
TextSpan issueSpan;
if (!CanSimplifyTypeNameExpressionCore(model, node, optionSet, out issueSpan, out diagnosticId, cancellationToken))
{
return false;
}
if (model.SyntaxTree.OverlapsHiddenPosition(issueSpan, cancellationToken))
{
return false;
}
PerLanguageOption<CodeStyleOption<bool>> option;
DiagnosticDescriptor descriptor;
switch (diagnosticId)
{
case IDEDiagnosticIds.SimplifyNamesDiagnosticId:
descriptor = s_descriptorSimplifyNames;
break;
case IDEDiagnosticIds.SimplifyMemberAccessDiagnosticId:
descriptor = s_descriptorSimplifyMemberAccess;
break;
case IDEDiagnosticIds.RemoveQualificationDiagnosticId:
descriptor = GetRemoveQualificationDiagnosticDescriptor(model, node, optionSet, cancellationToken);
break;
case IDEDiagnosticIds.PreferIntrinsicPredefinedTypeInDeclarationsDiagnosticId:
option = CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration;
descriptor = GetApplicablePredefinedTypeDiagnosticDescriptor(
IDEDiagnosticIds.PreferIntrinsicPredefinedTypeInDeclarationsDiagnosticId, option, optionSet);
break;
case IDEDiagnosticIds.PreferIntrinsicPredefinedTypeInMemberAccessDiagnosticId:
option = CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess;
descriptor = GetApplicablePredefinedTypeDiagnosticDescriptor(
IDEDiagnosticIds.PreferIntrinsicPredefinedTypeInMemberAccessDiagnosticId, option, optionSet);
break;
default:
throw ExceptionUtilities.Unreachable;
}
if (descriptor == null)
{
return false;
}
var tree = model.SyntaxTree;
var builder = ImmutableDictionary.CreateBuilder<string, string>();
builder["OptionName"] = nameof(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess); // TODO: need the actual one
builder["OptionLanguage"] = model.Language;
diagnostic = Diagnostic.Create(descriptor, tree.GetLocation(issueSpan), builder.ToImmutable());
return true;
}
private DiagnosticDescriptor GetApplicablePredefinedTypeDiagnosticDescriptor<T>(string id, PerLanguageOption<T> option, OptionSet optionSet) where T : CodeStyleOption<bool>
{
var optionValue = optionSet.GetOption(option, GetLanguageName());
DiagnosticDescriptor descriptor = null;
if (optionValue.Notification.Value != DiagnosticSeverity.Hidden)
{
descriptor = new DiagnosticDescriptor(id,
s_localizableTitleSimplifyNames,
s_localizableMessage,
DiagnosticCategory.Style,
optionValue.Notification.Value,
isEnabledByDefault: true,
customTags: DiagnosticCustomTags.Unnecessary);
}
return descriptor;
}
private DiagnosticDescriptor GetRemoveQualificationDiagnosticDescriptor(SemanticModel model, SyntaxNode node, OptionSet optionSet, CancellationToken cancellationToken)
{
var symbolInfo = model.GetSymbolInfo(node, cancellationToken);
if (symbolInfo.Symbol == null)
{
return null;
}
var applicableOption = QualifyMemberAccessDiagnosticAnalyzerBase<TLanguageKindEnum>.GetApplicableOptionFromSymbolKind(symbolInfo.Symbol.Kind);
var optionValue = optionSet.GetOption(applicableOption, GetLanguageName());
switch (optionValue.Notification.Value)
{
case DiagnosticSeverity.Hidden:
return s_descriptorRemoveThisOrMeHidden;
case DiagnosticSeverity.Info:
return s_descriptorRemoveThisOrMeInfo;
case DiagnosticSeverity.Warning:
return s_descriptorRemoveThisOrMeWarning;
case DiagnosticSeverity.Error:
return s_descriptorRemoveThisOrMeError;
default:
throw ExceptionUtilities.Unreachable;
}
}
public DiagnosticAnalyzerCategory GetAnalyzerCategory()
{
return DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
}
}
}
| |
using EPiServer.Commerce.Catalog.ContentTypes;
using EPiServer.Core;
using EPiServer.Framework.Cache;
using EPiServer.Reference.Commerce.Site.Features.Global.Shared.Services;
using EPiServer.Reference.Commerce.Site.Tests.TestSupport.Fakes;
using Mediachase.Commerce;
using Mediachase.Commerce.Catalog;
using Mediachase.Commerce.Markets;
using Mediachase.Commerce.Pricing;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using EPiServer.Commerce.Marketing;
using EPiServer.Commerce.Order;
using EPiServer.Commerce.Order.Internal;
using Xunit;
namespace EPiServer.Reference.Commerce.Site.Tests.Features.Shared.Services
{
public class PromotionServiceTests
{
[Fact]
public void GetDiscountPrice_WhenEmptyCurrencyIsProvided_ShouldReturnDiscountedPriceBasedOnMarket()
{
var priceWithDiscount = _subject.GetDiscountPrice(
new CatalogKey(_appContext.ApplicationId, _variation1.Code), _USMarketMock.Object.MarketId, Currency.Empty);
var cheapestPrice = CreatePriceList(_variation1.Code, Currency.USD).OrderBy(x => x.UnitPrice.Amount).First();
var expectedUnitPrice = new Money(cheapestPrice.UnitPrice.Amount - _discountAmount,
cheapestPrice.UnitPrice.Currency);
Assert.Equal<Money>(expectedUnitPrice, priceWithDiscount.UnitPrice);
}
[Fact]
public void GetDiscountPrice_WhenNonEmptyCurrencyIsProvided_ShouldReturnDiscountedPriceBasedOnProvidedCurrency()
{
var priceWithDiscount = _subject.GetDiscountPrice(
new CatalogKey(_appContext.ApplicationId, _variation1.Code), _USMarketMock.Object.MarketId, Currency.USD);
var cheapestPrice = CreatePriceList(_variation1.Code, Currency.USD).OrderBy(x => x.UnitPrice.Amount).First();
var expectedUnitPrice = new Money(cheapestPrice.UnitPrice.Amount - _discountAmount,
cheapestPrice.UnitPrice.Currency);
Assert.Equal<Money>(expectedUnitPrice, priceWithDiscount.UnitPrice);
}
[Fact]
public void GetDiscountPrice_WhenMismatchBetweenCurrencyAndMarketCurrency_ShouldReturnNoPrice()
{
var priceWithDiscount = _subject.GetDiscountPrice(
new CatalogKey(_appContext.ApplicationId, _variation1.Code), _USMarketMock.Object.MarketId, Currency.SEK);
Assert.Null(priceWithDiscount);
}
[Fact]
public void GetDiscountPrice_WhenMarketIsUnknown_ShouldThrow()
{
Assert.Throws<ArgumentException>(() => _subject.GetDiscountPrice(
new CatalogKey(_appContext.ApplicationId, _variation1.Code), new MarketId("UNKNOWN"), Currency.Empty));
}
[Fact]
public void GetDiscountPrice_WhenNoPricesAvailableForMarket_ShouldReturnNull()
{
_pricingServiceMock
.Setup(x => x.GetPriceList(It.IsAny<string>(), It.IsAny<MarketId>(), It.IsAny<PriceFilter>()))
.Returns(() => Enumerable.Empty<IPriceValue>().ToList());
var priceWithDiscount = _subject.GetDiscountPrice(
new CatalogKey(_appContext.ApplicationId, _variation1.Code), _USMarketMock.Object.MarketId, Currency.USD);
Assert.Null(priceWithDiscount);
}
private PromotionService _subject;
private FakeAppContext _appContext;
private Mock<IPricingService> _pricingServiceMock;
private List<VariationContent> _variations;
private Mock<IMarketService> _marketServiceMock;
private Mock<IContentLoader> _contentLoaderMock;
private Mock<ReferenceConverter> _referenceConverterMock;
private decimal _discountAmount;
private Mock<IMarket> _USMarketMock;
private Mock<IMarket> _SEKMarketMock;
private VariationContent _variation1;
private VariationContent _variation2;
private Mock<ILineItemCalculator> _lineItemcalculatorMock;
private Mock<IPromotionEngine> _promotionEngineMock;
public PromotionServiceTests()
{
_appContext = new FakeAppContext();
SetupContent();
SetupPricing();
SetupMarkets();
SetupReferenceConverter();
SetupPromotionEngine();
_lineItemcalculatorMock = new Mock<ILineItemCalculator>();
SetupDiscountedPrice();
_subject = new PromotionService(
_pricingServiceMock.Object,
_marketServiceMock.Object,
_contentLoaderMock.Object,
_referenceConverterMock.Object,
_lineItemcalculatorMock.Object,
_promotionEngineMock.Object
);
}
private void SetupReferenceConverter()
{
var synchronizedObjectInstanceCache = new Mock<ISynchronizedObjectInstanceCache>();
_referenceConverterMock = new Mock<ReferenceConverter>(
new EntryIdentityResolver(synchronizedObjectInstanceCache.Object),
new NodeIdentityResolver(synchronizedObjectInstanceCache.Object))
{
CallBase = true
};
_referenceConverterMock
.Setup(x => x.GetContentLink(It.IsAny<string>(), CatalogContentType.CatalogEntry))
.Returns((string catalogEntryCode, CatalogContentType type) =>
_variations.FirstOrDefault(x => x.Code == catalogEntryCode).ContentLink);
_referenceConverterMock
.Setup(x => x.GetContentLink(It.IsAny<string>()))
.Returns((string catalogEntryCode) =>
_variations.FirstOrDefault(x => x.Code == catalogEntryCode).ContentLink);
_referenceConverterMock
.Setup(x => x.GetCode(It.IsAny<ContentReference>()))
.Returns((ContentReference catalogContentReference) =>
_variations.FirstOrDefault(x => x.ContentLink == catalogContentReference).Code);
}
private void SetupPromotionEngine()
{
_promotionEngineMock = new Mock<IPromotionEngine>();
_discountAmount = 0.3m;
var lineItem = new InMemoryLineItem
{
Code = "code1",
Quantity = 1,
LineItemDiscountAmount = _discountAmount
};
var affectedItems = new[] {lineItem};
var redemptionDescription = new FakeRedemptionDescription(affectedItems.Select(item => new AffectedEntries(new List<PriceEntry> { new PriceEntry(item) })));
var rewardDescription = RewardDescription.CreateMoneyReward(FulfillmentStatus.Fulfilled, new [] {redemptionDescription}, null, 0m, null);
_promotionEngineMock
.Setup(x => x.Evaluate(
It.IsAny<IEnumerable<ContentReference>>(),
It.IsAny<IMarket>(),
It.IsAny<Currency>(),
RequestFulfillmentStatus.Fulfilled
))
.Returns(new RewardDescription[] { rewardDescription });
}
private void SetupDiscountedPrice()
{
var price = CreatePriceList(_variation1.Code, Currency.USD).OrderBy(x => x.UnitPrice.Amount).First();
_lineItemcalculatorMock.Setup(x => x.GetExtendedPrice(It.IsAny<ILineItem>(), It.IsAny<Currency>()))
.Returns((ILineItem item, Currency currency) => new Money(price.UnitPrice.Amount - _discountAmount, currency));
}
private void SetupMarkets()
{
_USMarketMock = new Mock<IMarket>();
_USMarketMock.Setup(x => x.MarketId).Returns(new MarketId("US"));
_USMarketMock.Setup(x => x.DefaultCurrency).Returns(new Currency("USD"));
_SEKMarketMock = new Mock<IMarket>();
_SEKMarketMock.Setup(x => x.MarketId).Returns(new MarketId("SE"));
_SEKMarketMock.Setup(x => x.DefaultCurrency).Returns(new Currency("SEK"));
var markets = new List<IMarket> {_USMarketMock.Object, _SEKMarketMock.Object};
_marketServiceMock = new Mock<IMarketService>();
_marketServiceMock.Setup(x => x.GetMarket(It.IsAny<MarketId>()))
.Returns((MarketId marketId) => markets.SingleOrDefault(x => x.MarketId == marketId));
}
private void SetupContent()
{
_variation1 = new VariationContent
{
Code = "code1",
ContentLink = new ContentReference(1),
Categories = new Categories {ContentLink = new ContentReference(11)}
};
_variation2 = new VariationContent
{
Code = "code2",
ContentLink = new ContentReference(2),
Categories = new Categories { ContentLink = new ContentReference(11) }
};
_variations = new List<VariationContent>
{
_variation1, _variation2
};
_contentLoaderMock = new Mock<IContentLoader>();
_contentLoaderMock.Setup(x => x.Get<EntryContentBase>(It.IsAny<ContentReference>()))
.Returns((ContentReference contentReference) => _variations.SingleOrDefault(x => x.ContentLink == contentReference));
}
private void SetupPricing()
{
_pricingServiceMock = new Mock<IPricingService>();
_pricingServiceMock
.Setup(x => x.GetPriceList(It.IsAny<string>(), It.IsAny<MarketId>(), It.IsAny<PriceFilter>()))
.Returns((string code, MarketId marketId, PriceFilter priceFilter) => CreatePriceList(code, Currency.USD));
}
private IList<IPriceValue> CreatePriceList(string code, Currency currency)
{
var priceList = new List<IPriceValue>()
{
new PriceValue
{
CatalogKey = new CatalogKey(_appContext.ApplicationId, code),
UnitPrice = new Money(2,currency)
},
new PriceValue
{
CatalogKey = new CatalogKey(_appContext.ApplicationId, code),
UnitPrice = new Money(1,currency)
},
};
return priceList;
}
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections;
using log4net.Appender;
using log4net.Core;
using log4net.Util;
namespace log4net.Repository.Hierarchy
{
#region LoggerCreationEvent
/// <summary>
/// Delegate used to handle logger creation event notifications.
/// </summary>
/// <param name="sender">The <see cref="Hierarchy"/> in which the <see cref="Logger"/> has been created.</param>
/// <param name="e">The <see cref="LoggerCreationEventArgs"/> event args that hold the <see cref="Logger"/> instance that has been created.</param>
/// <remarks>
/// <para>
/// Delegate used to handle logger creation event notifications.
/// </para>
/// </remarks>
public delegate void LoggerCreationEventHandler(object sender, LoggerCreationEventArgs e);
/// <summary>
/// Provides data for the <see cref="Hierarchy.LoggerCreatedEvent"/> event.
/// </summary>
/// <remarks>
/// <para>
/// A <see cref="Hierarchy.LoggerCreatedEvent"/> event is raised every time a
/// <see cref="Logger"/> is created.
/// </para>
/// </remarks>
public class LoggerCreationEventArgs : EventArgs
{
/// <summary>
/// The <see cref="Logger"/> created
/// </summary>
private Logger m_log;
/// <summary>
/// Constructor
/// </summary>
/// <param name="log">The <see cref="Logger"/> that has been created.</param>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="LoggerCreationEventArgs" /> event argument
/// class,with the specified <see cref="Logger"/>.
/// </para>
/// </remarks>
public LoggerCreationEventArgs(Logger log)
{
m_log = log;
}
/// <summary>
/// Gets the <see cref="Logger"/> that has been created.
/// </summary>
/// <value>
/// The <see cref="Logger"/> that has been created.
/// </value>
/// <remarks>
/// <para>
/// The <see cref="Logger"/> that has been created.
/// </para>
/// </remarks>
public Logger Logger
{
get { return m_log; }
}
}
#endregion LoggerCreationEvent
/// <summary>
/// Hierarchical organization of loggers
/// </summary>
/// <remarks>
/// <para>
/// <i>The casual user should not have to deal with this class
/// directly.</i>
/// </para>
/// <para>
/// This class is specialized in retrieving loggers by name and
/// also maintaining the logger hierarchy. Implements the
/// <see cref="ILoggerRepository"/> interface.
/// </para>
/// <para>
/// The structure of the logger hierarchy is maintained by the
/// <see cref="M:GetLogger(string)"/> method. The hierarchy is such that children
/// link to their parent but parents do not have any references to their
/// children. Moreover, loggers can be instantiated in any order, in
/// particular descendant before ancestor.
/// </para>
/// <para>
/// In case a descendant is created before a particular ancestor,
/// then it creates a provision node for the ancestor and adds itself
/// to the provision node. Other descendants of the same ancestor add
/// themselves to the previously created provision node.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public class Hierarchy : LoggerRepositorySkeleton, IBasicRepositoryConfigurator, IXmlRepositoryConfigurator
{
#region Public Events
/// <summary>
/// Event used to notify that a logger has been created.
/// </summary>
/// <remarks>
/// <para>
/// Event raised when a logger is created.
/// </para>
/// </remarks>
public event LoggerCreationEventHandler LoggerCreatedEvent
{
add { m_loggerCreatedEvent += value; }
remove { m_loggerCreatedEvent -= value; }
}
#endregion Public Events
#region Public Instance Constructors
/// <summary>
/// Default constructor
/// </summary>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="Hierarchy" /> class.
/// </para>
/// </remarks>
public Hierarchy() : this(new DefaultLoggerFactory())
{
}
/// <summary>
/// Construct with properties
/// </summary>
/// <param name="properties">The properties to pass to this repository.</param>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="Hierarchy" /> class.
/// </para>
/// </remarks>
public Hierarchy(PropertiesDictionary properties) : this(properties, new DefaultLoggerFactory())
{
}
/// <summary>
/// Construct with a logger factory
/// </summary>
/// <param name="loggerFactory">The factory to use to create new logger instances.</param>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="Hierarchy" /> class with
/// the specified <see cref="ILoggerFactory" />.
/// </para>
/// </remarks>
public Hierarchy(ILoggerFactory loggerFactory) : this(new PropertiesDictionary(), loggerFactory)
{
}
/// <summary>
/// Construct with properties and a logger factory
/// </summary>
/// <param name="properties">The properties to pass to this repository.</param>
/// <param name="loggerFactory">The factory to use to create new logger instances.</param>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="Hierarchy" /> class with
/// the specified <see cref="ILoggerFactory" />.
/// </para>
/// </remarks>
public Hierarchy(PropertiesDictionary properties, ILoggerFactory loggerFactory) : base(properties)
{
if (loggerFactory == null)
{
throw new ArgumentNullException("loggerFactory");
}
m_defaultFactory = loggerFactory;
m_ht = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable());
}
#endregion Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Has no appender warning been emitted
/// </summary>
/// <remarks>
/// <para>
/// Flag to indicate if we have already issued a warning
/// about not having an appender warning.
/// </para>
/// </remarks>
public bool EmittedNoAppenderWarning
{
get { return m_emittedNoAppenderWarning; }
set { m_emittedNoAppenderWarning = value; }
}
/// <summary>
/// Get the root of this hierarchy
/// </summary>
/// <remarks>
/// <para>
/// Get the root of this hierarchy.
/// </para>
/// </remarks>
public Logger Root
{
get
{
if (m_root == null)
{
lock (this)
{
if (m_root == null)
{
// Create the root logger
Logger root = m_defaultFactory.CreateLogger(this, null);
root.Hierarchy = this;
// Store root
m_root = root;
}
}
}
return m_root;
}
}
/// <summary>
/// Gets or sets the default <see cref="ILoggerFactory" /> instance.
/// </summary>
/// <value>The default <see cref="ILoggerFactory" /></value>
/// <remarks>
/// <para>
/// The logger factory is used to create logger instances.
/// </para>
/// </remarks>
public ILoggerFactory LoggerFactory
{
get { return m_defaultFactory; }
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
m_defaultFactory = value;
}
}
#endregion Public Instance Properties
#region Override Implementation of LoggerRepositorySkeleton
/// <summary>
/// Test if a logger exists
/// </summary>
/// <param name="name">The name of the logger to lookup</param>
/// <returns>The Logger object with the name specified</returns>
/// <remarks>
/// <para>
/// Check if the named logger exists in the hierarchy. If so return
/// its reference, otherwise returns <c>null</c>.
/// </para>
/// </remarks>
override public ILogger Exists(string name)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
lock (m_ht)
{
return m_ht[new LoggerKey(name)] as Logger;
}
}
/// <summary>
/// Returns all the currently defined loggers in the hierarchy as an Array
/// </summary>
/// <returns>All the defined loggers</returns>
/// <remarks>
/// <para>
/// Returns all the currently defined loggers in the hierarchy as an Array.
/// The root logger is <b>not</b> included in the returned
/// enumeration.
/// </para>
/// </remarks>
override public ILogger[] GetCurrentLoggers()
{
// The accumulation in loggers is necessary because not all elements in
// ht are Logger objects as there might be some ProvisionNodes
// as well.
lock (m_ht)
{
System.Collections.ArrayList loggers = new System.Collections.ArrayList(m_ht.Count);
// Iterate through m_ht values
foreach (object node in m_ht.Values)
{
if (node is Logger)
{
loggers.Add(node);
}
}
return (Logger[])loggers.ToArray(typeof(Logger));
}
}
/// <summary>
/// Return a new logger instance named as the first parameter using
/// the default factory.
/// </summary>
/// <remarks>
/// <para>
/// Return a new logger instance named as the first parameter using
/// the default factory.
/// </para>
/// <para>
/// If a logger of that name already exists, then it will be
/// returned. Otherwise, a new logger will be instantiated and
/// then linked with its existing ancestors as well as children.
/// </para>
/// </remarks>
/// <param name="name">The name of the logger to retrieve</param>
/// <returns>The logger object with the name specified</returns>
override public ILogger GetLogger(string name)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
return GetLogger(name, m_defaultFactory);
}
/// <summary>
/// Shutting down a hierarchy will <i>safely</i> close and remove
/// all appenders in all loggers including the root logger.
/// </summary>
/// <remarks>
/// <para>
/// Shutting down a hierarchy will <i>safely</i> close and remove
/// all appenders in all loggers including the root logger.
/// </para>
/// <para>
/// Some appenders need to be closed before the
/// application exists. Otherwise, pending logging events might be
/// lost.
/// </para>
/// <para>
/// The <c>Shutdown</c> method is careful to close nested
/// appenders before closing regular appenders. This is allows
/// configurations where a regular appender is attached to a logger
/// and again to a nested appender.
/// </para>
/// </remarks>
override public void Shutdown()
{
LogLog.Debug(declaringType, "Shutdown called on Hierarchy [" + this.Name + "]");
// begin by closing nested appenders
Root.CloseNestedAppenders();
lock (m_ht)
{
ILogger[] currentLoggers = this.GetCurrentLoggers();
foreach (Logger logger in currentLoggers)
{
logger.CloseNestedAppenders();
}
// then, remove all appenders
Root.RemoveAllAppenders();
foreach (Logger logger in currentLoggers)
{
logger.RemoveAllAppenders();
}
}
base.Shutdown();
}
/// <summary>
/// Reset all values contained in this hierarchy instance to their default.
/// </summary>
/// <remarks>
/// <para>
/// Reset all values contained in this hierarchy instance to their
/// default. This removes all appenders from all loggers, sets
/// the level of all non-root loggers to <c>null</c>,
/// sets their additivity flag to <c>true</c> and sets the level
/// of the root logger to <see cref="Level.Debug"/>. Moreover,
/// message disabling is set its default "off" value.
/// </para>
/// <para>
/// Existing loggers are not removed. They are just reset.
/// </para>
/// <para>
/// This method should be used sparingly and with care as it will
/// block all logging until it is completed.
/// </para>
/// </remarks>
override public void ResetConfiguration()
{
Root.Level = LevelMap.LookupWithDefault(Level.Debug);
Threshold = LevelMap.LookupWithDefault(Level.All);
// the synchronization is needed to prevent hashtable surprises
lock (m_ht)
{
Shutdown(); // nested locks are OK
foreach (Logger l in this.GetCurrentLoggers())
{
l.Level = null;
l.Additivity = true;
}
}
base.ResetConfiguration();
// Notify listeners
OnConfigurationChanged(null);
}
/// <summary>
/// Log the logEvent through this hierarchy.
/// </summary>
/// <param name="logEvent">the event to log</param>
/// <remarks>
/// <para>
/// This method should not normally be used to log.
/// The <see cref="ILog"/> interface should be used
/// for routine logging. This interface can be obtained
/// using the <see cref="M:log4net.LogManager.GetLogger(string)"/> method.
/// </para>
/// <para>
/// The <c>logEvent</c> is delivered to the appropriate logger and
/// that logger is then responsible for logging the event.
/// </para>
/// </remarks>
override public void Log(LoggingEvent logEvent)
{
if (logEvent == null)
{
throw new ArgumentNullException("logEvent");
}
this.GetLogger(logEvent.LoggerName, m_defaultFactory).Log(logEvent);
}
/// <summary>
/// Returns all the Appenders that are currently configured
/// </summary>
/// <returns>An array containing all the currently configured appenders</returns>
/// <remarks>
/// <para>
/// Returns all the <see cref="log4net.Appender.IAppender"/> instances that are currently configured.
/// All the loggers are searched for appenders. The appenders may also be containers
/// for appenders and these are also searched for additional loggers.
/// </para>
/// <para>
/// The list returned is unordered but does not contain duplicates.
/// </para>
/// </remarks>
override public Appender.IAppender[] GetAppenders()
{
System.Collections.ArrayList appenderList = new System.Collections.ArrayList();
CollectAppenders(appenderList, Root);
foreach (Logger logger in GetCurrentLoggers())
{
CollectAppenders(appenderList, logger);
}
return (Appender.IAppender[])appenderList.ToArray(typeof(Appender.IAppender));
}
#endregion Override Implementation of LoggerRepositorySkeleton
#region Private Static Methods
/// <summary>
/// Collect the appenders from an <see cref="IAppenderAttachable"/>.
/// The appender may also be a container.
/// </summary>
/// <param name="appenderList"></param>
/// <param name="appender"></param>
private static void CollectAppender(System.Collections.ArrayList appenderList, Appender.IAppender appender)
{
if (!appenderList.Contains(appender))
{
appenderList.Add(appender);
IAppenderAttachable container = appender as IAppenderAttachable;
if (container != null)
{
CollectAppenders(appenderList, container);
}
}
}
/// <summary>
/// Collect the appenders from an <see cref="IAppenderAttachable"/> container
/// </summary>
/// <param name="appenderList"></param>
/// <param name="container"></param>
private static void CollectAppenders(System.Collections.ArrayList appenderList, IAppenderAttachable container)
{
foreach (Appender.IAppender appender in container.Appenders)
{
CollectAppender(appenderList, appender);
}
}
#endregion
#region Implementation of IBasicRepositoryConfigurator
/// <summary>
/// Initialize the log4net system using the specified appender
/// </summary>
/// <param name="appender">the appender to use to log all logging events</param>
void IBasicRepositoryConfigurator.Configure(IAppender appender)
{
BasicRepositoryConfigure(appender);
}
/// <summary>
/// Initialize the log4net system using the specified appenders
/// </summary>
/// <param name="appenders">the appenders to use to log all logging events</param>
void IBasicRepositoryConfigurator.Configure(params IAppender[] appenders)
{
BasicRepositoryConfigure(appenders);
}
/// <summary>
/// Initialize the log4net system using the specified appenders
/// </summary>
/// <param name="appenders">the appenders to use to log all logging events</param>
/// <remarks>
/// <para>
/// This method provides the same functionality as the
/// <see cref="M:IBasicRepositoryConfigurator.Configure(IAppender)"/> method implemented
/// on this object, but it is protected and therefore can be called by subclasses.
/// </para>
/// </remarks>
protected void BasicRepositoryConfigure(params IAppender[] appenders)
{
ArrayList configurationMessages = new ArrayList();
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
foreach (IAppender appender in appenders)
{
Root.AddAppender(appender);
}
}
Configured = true;
ConfigurationMessages = configurationMessages;
// Notify listeners
OnConfigurationChanged(new ConfigurationChangedEventArgs(configurationMessages));
}
#endregion Implementation of IBasicRepositoryConfigurator
#region Implementation of IXmlRepositoryConfigurator
/// <summary>
/// Initialize the log4net system using the specified config
/// </summary>
/// <param name="element">the element containing the root of the config</param>
void IXmlRepositoryConfigurator.Configure(System.Xml.XmlElement element)
{
XmlRepositoryConfigure(element);
}
/// <summary>
/// Initialize the log4net system using the specified config
/// </summary>
/// <param name="element">the element containing the root of the config</param>
/// <remarks>
/// <para>
/// This method provides the same functionality as the
/// <see cref="M:IBasicRepositoryConfigurator.Configure(IAppender)"/> method implemented
/// on this object, but it is protected and therefore can be called by subclasses.
/// </para>
/// </remarks>
protected void XmlRepositoryConfigure(System.Xml.XmlElement element)
{
ArrayList configurationMessages = new ArrayList();
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
XmlHierarchyConfigurator config = new XmlHierarchyConfigurator(this);
config.Configure(element);
}
Configured = true;
ConfigurationMessages = configurationMessages;
// Notify listeners
OnConfigurationChanged(new ConfigurationChangedEventArgs(configurationMessages));
}
#endregion Implementation of IXmlRepositoryConfigurator
#region Public Instance Methods
/// <summary>
/// Test if this hierarchy is disabled for the specified <see cref="Level"/>.
/// </summary>
/// <param name="level">The level to check against.</param>
/// <returns>
/// <c>true</c> if the repository is disabled for the level argument, <c>false</c> otherwise.
/// </returns>
/// <remarks>
/// <para>
/// If this hierarchy has not been configured then this method will
/// always return <c>true</c>.
/// </para>
/// <para>
/// This method will return <c>true</c> if this repository is
/// disabled for <c>level</c> object passed as parameter and
/// <c>false</c> otherwise.
/// </para>
/// <para>
/// See also the <see cref="ILoggerRepository.Threshold"/> property.
/// </para>
/// </remarks>
public bool IsDisabled(Level level)
{
// Cast level to object for performance
if ((object)level == null)
{
throw new ArgumentNullException("level");
}
if (Configured)
{
return Threshold > level;
}
else
{
// If not configured the hierarchy is effectively disabled
return true;
}
}
/// <summary>
/// Clear all logger definitions from the internal hashtable
/// </summary>
/// <remarks>
/// <para>
/// This call will clear all logger definitions from the internal
/// hashtable. Invoking this method will irrevocably mess up the
/// logger hierarchy.
/// </para>
/// <para>
/// You should <b>really</b> know what you are doing before
/// invoking this method.
/// </para>
/// </remarks>
public void Clear()
{
lock (m_ht)
{
m_ht.Clear();
}
}
/// <summary>
/// Return a new logger instance named as the first parameter using
/// <paramref name="factory"/>.
/// </summary>
/// <param name="name">The name of the logger to retrieve</param>
/// <param name="factory">The factory that will make the new logger instance</param>
/// <returns>The logger object with the name specified</returns>
/// <remarks>
/// <para>
/// If a logger of that name already exists, then it will be
/// returned. Otherwise, a new logger will be instantiated by the
/// <paramref name="factory"/> parameter and linked with its existing
/// ancestors as well as children.
/// </para>
/// </remarks>
public Logger GetLogger(string name, ILoggerFactory factory)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
if (factory == null)
{
throw new ArgumentNullException("factory");
}
LoggerKey key = new LoggerKey(name);
// Synchronize to prevent write conflicts. Read conflicts (in
// GetEffectiveLevel() method) are possible only if variable
// assignments are non-atomic.
lock (m_ht)
{
Logger logger = null;
Object node = m_ht[key];
if (node == null)
{
logger = factory.CreateLogger(this, name);
logger.Hierarchy = this;
m_ht[key] = logger;
UpdateParents(logger);
OnLoggerCreationEvent(logger);
return logger;
}
Logger nodeLogger = node as Logger;
if (nodeLogger != null)
{
return nodeLogger;
}
ProvisionNode nodeProvisionNode = node as ProvisionNode;
if (nodeProvisionNode != null)
{
logger = factory.CreateLogger(this, name);
logger.Hierarchy = this;
m_ht[key] = logger;
UpdateChildren(nodeProvisionNode, logger);
UpdateParents(logger);
OnLoggerCreationEvent(logger);
return logger;
}
// It should be impossible to arrive here but let's keep the compiler happy.
return null;
}
}
#endregion Public Instance Methods
#region Protected Instance Methods
/// <summary>
/// Sends a logger creation event to all registered listeners
/// </summary>
/// <param name="logger">The newly created logger</param>
/// <remarks>
/// Raises the logger creation event.
/// </remarks>
protected virtual void OnLoggerCreationEvent(Logger logger)
{
LoggerCreationEventHandler handler = m_loggerCreatedEvent;
if (handler != null)
{
handler(this, new LoggerCreationEventArgs(logger));
}
}
#endregion Protected Instance Methods
#region Private Instance Methods
/// <summary>
/// Updates all the parents of the specified logger
/// </summary>
/// <param name="log">The logger to update the parents for</param>
/// <remarks>
/// <para>
/// This method loops through all the <i>potential</i> parents of
/// <paramref name="log"/>. There 3 possible cases:
/// </para>
/// <list type="number">
/// <item>
/// <term>No entry for the potential parent of <paramref name="log"/> exists</term>
/// <description>
/// We create a ProvisionNode for this potential
/// parent and insert <paramref name="log"/> in that provision node.
/// </description>
/// </item>
/// <item>
/// <term>The entry is of type Logger for the potential parent.</term>
/// <description>
/// The entry is <paramref name="log"/>'s nearest existing parent. We
/// update <paramref name="log"/>'s parent field with this entry. We also break from
/// he loop because updating our parent's parent is our parent's
/// responsibility.
/// </description>
/// </item>
/// <item>
/// <term>The entry is of type ProvisionNode for this potential parent.</term>
/// <description>
/// We add <paramref name="log"/> to the list of children for this
/// potential parent.
/// </description>
/// </item>
/// </list>
/// </remarks>
private void UpdateParents(Logger log)
{
string name = log.Name;
int length = name.Length;
bool parentFound = false;
// if name = "w.x.y.z", loop through "w.x.y", "w.x" and "w", but not "w.x.y.z"
for (int i = name.LastIndexOf('.', length - 1); i >= 0; i = name.LastIndexOf('.', i - 1))
{
string substr = name.Substring(0, i);
LoggerKey key = new LoggerKey(substr); // simple constructor
Object node = m_ht[key];
// Create a provision node for a future parent.
if (node == null)
{
ProvisionNode pn = new ProvisionNode(log);
m_ht[key] = pn;
}
else
{
Logger nodeLogger = node as Logger;
if (nodeLogger != null)
{
parentFound = true;
log.Parent = nodeLogger;
break; // no need to update the ancestors of the closest ancestor
}
else
{
ProvisionNode nodeProvisionNode = node as ProvisionNode;
if (nodeProvisionNode != null)
{
nodeProvisionNode.Add(log);
}
else
{
LogLog.Error(declaringType, "Unexpected object type [" + node.GetType() + "] in ht.", new LogException());
}
}
}
if (i == 0)
{
// logger name starts with a dot
// and we've hit the start
break;
}
}
// If we could not find any existing parents, then link with root.
if (!parentFound)
{
log.Parent = this.Root;
}
}
/// <summary>
/// Replace a <see cref="ProvisionNode"/> with a <see cref="Logger"/> in the hierarchy.
/// </summary>
/// <param name="pn"></param>
/// <param name="log"></param>
/// <remarks>
/// <para>
/// We update the links for all the children that placed themselves
/// in the provision node 'pn'. The second argument 'log' is a
/// reference for the newly created Logger, parent of all the
/// children in 'pn'.
/// </para>
/// <para>
/// We loop on all the children 'c' in 'pn'.
/// </para>
/// <para>
/// If the child 'c' has been already linked to a child of
/// 'log' then there is no need to update 'c'.
/// </para>
/// <para>
/// Otherwise, we set log's parent field to c's parent and set
/// c's parent field to log.
/// </para>
/// </remarks>
private static void UpdateChildren(ProvisionNode pn, Logger log)
{
for (int i = 0; i < pn.Count; i++)
{
Logger childLogger = (Logger)pn[i];
// Unless this child already points to a correct (lower) parent,
// make log.Parent point to childLogger.Parent and childLogger.Parent to log.
if (!childLogger.Parent.Name.StartsWith(log.Name))
{
log.Parent = childLogger.Parent;
childLogger.Parent = log;
}
}
}
/// <summary>
/// Define or redefine a Level using the values in the <see cref="LevelEntry"/> argument
/// </summary>
/// <param name="levelEntry">the level values</param>
/// <remarks>
/// <para>
/// Define or redefine a Level using the values in the <see cref="LevelEntry"/> argument
/// </para>
/// <para>
/// Supports setting levels via the configuration file.
/// </para>
/// </remarks>
internal void AddLevel(LevelEntry levelEntry)
{
if (levelEntry == null) throw new ArgumentNullException("levelEntry");
if (levelEntry.Name == null) throw new ArgumentNullException("levelEntry.Name");
// Lookup replacement value
if (levelEntry.Value == -1)
{
Level previousLevel = LevelMap[levelEntry.Name];
if (previousLevel == null)
{
throw new InvalidOperationException("Cannot redefine level [" + levelEntry.Name + "] because it is not defined in the LevelMap. To define the level supply the level value.");
}
levelEntry.Value = previousLevel.Value;
}
LevelMap.Add(levelEntry.Name, levelEntry.Value, levelEntry.DisplayName);
}
/// <summary>
/// A class to hold the value, name and display name for a level
/// </summary>
/// <remarks>
/// <para>
/// A class to hold the value, name and display name for a level
/// </para>
/// </remarks>
internal class LevelEntry
{
private int m_levelValue = -1;
private string m_levelName = null;
private string m_levelDisplayName = null;
/// <summary>
/// Value of the level
/// </summary>
/// <remarks>
/// <para>
/// If the value is not set (defaults to -1) the value will be looked
/// up for the current level with the same name.
/// </para>
/// </remarks>
public int Value
{
get { return m_levelValue; }
set { m_levelValue = value; }
}
/// <summary>
/// Name of the level
/// </summary>
/// <value>
/// The name of the level
/// </value>
/// <remarks>
/// <para>
/// The name of the level.
/// </para>
/// </remarks>
public string Name
{
get { return m_levelName; }
set { m_levelName = value; }
}
/// <summary>
/// Display name for the level
/// </summary>
/// <value>
/// The display name of the level
/// </value>
/// <remarks>
/// <para>
/// The display name of the level.
/// </para>
/// </remarks>
public string DisplayName
{
get { return m_levelDisplayName; }
set { m_levelDisplayName = value; }
}
/// <summary>
/// Override <c>Object.ToString</c> to return sensible debug info
/// </summary>
/// <returns>string info about this object</returns>
public override string ToString()
{
return "LevelEntry(Value=" + m_levelValue + ", Name=" + m_levelName + ", DisplayName=" + m_levelDisplayName + ")";
}
}
/// <summary>
/// Set a Property using the values in the <see cref="LevelEntry"/> argument
/// </summary>
/// <param name="propertyEntry">the property value</param>
/// <remarks>
/// <para>
/// Set a Property using the values in the <see cref="LevelEntry"/> argument.
/// </para>
/// <para>
/// Supports setting property values via the configuration file.
/// </para>
/// </remarks>
internal void AddProperty(PropertyEntry propertyEntry)
{
if (propertyEntry == null) throw new ArgumentNullException("propertyEntry");
if (propertyEntry.Key == null) throw new ArgumentNullException("propertyEntry.Key");
Properties[propertyEntry.Key] = propertyEntry.Value;
}
#endregion Private Instance Methods
#region Private Instance Fields
private ILoggerFactory m_defaultFactory;
private System.Collections.Hashtable m_ht;
private Logger m_root;
private bool m_emittedNoAppenderWarning = false;
private event LoggerCreationEventHandler m_loggerCreatedEvent;
#endregion Private Instance Fields
#region Private Static Fields
/// <summary>
/// The fully qualified type of the Hierarchy class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private readonly static Type declaringType = typeof(Hierarchy);
#endregion Private Static Fields
}
}
| |
using System;
using System.Collections.Generic;
using droid.Runtime.Enums.BoundingBox;
using droid.Runtime.Environments.Prototyping;
using droid.Runtime.GameObjects.BoundingBoxes.Experimental;
using droid.Runtime.Interfaces;
using droid.Runtime.Utilities;
using UnityEditor;
using UnityEngine;
#if UNITY_EDITOR
#endif
namespace droid.Runtime.GameObjects.BoundingBoxes {
/// <inheritdoc />
/// <summary>
/// </summary>
[ExecuteInEditMode]
public class BoundingBox : MonoBehaviour {
/// <summary>
/// </summary>
Transform _bb_transform = null;
/// <summary>
/// </summary>
protected Bounds _Bounds = new Bounds();
/// <summary>
/// </summary>
protected Vector3 _Bounds_Offset;
/// <summary>
/// </summary>
Collider[] _children_colliders = null;
/// <summary>
/// </summary>
MeshFilter[] _children_meshes = null;
GameObject _empty_go = null;
/// <summary>
/// </summary>
Vector3[,] _lines = null;
List<Vector3[]> _lines_list = new List<Vector3[]>();
Collider _local_collider;
MeshFilter _local_mesh;
Vector3 _point_bbl;
Vector3 _point_bbr;
Vector3 _point_bfl;
Vector3 _point_bfr;
Vector3 _point_tbl;
Vector3 _point_tbr;
Vector3 _point_tfl;
Vector3 _point_tfr;
/// <summary>
/// </summary>
Vector3[] _points = null;
#region fields
/// <summary>
/// </summary>
[SerializeField]
public bool _use_bb_transform = false;
[SerializeField] bool _use_shared_mesh = false;
/// <summary>
/// </summary>
[SearchableEnum]
public BasedOn basedOn = BasedOn.Geometry_;
/// <summary>
/// </summary>
[SerializeField]
float bb_margin = 0;
/// <summary>
/// </summary>
[SerializeField]
BoundingBoxOrientation BbAligning = BoundingBoxOrientation.Axis_aligned_;
/// <summary>
/// </summary>
[SerializeField]
bool cacheChildren = true;
/// <summary>
/// </summary>
[SerializeField]
Color editorPreviewLineColor = new Color(1f,
0.36f,
0.38f,
0.74f);
/// <summary>
/// </summary>
[SerializeField]
ISpatialPrototypingEnvironment environment = null;
/// <summary>
/// </summary>
[SerializeField]
bool freezeAfterFirstCalculation = true;
/// <summary>
/// </summary>
[SerializeField]
bool includeChildren = false;
/// <summary>
/// </summary>
[SerializeField]
bool _only_active_children = true;
/// <summary>
/// </summary>
[SerializeField]
bool includeSelf = true;
/// <summary>
/// </summary>
[SerializeField]
bool OnAwakeSetup = true;
/// <summary>
/// </summary>
[SerializeField]
bool RunInEditModeSetup = false;
#endregion
#region Properties
/// <summary>
/// </summary>
public Vector3[] BoundingBoxCoordinates {
get {
return new[] {
this._point_tfl,
this._point_tfr,
this._point_tbl,
this._point_tbr,
this._point_bfl,
this._point_bfr,
this._point_bbl,
this._point_bbr
};
}
}
/// <summary>
/// </summary>
public Bounds Bounds { get { return this._Bounds; } }
public Vector3 Max { get { return this._Bounds.max; } }
public Vector3 Min { get { return this._Bounds.min; } }
/// <summary>
/// </summary>
public string BoundingBoxCoordinatesAsString {
get {
var str_rep = "";
str_rep += $"\"_top_front_left\":{this.BoundingBoxCoordinates[0]}, ";
str_rep += $"\"_top_front_right\":{this.BoundingBoxCoordinates[1]}, ";
str_rep += $"\"_top_back_left\":{this.BoundingBoxCoordinates[2]}, ";
str_rep += $"\"_top_back_right\":{this.BoundingBoxCoordinates[3]}, ";
str_rep += $"\"_bottom_front_left\":{this.BoundingBoxCoordinates[4]}, ";
str_rep += $"\"_bottom_front_right\":{this.BoundingBoxCoordinates[5]}, ";
str_rep += $"\"_bottom_back_left\":{this.BoundingBoxCoordinates[6]}, ";
str_rep += $"\"_bottom_back_right\":{this.BoundingBoxCoordinates[7]}";
return str_rep;
}
}
/// <summary>
/// </summary>
public string BoundingBoxCoordinatesWorldSpaceAsJson {
get {
var str_rep = "{";
var transform1 = this.transform;
if (this._use_bb_transform) {
transform1 = this._bb_transform;
}
var rotation = transform1.rotation;
var position = transform1.position;
if (this.environment != null) {
str_rep +=
$"\"top_front_left\":{JsonifyVec3(this.environment.TransformPoint(rotation * this._point_tfl + position))}, ";
str_rep +=
$"\"bottom_back_right\":{JsonifyVec3(this.environment.TransformPoint(rotation * this._point_bbr + position))}";
}
str_rep += "}";
return str_rep;
}
}
/// <summary>
/// </summary>
public Vector3[,] Lines { get { return this._lines; } }
/// <summary>
/// </summary>
public Vector3[] Points { get { return this._points; } }
/// <summary>
///
/// </summary>
public Color EditorPreviewLineColor {
get { return this.editorPreviewLineColor; }
set { this.editorPreviewLineColor = value; }
}
#endregion
/// <summary>
/// </summary>
/// <param name="a_camera"></param>
/// <param name="margin"></param>
/// <returns></returns>
public Rect ScreenSpaceBoundingRect(Camera a_camera, float margin = 0f) {
if (this.basedOn == BasedOn.Collider_) {
var a = this._local_collider as MeshCollider;
if (a) {
return a.sharedMesh.GetCameraMinMaxRect(this.transform, a_camera, this.bb_margin - margin);
}
}
if (this._local_mesh) {
if (this._use_shared_mesh || !Application.isPlaying) {
var a = this._local_mesh.sharedMesh.GetCameraMinMaxPoints(this.transform, a_camera);
if (this.includeChildren) {
foreach (var children_mesh in this._children_meshes) {
a = children_mesh.sharedMesh.GetCameraMinMaxPoints(children_mesh.transform,
a_camera,
a[0],
a[1]);
}
return BoundingBoxUtilities.GetMinMaxRect(a[0], a[1], this.bb_margin - margin);
}
} else {
var a = this._local_mesh.mesh.GetCameraMinMaxPoints(this.transform, a_camera);
if (this.includeChildren) {
foreach (var children_mesh in this._children_meshes) {
a = children_mesh.mesh.GetCameraMinMaxPoints(children_mesh.transform,
a_camera,
a[0],
a[1]);
}
return BoundingBoxUtilities.GetMinMaxRect(a[0], a[1], this.bb_margin - margin);
}
}
} else {
if (this._use_shared_mesh || !Application.isPlaying) {
if (this._children_meshes != null && this._children_meshes.Length > 0) {
var a = this._children_meshes[0].sharedMesh
.GetCameraMinMaxPoints(this._children_meshes[0].transform, a_camera);
if (this.includeChildren) {
for (var index = 1; index < this._children_meshes.Length; index++) {
var children_mesh = this._children_meshes[index];
a = children_mesh.sharedMesh.GetCameraMinMaxPoints(children_mesh.transform,
a_camera,
a[0],
a[1]);
}
return BoundingBoxUtilities.GetMinMaxRect(a[0], a[1], this.bb_margin - margin);
}
}
} else {
if (this._children_meshes != null && this._children_meshes.Length > 0) {
var a = this._children_meshes[0].mesh
.GetCameraMinMaxPoints(this._children_meshes[0].transform, a_camera);
if (this.includeChildren) {
for (var index = 1; index < this._children_meshes.Length; index++) {
var children_mesh = this._children_meshes[index];
a = children_mesh.mesh.GetCameraMinMaxPoints(children_mesh.transform,
a_camera,
a[0],
a[1]);
}
return BoundingBoxUtilities.GetMinMaxRect(a[0], a[1], this.bb_margin - margin);
}
}
}
}
return new Rect();
}
/// <summary>
/// </summary>
/// <param name="vec"></param>
/// <returns></returns>
static string JsonifyVec3(Vector3 vec) { return $"[{vec.x},{vec.y},{vec.z}]"; }
/// <summary>
/// </summary>
void BoundingBoxReset() {
this.Awake();
this.Start();
}
/// <summary>
/// </summary>
void Start() {
if (!this.OnAwakeSetup) {
this.Setup();
}
}
/// <summary>
/// </summary>
void Awake() {
if (!this.enabled) {
return;
}
if (this.environment == null) {
this.environment = FindObjectOfType<AbstractSpatialPrototypingEnvironment>();
}
if (!this._bb_transform) {
this._empty_go = new GameObject {hideFlags = HideFlags.HideAndDontSave};
this._bb_transform = this._empty_go.transform;
}
if (this.OnAwakeSetup) {
this.Setup();
}
}
/// <summary>
/// </summary>
void Setup() {
if (!this.RunInEditModeSetup && !Application.isPlaying) {
return;
}
if (!this._bb_transform) {
this._empty_go = new GameObject {hideFlags = HideFlags.HideAndDontSave};
this._bb_transform = this._empty_go.transform;
}
if (this.includeSelf) {
this._local_collider = this.GetComponent<BoxCollider>();
this._local_mesh = this.GetComponent<MeshFilter>();
}
if (this.includeChildren) {
this._children_meshes = this.GetComponentsInChildren<MeshFilter>();
this._children_colliders = this.GetComponentsInChildren<Collider>();
}
this.CalculateBoundingBox();
}
/// <summary>
/// </summary>
void LateUpdate() {
if (this.freezeAfterFirstCalculation) {
return;
}
if (this.includeChildren && !this.cacheChildren) {
if (this._children_meshes != this.GetComponentsInChildren<MeshFilter>()) {
this.BoundingBoxReset();
}
if (this._children_colliders != this.GetComponentsInChildren<Collider>()) {
this.BoundingBoxReset();
}
} else {
this.CalculateBoundingBox();
}
}
/// <summary>
/// </summary>
void FitCollidersAabb() {
var transform1 = this.transform;
this._bb_transform.rotation = transform1.rotation;
this._bb_transform.position = transform1.position;
var bounds = new Bounds(this._bb_transform.position, Vector3.zero);
if (this.includeSelf && this._local_collider) {
this._bb_transform.position = this._local_collider.bounds.center;
bounds = this._local_collider.bounds;
}
if (this.includeChildren && this._children_colliders != null) {
foreach (var a_collider in this._children_colliders) {
if (a_collider && a_collider != this._local_collider) {
if (this._only_active_children) {
if (a_collider.gameObject.activeInHierarchy
&& a_collider.gameObject.activeSelf
&& a_collider.enabled) {
if (bounds.size == Vector3.zero) {
this._bb_transform.rotation = a_collider.transform.rotation;
this._bb_transform.position = a_collider.bounds.center;
bounds = a_collider.bounds;
} else {
bounds.Encapsulate(a_collider.bounds);
}
}
} else {
if (bounds.size == Vector3.zero) {
this._bb_transform.rotation = a_collider.transform.rotation;
this._bb_transform.position = a_collider.bounds.center;
bounds = a_collider.bounds;
} else {
bounds.Encapsulate(a_collider.bounds);
}
}
}
}
}
this._Bounds = bounds;
this._Bounds_Offset = this._Bounds.center - this._bb_transform.position;
}
/// <summary>
/// </summary>
void FitRenderersAabb() {
var transform1 = this.transform;
var position = transform1.position;
this._bb_transform.position = position;
this._bb_transform.rotation = transform1.rotation;
var bounds = new Bounds(position, Vector3.zero);
if (this.includeSelf && this._local_mesh) {
Mesh a_mesh;
if (this._use_shared_mesh) {
a_mesh = this._local_mesh.sharedMesh;
} else {
a_mesh = this._local_mesh.mesh;
}
if (a_mesh.isReadable) {
var vc = a_mesh.vertexCount;
for (var i = 0; i < vc; i++) {
bounds.Encapsulate(this._local_mesh.transform.TransformPoint(a_mesh.vertices[i]));
}
} else {
Debug.LogWarning("Make sure mesh is marked as readable when imported!");
}
}
if (this.includeChildren && this._children_meshes != null) {
foreach (var t in this._children_meshes) {
if (t) {
if (this._only_active_children) {
if (t.gameObject.activeInHierarchy && t.gameObject.activeSelf) {
if (bounds.size == Vector3.zero) {
var transform2 = t.transform;
position = transform2.position;
this._bb_transform.position = position;
this._bb_transform.rotation = transform2.rotation;
bounds = new Bounds(position, Vector3.zero);
}
Mesh a_mesh;
if (this._use_shared_mesh) {
a_mesh = t.sharedMesh;
} else {
a_mesh = t.mesh;
}
if (a_mesh) {
if (a_mesh.isReadable) {
var vc = a_mesh.vertexCount;
for (var j = 0; j < vc; j++) {
bounds.Encapsulate(t.transform.TransformPoint(a_mesh.vertices[j]));
}
} else {
Debug.LogWarning("Make sure mesh is marked as readable when imported!");
}
}
}
} else {
if (bounds.size == Vector3.zero) {
bounds = new Bounds(t.transform.position, Vector3.zero);
}
Mesh a_mesh;
if (this._use_shared_mesh) {
a_mesh = t.sharedMesh;
} else {
a_mesh = t.mesh;
}
if (a_mesh) {
var vc = a_mesh.vertexCount;
for (var j = 0; j < vc; j++) {
bounds.Encapsulate(t.transform.TransformPoint(a_mesh.vertices[j]));
}
}
}
}
}
}
this._Bounds = bounds;
this._Bounds_Offset = this._Bounds.center - position;
}
/// <summary>
/// </summary>
void CalculateBoundingBox() {
if (!this.RunInEditModeSetup && !Application.isPlaying || this._bb_transform == null) {
return;
}
if (this.basedOn == BasedOn.Collider_) {
switch (this.BbAligning) {
case BoundingBoxOrientation.Axis_aligned_:
this.FitCollidersAabb();
this.RecalculatePoints();
this.RecalculateLines();
break;
case BoundingBoxOrientation.Object_oriented_:
this.FitCollidersOobb();
break;
case BoundingBoxOrientation.Camera_oriented_:
this.FitRenderersCabb();
break;
default: throw new ArgumentOutOfRangeException();
}
} else {
switch (this.BbAligning) {
case BoundingBoxOrientation.Axis_aligned_:
this.FitRenderersAabb();
this.RecalculatePoints();
this.RecalculateLines();
break;
case BoundingBoxOrientation.Object_oriented_:
this.FitRenderersOobb();
break;
case BoundingBoxOrientation.Camera_oriented_:
this.FitRenderersCabb();
break;
default: throw new ArgumentOutOfRangeException();
}
}
}
void FitRenderersCabb() {
throw new NotImplementedException();
/*
var transform1 = this.transform;
var position = transform1.position;
this._bb_transform.position = position;
this._bb_transform.rotation = transform1.rotation;
var a = this._local_mesh.sharedMesh.GetCameraMinMaxPoints(this._bb_transform,
this._camera,
this.use_view_port);
var min = a[0];
var max = a[1];
var extent = a[2];
if (this.use_view_port) {
min = this._camera.ViewportToWorldPoint(min);
max = this._camera.ViewportToWorldPoint(max);
} else {
min = this._camera.ScreenToWorldPoint(min);
max = this._camera.ScreenToWorldPoint(max);
extent = max - min;
}
var cobb_extent = extent;
var cobb_center =
new Vector3(min.x + extent.x / 2.0f, min.y + extent.y / 2.0f, min.z + extent.z / 2.0f);
this._point_tfr = cobb_center + Vector3.Scale(cobb_extent, BoundingBoxUtilities._Top_Front_Right);
this._point_tfl = cobb_center + Vector3.Scale(cobb_extent, BoundingBoxUtilities._Top_Front_Left);
this._point_tbl = cobb_center + Vector3.Scale(cobb_extent, BoundingBoxUtilities._Top_Back_Left);
this._point_tbr = cobb_center + Vector3.Scale(cobb_extent, BoundingBoxUtilities._Top_Back_Right);
this._point_bfr = cobb_center + Vector3.Scale(cobb_extent, BoundingBoxUtilities._Bottom_Front_Right);
this._point_bfl = cobb_center + Vector3.Scale(cobb_extent, BoundingBoxUtilities._Bottom_Front_Left);
this._point_bbl = cobb_center + Vector3.Scale(cobb_extent, BoundingBoxUtilities._Bottom_Back_Left);
this._point_bbr = cobb_center + Vector3.Scale(cobb_extent, BoundingBoxUtilities._Bottom_Back_Right);
this._Bounds.center = cobb_center;
this._Bounds.extents = cobb_extent;
this._points = new[] {
this._point_tfr,
this._point_tfl,
this._point_tbl,
this._point_tbr,
this._point_bfr,
this._point_bfl,
this._point_bbl,
this._point_bbr
};
var rot = Quaternion.identity;
var pos = Vector3.zero;
//rot = transform1.rotation;
//pos = transform1.position;
this._lines_list.Clear();
for (var i = 0; i < 4; i++) {
//width
var line = new[] {rot * this.Points[2 * i] + pos, rot * this.Points[2 * i + 1] + pos};
this._lines_list.Add(line);
//height
line = new[] {rot * this.Points[i] + pos, rot * this.Points[i + 4] + pos};
this._lines_list.Add(line);
//depth
line = new[] {rot * this.Points[2 * i] + pos, rot * this.Points[2 * i + 3 - 4 * (i % 2)] + pos};
this._lines_list.Add(line);
}
this._lines = new Vector3[BoundingBoxUtilities._Num_Lines, BoundingBoxUtilities._Num_Points_Per_Line];
for (var j = 0; j < BoundingBoxUtilities._Num_Lines; j++) {
this.Lines[j, 0] = this._lines_list[j][0];
this.Lines[j, 1] = this._lines_list[j][1];
}
*/
}
void FitRenderersOobb() { throw new NotImplementedException(); }
void FitCollidersOobb() { throw new NotImplementedException(); }
/// <summary>
/// </summary>
void RecalculatePoints() {
this._point_tfr = this._Bounds_Offset
+ Vector3.Scale(this._Bounds.extents, BoundingBoxUtilities._Top_Front_Right);
this._point_tfl = this._Bounds_Offset
+ Vector3.Scale(this._Bounds.extents, BoundingBoxUtilities._Top_Front_Left);
this._point_tbl = this._Bounds_Offset
+ Vector3.Scale(this._Bounds.extents, BoundingBoxUtilities._Top_Back_Left);
this._point_tbr = this._Bounds_Offset
+ Vector3.Scale(this._Bounds.extents, BoundingBoxUtilities._Top_Back_Right);
this._point_bfr = this._Bounds_Offset
+ Vector3.Scale(this._Bounds.extents, BoundingBoxUtilities._Bottom_Front_Right);
this._point_bfl = this._Bounds_Offset
+ Vector3.Scale(this._Bounds.extents, BoundingBoxUtilities._Bottom_Front_Left);
this._point_bbl = this._Bounds_Offset
+ Vector3.Scale(this._Bounds.extents, BoundingBoxUtilities._Bottom_Back_Left);
this._point_bbr = this._Bounds_Offset
+ Vector3.Scale(this._Bounds.extents, BoundingBoxUtilities._Bottom_Back_Right);
this._points = new[] {
this._point_tfr,
this._point_tfl,
this._point_tbl,
this._point_tbr,
this._point_bfr,
this._point_bfl,
this._point_bbl,
this._point_bbr
};
}
/// <summary>
/// </summary>
void RecalculateLines() {
var transform1 = this.transform;
if (this._bb_transform) {
transform1 = this._bb_transform;
}
var rot = Quaternion.identity;
var pos = Vector3.zero;
if (this._use_bb_transform) {
rot = transform1.rotation;
}
pos = transform1.position;
this._lines_list.Clear();
for (var i = 0; i < 4; i++) {
//width
var line = new[] {rot * this.Points[2 * i] + pos, rot * this.Points[2 * i + 1] + pos};
this._lines_list.Add(line);
//height
line = new[] {rot * this.Points[i] + pos, rot * this.Points[i + 4] + pos};
this._lines_list.Add(line);
//depth
line = new[] {rot * this.Points[2 * i] + pos, rot * this.Points[2 * i + 3 - 4 * (i % 2)] + pos};
this._lines_list.Add(line);
}
this._lines = new Vector3[BoundingBoxUtilities._Num_Lines, BoundingBoxUtilities._Num_Points_Per_Line];
for (var j = 0; j < BoundingBoxUtilities._Num_Lines; j++) {
this.Lines[j, 0] = this._lines_list[j][0];
this.Lines[j, 1] = this._lines_list[j][1];
}
}
/// <summary>
/// </summary>
void OnMouseDown() {
//if (_permanent)
// return;
//this.enabled = !this.enabled;
}
#if UNITY_EDITOR
/// <summary>
/// </summary>
void OnValidate() {
if (!this.enabled) {
return;
}
if (EditorApplication.isPlaying) {
return;
}
this.CalculateBoundingBox();
}
/// <summary>
/// </summary>
void OnDrawGizmosSelected() {
if (this.enabled) {
Gizmos.color = this.editorPreviewLineColor;
if (this.Lines != null) {
for (var i = 0; i < this.Lines.GetLength(0); i++) {
Gizmos.DrawLine(this.Lines[i, 0], this.Lines[i, 1]);
}
} else {
Gizmos.DrawWireCube(this.Bounds.center, this.Bounds.size);
}
if (this._bb_transform) {
Handles.Label(this._bb_transform.position, this.name);
} else {
Handles.Label(this.transform.position, this.name);
}
}
}
#endif
}
}
| |
// <copyright file="SourceGenerator.cs" company="Adrian Mos">
// Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework.
// </copyright>
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IX.StandardExtensions.Extensions;
using IX.StandardExtensions.SourceGeneration.Helpers;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace IX.StandardExtensions.SourceGeneration
{
/// <summary>
/// A source generator for an automatically-disposable container.
/// </summary>
/// <seealso cref="Microsoft.CodeAnalysis.ISourceGenerator" />
[Generator]
public class SourceGenerator : ISourceGenerator
{
private readonly object lockTarget = new();
#region Methods
#region Interface implementations
/// <summary>
/// Executes the generator in the specified context.
/// </summary>
/// <param name="context">The context.</param>
[global::System.Diagnostics.CodeAnalysis.SuppressMessage(
"Performance",
"HAA0302:Display class allocation to capture closure",
Justification = "This is acceptable in this case.")]
[global::System.Diagnostics.CodeAnalysis.SuppressMessage(
"Performance",
"HAA0301:Closure Allocation Source",
Justification = "This is acceptable in this case.")]
[global::System.Diagnostics.CodeAnalysis.SuppressMessage(
"Performance",
"HAA0601:Value type to reference type conversion causing boxing allocation",
Justification = "Unavoidable, I'm afraid.")]
[global::System.Diagnostics.CodeAnalysis.SuppressMessage(
"Performance",
"HAA0603:Delegate allocation from a method group",
Justification = "No worries.")]
public void Execute(GeneratorExecutionContext context)
{
DebugDiagnosticsExtensions.Breakpoint();
if (context.SyntaxReceiver is not StandardTypesSyntaxReceiver receiver)
{
return;
}
if (receiver.Candidates.Count == 0)
{
return;
}
try
{
context.ReportDiagnostic(
Diagnostic.Create(
DiagnosticDescriptors.Dd1003,
Location.None,
receiver.Candidates.Count));
ConcurrentBag<(TypeDeclarationSyntax Type, string[] FieldNames)> autoDisposeMembers = new();
Parallel.ForEach(
receiver.Candidates,
SelectCandidateMembers);
void SelectCandidateMembers(StandardTypesSyntaxReceiver.CandidateEntry candidate)
{
var syntaxTree = candidate.TypeDeclaration.SyntaxTree;
SemanticModel semanticModel = context.Compilation.GetSemanticModel(syntaxTree);
var semanticType = semanticModel.GetDeclaredSymbol(candidate.TypeDeclaration);
if (semanticType == null)
{
return;
}
if (!candidate.IsPartial)
{
context.ReportDiagnostic(
Diagnostic.Create(
DiagnosticDescriptors.Dd1001,
Location.Create(
syntaxTree,
candidate.TypeDeclaration.Identifier.Span),
semanticType.Name));
return;
}
foreach (var member in candidate.TypeDeclaration.Members)
{
if (member is FieldDeclarationSyntax field)
{
// Test for auto-disposable
if (field.AttributeLists.Any(
q => q.Attributes.Any(
r => r.Name.ToString()
.IsAttributeName("AutoDisposableMember"))))
{
var names = field.GetDeclaredFieldNames(semanticModel);
// Check whether the base class is inherited from DisposableBase
if (semanticType.GetBaseTypesAndThis()
.All(p => p.Name != "DisposableBase"))
{
context.ReportDiagnostic(
Diagnostic.Create(
DiagnosticDescriptors.Dd1002,
Location.Create(
syntaxTree,
field.Span),
string.Join(
",",
names),
semanticType.Name));
}
else
{
autoDisposeMembers.Add((candidate.TypeDeclaration, names));
}
}
}
}
}
// Auto-dispose members
Parallel.ForEach(
autoDisposeMembers.GroupBy(p => p.Type),
ProcessAutoDispose);
void ProcessAutoDispose(
IGrouping<TypeDeclarationSyntax, (TypeDeclarationSyntax Type, string[] FieldNames)> s)
{
try
{
TypeDeclarationSyntax key = s.Key;
var syntaxTree = key.SyntaxTree;
SemanticModel semanticModel = context.Compilation.GetSemanticModel(syntaxTree);
var className = semanticModel.GetDeclaredSymbol(key)
?.Name;
if (className == null)
{
return;
}
var fileName = className.Replace(
Path.GetInvalidFileNameChars(),
'_');
StringBuilder sb = new();
sb.Append(
$@"// <auto-generated />
namespace {key.GetContainingNamespace()}
{{
");
sb.AppendAccessModifierKeywords(key.GetApplicableAccessModifier());
sb.Append(
$@"partial class {className}
{{
protected override void DisposeAutomatically()
{{
this.Dispose_AutoGenerated();
}}
private void Dispose_AutoGenerated()
{{
");
foreach (var (_, fieldNames) in s)
{
foreach (var name in fieldNames)
{
sb.Append(" this.");
sb.Append(name);
sb.AppendLine("?.Dispose();");
}
}
sb.Append(
@"
base.DisposeAutomatically();
}
}
}");
lock (this.lockTarget)
{
context.AddSource(
$"{fileName}.AutoDispose.cs",
SourceText.From(
sb.ToString(),
Encoding.UTF8));
}
}
catch (Exception ex)
{
context.ReportDiagnostic(
Diagnostic.Create(
DiagnosticDescriptors.Dd1004,
Location.None,
ex.GetType(),
ex));
}
}
}
catch (Exception e)
{
context.ReportDiagnostic(
Diagnostic.Create(
DiagnosticDescriptors.Dd1004,
Location.None,
e.GetType(),
e));
}
}
/// <summary>
/// Initializes the specified context.
/// </summary>
/// <param name="context">The context.</param>
public void Initialize(GeneratorInitializationContext context) =>
context.RegisterForSyntaxNotifications(() => new StandardTypesSyntaxReceiver());
#endregion
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO
{
public abstract class Stream : MarshalByRefObject, IDisposable
{
public static readonly Stream Null = new NullStream();
//We pick a value that is the largest multiple of 4096 that is still smaller than the large object heap threshold (85K).
// The CopyTo/CopyToAsync buffer is short-lived and is likely to be collected at Gen0, and it offers a significant
// improvement in Copy performance.
private const int DefaultCopyBufferSize = 81920;
// To implement Async IO operations on streams that don't support async IO
private SemaphoreSlim _asyncActiveSemaphore;
internal SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized()
{
// Lazily-initialize _asyncActiveSemaphore. As we're never accessing the SemaphoreSlim's
// WaitHandle, we don't need to worry about Disposing it.
return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1));
}
public abstract bool CanRead
{
[Pure]
get;
}
// If CanSeek is false, Position, Seek, Length, and SetLength should throw.
public abstract bool CanSeek
{
[Pure]
get;
}
public virtual bool CanTimeout
{
[Pure]
get
{
return false;
}
}
public abstract bool CanWrite
{
[Pure]
get;
}
public abstract long Length
{
get;
}
public abstract long Position
{
get;
set;
}
public virtual int ReadTimeout
{
get
{
throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
set
{
throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
}
public virtual int WriteTimeout
{
get
{
throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
set
{
throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
}
public Task CopyToAsync(Stream destination)
{
int bufferSize = DefaultCopyBufferSize;
if (CanSeek)
{
long length = Length;
long position = Position;
if (length <= position) // Handles negative overflows
{
// If we go down this branch, it means there are
// no bytes left in this stream.
// Ideally we would just return Task.CompletedTask here,
// but CopyToAsync(Stream, int, CancellationToken) was already
// virtual at the time this optimization was introduced. So
// if it does things like argument validation (checking if destination
// is null and throwing an exception), then await fooStream.CopyToAsync(null)
// would no longer throw if there were no bytes left. On the other hand,
// we also can't roll our own argument validation and return Task.CompletedTask,
// because it would be a breaking change if the stream's override didn't throw before,
// or in a different order. So for simplicity, we just set the bufferSize to 1
// (not 0 since the default implementation throws for 0) and forward to the virtual method.
bufferSize = 1;
}
else
{
long remaining = length - position;
if (remaining > 0) // In the case of a positive overflow, stick to the default size
bufferSize = (int)Math.Min(bufferSize, remaining);
}
}
return CopyToAsync(destination, bufferSize);
}
public Task CopyToAsync(Stream destination, int bufferSize)
{
return CopyToAsync(destination, bufferSize, CancellationToken.None);
}
public virtual Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
return CopyToAsyncInternal(destination, bufferSize, cancellationToken);
}
private async Task CopyToAsyncInternal(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
Debug.Assert(destination != null);
Debug.Assert(bufferSize > 0);
Debug.Assert(CanRead);
Debug.Assert(destination.CanWrite);
byte[] buffer = new byte[bufferSize];
while (true)
{
int bytesRead = await ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
if (bytesRead == 0) break;
await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
}
}
// Reads the bytes from the current stream and writes the bytes to
// the destination stream until all bytes are read, starting at
// the current position.
public void CopyTo(Stream destination)
{
int bufferSize = DefaultCopyBufferSize;
if (CanSeek)
{
long length = Length;
long position = Position;
if (length <= position) // Handles negative overflows
{
// No bytes left in stream
// Call the other overload with a bufferSize of 1,
// in case it's made virtual in the future
bufferSize = 1;
}
else
{
long remaining = length - position;
if (remaining > 0) // In the case of a positive overflow, stick to the default size
bufferSize = (int)Math.Min(bufferSize, remaining);
}
}
CopyTo(destination, bufferSize);
}
public virtual void CopyTo(Stream destination, int bufferSize)
{
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
byte[] buffer = new byte[bufferSize];
int read;
while ((read = Read(buffer, 0, buffer.Length)) != 0)
{
destination.Write(buffer, 0, read);
}
}
public virtual void Close()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose()
{
Close();
}
protected virtual void Dispose(bool disposing)
{
// Note: Never change this to call other virtual methods on Stream
// like Write, since the state on subclasses has already been
// torn down. This is the last code to run on cleanup for a stream.
}
public abstract void Flush();
public Task FlushAsync()
{
return FlushAsync(CancellationToken.None);
}
public virtual Task FlushAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled(cancellationToken);
}
return Task.Factory.StartNew(state => ((Stream)state).Flush(), this,
cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[Obsolete("CreateWaitHandle will be removed eventually. Please use \"new ManualResetEvent(false)\" instead.")]
protected virtual WaitHandle CreateWaitHandle()
{
return new ManualResetEvent(initialState: false);
}
public Task<int> ReadAsync(Byte[] buffer, int offset, int count)
{
return ReadAsync(buffer, offset, count, CancellationToken.None);
}
public virtual Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (!CanRead)
{
throw new NotSupportedException(SR.NotSupported_UnreadableStream);
}
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled<int>(cancellationToken) :
Task.Factory.FromAsync(
(localBuffer, localOffset, localCount, callback, state) => ((Stream)state).BeginRead(localBuffer, localOffset, localCount, callback, state),
iar => ((Stream)iar.AsyncState).EndRead(iar),
buffer, offset, count, this);
}
public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) =>
TaskToApm.Begin(ReadAsyncInternal(buffer, offset, count), callback, state);
public virtual int EndRead(IAsyncResult asyncResult) =>
TaskToApm.End<int>(asyncResult);
private Task<int> ReadAsyncInternal(Byte[] buffer, int offset, int count)
{
// To avoid a race with a stream's position pointer & generating race
// conditions with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will serialize the requests.
return EnsureAsyncActiveSemaphoreInitialized().WaitAsync().ContinueWith((completedWait, s) =>
{
Debug.Assert(completedWait.Status == TaskStatus.RanToCompletion);
var state = (Tuple<Stream, byte[], int, int>)s;
try
{
return state.Item1.Read(state.Item2, state.Item3, state.Item4); // this.Read(buffer, offset, count);
}
finally
{
state.Item1._asyncActiveSemaphore.Release();
}
}, Tuple.Create(this, buffer, offset, count), CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default);
}
public Task WriteAsync(Byte[] buffer, int offset, int count)
{
return WriteAsync(buffer, offset, count, CancellationToken.None);
}
public virtual Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (!CanWrite)
{
throw new NotSupportedException(SR.NotSupported_UnwritableStream);
}
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled<int>(cancellationToken) :
Task.Factory.FromAsync(
(localBuffer, localOffset, localCount, callback, state) => ((Stream)state).BeginWrite(localBuffer, localOffset, localCount, callback, state),
iar => ((Stream)iar.AsyncState).EndWrite(iar),
buffer, offset, count, this);
}
public virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) =>
TaskToApm.Begin(WriteAsyncInternal(buffer, offset, count), callback, state);
public virtual void EndWrite(IAsyncResult asyncResult) =>
TaskToApm.End(asyncResult);
private Task WriteAsyncInternal(Byte[] buffer, int offset, int count)
{
// To avoid a race with a stream's position pointer & generating race
// conditions with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will serialize the requests.
return EnsureAsyncActiveSemaphoreInitialized().WaitAsync().ContinueWith((completedWait, s) =>
{
Debug.Assert(completedWait.Status == TaskStatus.RanToCompletion);
var state = (Tuple<Stream, byte[], int, int>)s;
try
{
state.Item1.Write(state.Item2, state.Item3, state.Item4); // this.Write(buffer, offset, count);
}
finally
{
state.Item1._asyncActiveSemaphore.Release();
}
}, Tuple.Create(this, buffer, offset, count), CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default);
}
public abstract long Seek(long offset, SeekOrigin origin);
public abstract void SetLength(long value);
public abstract int Read(byte[] buffer, int offset, int count);
// Reads one byte from the stream by calling Read(byte[], int, int).
// Will return an unsigned byte cast to an int or -1 on end of stream.
// This implementation does not perform well because it allocates a new
// byte[] each time you call it, and should be overridden by any
// subclass that maintains an internal buffer. Then, it can help perf
// significantly for people who are reading one byte at a time.
public virtual int ReadByte()
{
byte[] oneByteArray = new byte[1];
int r = Read(oneByteArray, 0, 1);
if (r == 0)
{
return -1;
}
return oneByteArray[0];
}
public abstract void Write(byte[] buffer, int offset, int count);
// Writes one byte from the stream by calling Write(byte[], int, int).
// This implementation does not perform well because it allocates a new
// byte[] each time you call it, and should be overridden by any
// subclass that maintains an internal buffer. Then, it can help perf
// significantly for people who are writing one byte at a time.
public virtual void WriteByte(byte value)
{
byte[] oneByteArray = new byte[1];
oneByteArray[0] = value;
Write(oneByteArray, 0, 1);
}
public static Stream Synchronized(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (stream is SyncStream)
return stream;
return new SyncStream(stream);
}
[Obsolete("Do not call or override this method.")]
protected virtual void ObjectInvariant()
{
}
private sealed class NullStream : Stream
{
internal NullStream() { }
public override bool CanRead
{
[Pure]
get
{ return true; }
}
public override bool CanWrite
{
[Pure]
get
{ return true; }
}
public override bool CanSeek
{
[Pure]
get
{ return true; }
}
public override long Length
{
get { return 0; }
}
public override long Position
{
get { return 0; }
set { }
}
public override void CopyTo(Stream destination, int bufferSize)
{
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
// After we validate arguments this is a nop.
}
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
// Validate arguments for compat, since previously this
// method was inherited from Stream, which did check its arguments.
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
protected override void Dispose(bool disposing)
{
// Do nothing - we don't want NullStream singleton (static) to be closable
}
public override void Flush()
{
}
#pragma warning disable 1998 // async method with no await
public override async Task FlushAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
}
#pragma warning restore 1998
public override int Read(byte[] buffer, int offset, int count)
{
return 0;
}
#pragma warning disable 1998 // async method with no await
public override async Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return 0;
}
#pragma warning restore 1998
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) =>
TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), callback, state);
public override int EndRead(IAsyncResult asyncResult) =>
TaskToApm.End<int>(asyncResult);
public override int ReadByte()
{
return -1;
}
public override void Write(byte[] buffer, int offset, int count)
{
}
#pragma warning disable 1998 // async method with no await
public override async Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
}
#pragma warning restore 1998
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) =>
TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), callback, state);
public override void EndWrite(IAsyncResult asyncResult) =>
TaskToApm.End(asyncResult);
public override void WriteByte(byte value)
{
}
public override long Seek(long offset, SeekOrigin origin)
{
return 0;
}
public override void SetLength(long length)
{
}
}
// SyncStream is a wrapper around a stream that takes
// a lock for every operation making it thread safe.
[Serializable]
private sealed class SyncStream : Stream, IDisposable
{
private Stream _stream;
internal SyncStream(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
_stream = stream;
}
public override bool CanRead
{
[Pure]
get { return _stream.CanRead; }
}
public override bool CanWrite
{
[Pure]
get { return _stream.CanWrite; }
}
public override bool CanSeek
{
[Pure]
get { return _stream.CanSeek; }
}
public override bool CanTimeout
{
[Pure]
get
{
return _stream.CanTimeout;
}
}
public override long Length
{
get
{
lock (_stream)
{
return _stream.Length;
}
}
}
public override long Position
{
get
{
lock (_stream)
{
return _stream.Position;
}
}
set
{
lock (_stream)
{
_stream.Position = value;
}
}
}
public override int ReadTimeout
{
get
{
return _stream.ReadTimeout;
}
set
{
_stream.ReadTimeout = value;
}
}
public override int WriteTimeout
{
get
{
return _stream.WriteTimeout;
}
set
{
_stream.WriteTimeout = value;
}
}
// In the off chance that some wrapped stream has different
// semantics for Close vs. Dispose, let's preserve that.
public override void Close()
{
lock (_stream)
{
try
{
_stream.Close();
}
finally
{
base.Dispose(true);
}
}
}
protected override void Dispose(bool disposing)
{
lock (_stream)
{
try
{
// Explicitly pick up a potentially methodimpl'ed Dispose
if (disposing)
((IDisposable)_stream).Dispose();
}
finally
{
base.Dispose(disposing);
}
}
}
public override void Flush()
{
lock (_stream)
_stream.Flush();
}
public override int Read(byte[] bytes, int offset, int count)
{
lock (_stream)
return _stream.Read(bytes, offset, count);
}
public override int ReadByte()
{
lock (_stream)
return _stream.ReadByte();
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
throw new NotImplementedException(); // TODO: https://github.com/dotnet/corert/issues/3251
//bool overridesBeginRead = _stream.HasOverriddenBeginEndRead();
//lock (_stream)
//{
// // If the Stream does have its own BeginRead implementation, then we must use that override.
// // If it doesn't, then we'll use the base implementation, but we'll make sure that the logic
// // which ensures only one asynchronous operation does so with an asynchronous wait rather
// // than a synchronous wait. A synchronous wait will result in a deadlock condition, because
// // the EndXx method for the outstanding async operation won't be able to acquire the lock on
// // _stream due to this call blocked while holding the lock.
// return overridesBeginRead ?
// _stream.BeginRead(buffer, offset, count, callback, state) :
// _stream.BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true);
//}
}
public override int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
lock (_stream)
return _stream.EndRead(asyncResult);
}
public override long Seek(long offset, SeekOrigin origin)
{
lock (_stream)
return _stream.Seek(offset, origin);
}
public override void SetLength(long length)
{
lock (_stream)
_stream.SetLength(length);
}
public override void Write(byte[] bytes, int offset, int count)
{
lock (_stream)
_stream.Write(bytes, offset, count);
}
public override void WriteByte(byte b)
{
lock (_stream)
_stream.WriteByte(b);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
throw new NotImplementedException(); // TODO: https://github.com/dotnet/corert/issues/3251
//bool overridesBeginWrite = _stream.HasOverriddenBeginEndWrite();
//lock (_stream)
//{
// // If the Stream does have its own BeginWrite implementation, then we must use that override.
// // If it doesn't, then we'll use the base implementation, but we'll make sure that the logic
// // which ensures only one asynchronous operation does so with an asynchronous wait rather
// // than a synchronous wait. A synchronous wait will result in a deadlock condition, because
// // the EndXx method for the outstanding async operation won't be able to acquire the lock on
// // _stream due to this call blocked while holding the lock.
// return overridesBeginWrite ?
// _stream.BeginWrite(buffer, offset, count, callback, state) :
// _stream.BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true);
//}
}
public override void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
lock (_stream)
_stream.EndWrite(asyncResult);
}
}
}
}
| |
// 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.ServiceModel.Channels;
using System.IdentityModel.Tokens;
using System.IdentityModel.Selectors;
using System.Runtime.Serialization;
using Microsoft.Xml;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Globalization;
using System.ServiceModel.Dispatcher;
using System.Security.Authentication.ExtendedProtection;
namespace System.ServiceModel.Security
{
internal class RequestSecurityToken : BodyWriter
{
private string _context;
private string _tokenType;
private string _requestType;
private BinaryNegotiation _negotiationData;
private XmlElement _rstXml;
private IList<XmlElement> _requestProperties;
private ArraySegment<byte> _cachedWriteBuffer;
private int _cachedWriteBufferLength;
private int _keySize;
private Message _message;
private SecurityKeyIdentifierClause _renewTarget;
private SecurityKeyIdentifierClause _closeTarget;
private OnGetBinaryNegotiationCallback _onGetBinaryNegotiation;
private SecurityStandardsManager _standardsManager;
private bool _isReceiver;
private bool _isReadOnly;
private object _appliesTo;
private DataContractSerializer _appliesToSerializer;
private Type _appliesToType;
private object _thisLock = new Object();
public RequestSecurityToken()
: this(SecurityStandardsManager.DefaultInstance)
{
}
public RequestSecurityToken(MessageSecurityVersion messageSecurityVersion, SecurityTokenSerializer securityTokenSerializer)
: this(SecurityUtils.CreateSecurityStandardsManager(messageSecurityVersion, securityTokenSerializer))
{
}
public RequestSecurityToken(MessageSecurityVersion messageSecurityVersion,
SecurityTokenSerializer securityTokenSerializer,
XmlElement requestSecurityTokenXml,
string context,
string tokenType,
string requestType,
int keySize,
SecurityKeyIdentifierClause renewTarget,
SecurityKeyIdentifierClause closeTarget)
: this(SecurityUtils.CreateSecurityStandardsManager(messageSecurityVersion, securityTokenSerializer),
requestSecurityTokenXml,
context,
tokenType,
requestType,
keySize,
renewTarget,
closeTarget)
{
}
public RequestSecurityToken(XmlElement requestSecurityTokenXml,
string context,
string tokenType,
string requestType,
int keySize,
SecurityKeyIdentifierClause renewTarget,
SecurityKeyIdentifierClause closeTarget)
: this(SecurityStandardsManager.DefaultInstance,
requestSecurityTokenXml,
context,
tokenType,
requestType,
keySize,
renewTarget,
closeTarget)
{
}
internal RequestSecurityToken(SecurityStandardsManager standardsManager,
XmlElement rstXml,
string context,
string tokenType,
string requestType,
int keySize,
SecurityKeyIdentifierClause renewTarget,
SecurityKeyIdentifierClause closeTarget)
: base(true)
{
if (standardsManager == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("standardsManager"));
}
_standardsManager = standardsManager;
if (rstXml == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rstXml");
_rstXml = rstXml;
_context = context;
_tokenType = tokenType;
_keySize = keySize;
_requestType = requestType;
_renewTarget = renewTarget;
_closeTarget = closeTarget;
_isReceiver = true;
_isReadOnly = true;
}
internal RequestSecurityToken(SecurityStandardsManager standardsManager)
: this(standardsManager, true)
{
// no op
}
internal RequestSecurityToken(SecurityStandardsManager standardsManager, bool isBuffered)
: base(isBuffered)
{
if (standardsManager == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("standardsManager"));
}
_standardsManager = standardsManager;
_requestType = _standardsManager.TrustDriver.RequestTypeIssue;
_requestProperties = null;
_isReceiver = false;
_isReadOnly = false;
}
public ChannelBinding GetChannelBinding()
{
if (_message == null)
{
return null;
}
ChannelBindingMessageProperty channelBindingMessageProperty = null;
ChannelBindingMessageProperty.TryGet(_message, out channelBindingMessageProperty);
ChannelBinding channelBinding = null;
if (channelBindingMessageProperty != null)
{
channelBinding = channelBindingMessageProperty.ChannelBinding;
}
return channelBinding;
}
/// <summary>
/// Will hold a reference to the outbound message from which we will fish the ChannelBinding out of.
/// </summary>
public Message Message
{
get { return _message; }
set { _message = value; }
}
public string Context
{
get
{
return _context;
}
set
{
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ObjectIsReadOnly));
_context = value;
}
}
public string TokenType
{
get
{
return _tokenType;
}
set
{
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ObjectIsReadOnly));
_tokenType = value;
}
}
public int KeySize
{
get
{
return _keySize;
}
set
{
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ObjectIsReadOnly));
if (value < 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", SRServiceModel.ValueMustBeNonNegative));
_keySize = value;
}
}
public bool IsReadOnly
{
get
{
return _isReadOnly;
}
}
public delegate void OnGetBinaryNegotiationCallback(ChannelBinding channelBinding);
public OnGetBinaryNegotiationCallback OnGetBinaryNegotiation
{
get
{
return _onGetBinaryNegotiation;
}
set
{
if (this.IsReadOnly)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ObjectIsReadOnly));
}
_onGetBinaryNegotiation = value;
}
}
public IEnumerable<XmlElement> RequestProperties
{
get
{
if (_isReceiver)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.ItemNotAvailableInDeserializedRST, "RequestProperties")));
}
return _requestProperties;
}
set
{
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ObjectIsReadOnly));
if (value != null)
{
int index = 0;
Collection<XmlElement> coll = new Collection<XmlElement>();
foreach (XmlElement property in value)
{
if (property == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(String.Format(CultureInfo.InvariantCulture, "value[{0}]", index)));
coll.Add(property);
++index;
}
_requestProperties = coll;
}
else
{
_requestProperties = null;
}
}
}
public string RequestType
{
get
{
return _requestType;
}
set
{
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ObjectIsReadOnly));
if (value == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
_requestType = value;
}
}
public SecurityKeyIdentifierClause RenewTarget
{
get
{
return _renewTarget;
}
set
{
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ObjectIsReadOnly));
_renewTarget = value;
}
}
public SecurityKeyIdentifierClause CloseTarget
{
get
{
return _closeTarget;
}
set
{
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ObjectIsReadOnly));
_closeTarget = value;
}
}
public XmlElement RequestSecurityTokenXml
{
get
{
if (!_isReceiver)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.ItemAvailableInDeserializedRSTOnly, "RequestSecurityTokenXml")));
}
return _rstXml;
}
}
internal SecurityStandardsManager StandardsManager
{
get
{
return _standardsManager;
}
set
{
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ObjectIsReadOnly));
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value"));
}
_standardsManager = value;
}
}
internal bool IsReceiver
{
get
{
return _isReceiver;
}
}
internal object AppliesTo
{
get
{
if (_isReceiver)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.ItemNotAvailableInDeserializedRST, "AppliesTo")));
}
return _appliesTo;
}
}
internal DataContractSerializer AppliesToSerializer
{
get
{
if (_isReceiver)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.ItemNotAvailableInDeserializedRST, "AppliesToSerializer")));
}
return _appliesToSerializer;
}
}
internal Type AppliesToType
{
get
{
if (_isReceiver)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.ItemNotAvailableInDeserializedRST, "AppliesToType")));
}
return _appliesToType;
}
}
protected Object ThisLock
{
get
{
return _thisLock;
}
}
internal void SetBinaryNegotiation(BinaryNegotiation negotiation)
{
if (negotiation == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("negotiation");
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ObjectIsReadOnly));
_negotiationData = negotiation;
}
internal BinaryNegotiation GetBinaryNegotiation()
{
if (_isReceiver)
{
return _standardsManager.TrustDriver.GetBinaryNegotiation(this);
}
else if (_negotiationData == null && _onGetBinaryNegotiation != null)
{
_onGetBinaryNegotiation(this.GetChannelBinding());
}
return _negotiationData;
}
public SecurityToken GetRequestorEntropy()
{
return this.GetRequestorEntropy(null);
}
internal SecurityToken GetRequestorEntropy(SecurityTokenResolver resolver)
{
if (_isReceiver)
{
return _standardsManager.TrustDriver.GetEntropy(this, resolver);
}
else
return null;
}
public void SetAppliesTo<T>(T appliesTo, DataContractSerializer serializer)
{
if (this.IsReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ObjectIsReadOnly));
if (appliesTo != null && serializer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serializer");
}
_appliesTo = appliesTo;
_appliesToSerializer = serializer;
_appliesToType = typeof(T);
}
public void GetAppliesToQName(out string localName, out string namespaceUri)
{
if (!_isReceiver)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.ItemAvailableInDeserializedRSTOnly, "MatchesAppliesTo")));
_standardsManager.TrustDriver.GetAppliesToQName(this, out localName, out namespaceUri);
}
public T GetAppliesTo<T>()
{
return this.GetAppliesTo<T>(DataContractSerializerDefaults.CreateSerializer(typeof(T), DataContractSerializerDefaults.MaxItemsInObjectGraph));
}
public T GetAppliesTo<T>(XmlObjectSerializer serializer)
{
if (_isReceiver)
{
if (serializer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serializer");
}
return _standardsManager.TrustDriver.GetAppliesTo<T>(this, serializer);
}
else
{
return (T)_appliesTo;
}
}
private void OnWriteTo(XmlWriter writer)
{
if (_isReceiver)
{
_rstXml.WriteTo(writer);
}
else
{
_standardsManager.TrustDriver.WriteRequestSecurityToken(this, writer);
}
}
public void WriteTo(XmlWriter writer)
{
if (writer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
if (this.IsReadOnly)
{
// cache the serialized bytes to ensure repeatability
if (_cachedWriteBuffer.Array == null)
{
MemoryStream stream = new MemoryStream();
using (XmlDictionaryWriter binaryWriter = XmlDictionaryWriter.CreateBinaryWriter(stream, XD.Dictionary))
{
this.OnWriteTo(binaryWriter);
binaryWriter.Flush();
stream.Flush();
stream.Seek(0, SeekOrigin.Begin);
bool gotBuffer = stream.TryGetBuffer(out _cachedWriteBuffer);
if (!gotBuffer)
{
throw new UnauthorizedAccessException(SRServiceModel.UnauthorizedAccess_MemStreamBuffer);
}
_cachedWriteBufferLength = (int)stream.Length;
}
}
writer.WriteNode(XmlDictionaryReader.CreateBinaryReader(_cachedWriteBuffer.Array, 0, _cachedWriteBufferLength, XD.Dictionary, XmlDictionaryReaderQuotas.Max), false);
}
else
this.OnWriteTo(writer);
}
public static RequestSecurityToken CreateFrom(XmlReader reader)
{
return CreateFrom(SecurityStandardsManager.DefaultInstance, reader);
}
public static RequestSecurityToken CreateFrom(XmlReader reader, MessageSecurityVersion messageSecurityVersion, SecurityTokenSerializer securityTokenSerializer)
{
return CreateFrom(SecurityUtils.CreateSecurityStandardsManager(messageSecurityVersion, securityTokenSerializer), reader);
}
internal static RequestSecurityToken CreateFrom(SecurityStandardsManager standardsManager, XmlReader reader)
{
return standardsManager.TrustDriver.CreateRequestSecurityToken(reader);
}
public void MakeReadOnly()
{
if (!_isReadOnly)
{
_isReadOnly = true;
if (_requestProperties != null)
{
_requestProperties = new ReadOnlyCollection<XmlElement>(_requestProperties);
}
this.OnMakeReadOnly();
}
}
internal protected virtual void OnWriteCustomAttributes(XmlWriter writer) { }
internal protected virtual void OnWriteCustomElements(XmlWriter writer) { }
internal protected virtual void OnMakeReadOnly() { }
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
WriteTo(writer);
}
}
}
| |
#region license
// Copyright (c) 2003, 2004, 2005 Rodrigo B. de Oliveira (rbo@acm.org)
// 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 Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
namespace Boo.Lang.Compiler.TypeSystem
{
using System;
using System.Collections.Generic;
using Boo.Lang.Compiler.TypeSystem;
using Boo.Lang.Compiler.Ast;
/// <summary>
/// A base class for a member mapped from a generic type onto a constructed type.
/// </summary>
public abstract class GenericMappedMember<T> : IMember where T : IMember
{
protected readonly TypeSystemServices _tss;
readonly T _source;
readonly GenericMapping _genericMapping;
string _fullName = null;
protected GenericMappedMember(TypeSystemServices tss, T source, GenericMapping genericMapping)
{
_tss = tss;
_source = source;
_genericMapping = genericMapping;
}
public T Source
{
get { return _source; }
}
private string BuildFullName()
{
return DeclaringType.FullName + "." + Name;
}
public GenericMapping GenericMapping
{
get { return _genericMapping; }
}
public bool IsDuckTyped
{
get { return Source.IsDuckTyped; }
}
public IType DeclaringType
{
get { return GenericMapping.Map(Source.DeclaringType); }
}
public bool IsStatic
{
get { return Source.IsStatic; }
}
public IType Type
{
get { return GenericMapping.Map(Source.Type); }
}
public EntityType EntityType
{
get { return Source.EntityType; }
}
public string Name
{
get
{
return Source.Name;
}
}
public string FullName
{
get { return _fullName ?? (_fullName = BuildFullName()); }
}
public bool IsPublic
{
get { return Source.IsPublic; }
}
public override string ToString()
{
return FullName;
}
public bool IsDefined(IType attributeType)
{
return _source.IsDefined(attributeType);
}
}
/// <summary>
/// A base class for an accessible member mapped from a generic type onto a constructed type.
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class GenericMappedAccessibleMember<T> : GenericMappedMember<T> where T : IAccessibleMember
{
protected GenericMappedAccessibleMember(TypeSystemServices tss, T source, GenericMapping genericMapping)
: base(tss, source, genericMapping)
{
}
public bool IsProtected
{
get { return Source.IsProtected; }
}
public bool IsInternal
{
get { return Source.IsInternal; }
}
public bool IsPrivate
{
get { return Source.IsPrivate; }
}
}
#region class GenericMappedMethod
/// <summary>
/// A method on a generic constructed type.
/// </summary>
public class GenericMappedMethod : GenericMappedAccessibleMember<IMethod>, IMethod
{
IParameter[] _parameters = null;
ICallableType _callableType = null;
public GenericMappedMethod(TypeSystemServices tss, IMethod source, GenericMapping genericMapping)
: base(tss, source, genericMapping)
{
}
public bool IsAbstract
{
get { return Source.IsAbstract; }
}
public bool IsVirtual
{
get { return Source.IsVirtual; }
}
public bool IsSpecialName
{
get { return Source.IsSpecialName; }
}
public bool IsPInvoke
{
get { return Source.IsPInvoke; }
}
public virtual IConstructedMethodInfo ConstructedInfo
{
// Generic mapped methods are not generic methods - those are InternalGenericMethods
get { return null; }
}
public IGenericMethodInfo GenericInfo
{
// TODO: Generic mapped methods can be generic definitions!
get { return null; }
}
public ICallableType CallableType
{
get
{
if (null == _callableType)
{
_callableType = _tss.GetCallableType(this);
}
return _callableType;
}
}
public bool AcceptVarArgs
{
get { return Source.AcceptVarArgs; }
}
public bool IsExtension
{
get { return Source.IsExtension; }
}
public bool IsBooExtension
{
get { return Source.IsBooExtension; }
}
public bool IsClrExtension
{
get { return Source.IsClrExtension; }
}
public IType ReturnType
{
get { return GenericMapping.Map(Source.ReturnType); }
}
public IParameter[] GetParameters()
{
return _parameters ?? (_parameters = GenericMapping.Map(Source.GetParameters()));
}
}
#endregion
#region class GenericMappedConstructor
/// <summary>
/// A constructor on a generic constructed type.
/// </summary>
public class GenericMappedConstructor : GenericMappedMethod, IConstructor
{
public GenericMappedConstructor(TypeSystemServices tss, IConstructor source, GenericMapping genericMapping)
: base(tss, (IMethod)source, genericMapping)
{
}
}
#endregion
#region class GenericMappedProperty
/// <summary>
/// A property on a generic constructed type.
/// </summary>
public class GenericMappedProperty : GenericMappedAccessibleMember<IProperty>, IProperty
{
IParameter[] _parameters;
public GenericMappedProperty(TypeSystemServices tss, IProperty source, GenericMapping genericMapping)
: base(tss, source, genericMapping)
{
}
public IParameter[] GetParameters()
{
return _parameters ?? (_parameters = GenericMapping.Map(Source.GetParameters()));
}
public IMethod GetGetMethod()
{
return GenericMapping.Map(Source.GetGetMethod());
}
public IMethod GetSetMethod()
{
return GenericMapping.Map(Source.GetSetMethod());
}
public override string ToString()
{
return string.Format("{0} as {1}", Name, Type);
}
public bool AcceptVarArgs
{
get { return Source.AcceptVarArgs; }
}
public bool IsExtension
{
get { return Source.IsExtension; }
}
public bool IsBooExtension
{
get { return Source.IsBooExtension; }
}
public bool IsClrExtension
{
get { return Source.IsClrExtension; }
}
}
#endregion
#region class GenericMappedEvent
/// <summary>
/// An event in a constructed generic type.
/// </summary>
public class GenericMappedEvent : GenericMappedMember<IEvent>, IEvent
{
public GenericMappedEvent(TypeSystemServices tss, IEvent source, GenericMapping genericMapping)
: base(tss, source, genericMapping)
{
}
public IMethod GetAddMethod()
{
return GenericMapping.Map(Source.GetAddMethod());
}
public IMethod GetRemoveMethod()
{
return GenericMapping.Map(Source.GetRemoveMethod());
}
public IMethod GetRaiseMethod()
{
return GenericMapping.Map(Source.GetRemoveMethod());
}
public bool IsAbstract
{
get { return Source.IsAbstract; }
}
public bool IsVirtual
{
get { return Source.IsVirtual; }
}
}
#endregion
#region class GenericMappedField
/// <summary>
/// A field on a generic constructed type.
/// </summary>
public class GenericMappedField : GenericMappedAccessibleMember<IField>, IField
{
public GenericMappedField(TypeSystemServices tss, IField source, GenericMapping genericMapping)
: base(tss, source, genericMapping)
{
}
public bool IsInitOnly
{
get { return Source.IsInitOnly; }
}
public bool IsLiteral
{
get { return Source.IsLiteral; }
}
public object StaticValue
{
get { return Source.StaticValue; }
}
}
#endregion
#region class GenericMappedParameter
/// <summary>
/// A parameter in a method constructed from a generic method, or a mapped onto a type constructed
/// from a generic type.
/// </summary>
public class GenericMappedParameter : IParameter
{
private GenericMapping _genericMapping;
private IParameter _baseParameter;
public GenericMappedParameter(IParameter parameter, GenericMapping genericMapping)
{
_genericMapping = genericMapping;
_baseParameter = parameter;
}
public bool IsByRef
{
get { return _baseParameter.IsByRef; }
}
public IType Type
{
get { return _genericMapping.Map(_baseParameter.Type); }
}
public string Name
{
get { return _baseParameter.Name; }
}
public string FullName
{
get { return _baseParameter.FullName; }
}
public EntityType EntityType
{
get { return EntityType.Parameter; }
}
}
#endregion
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.ComponentModel;
using Microsoft.Practices.Prism.Modularity;
namespace ModularityWithMef.Desktop
{
/// <summary>
/// Provides tracking of a module's state for the quickstart.
/// </summary>
/// <remarks>
/// This class is for demonstration purposes for the quickstart and not expected to be used in a real world application.
/// </remarks>
public class ModuleTrackingState : INotifyPropertyChanged
{
private string moduleName;
private ModuleInitializationStatus moduleInitializationStatus;
private DiscoveryMethod expectedDiscoveryMethod;
private InitializationMode expectedInitializationMode;
private DownloadTiming expectedDownloadTiming;
private string configuredDependencies = "(none)";
private long bytesReceived;
private long totalBytesToReceive;
/// <summary>
/// Raised when a property value changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Gets or sets the name of the module.
/// </summary>
/// <remarks>
/// This is a display string.
/// </remarks>
public string ModuleName
{
get
{
return this.moduleName;
}
set
{
if (this.moduleName != value)
{
this.moduleName = value;
this.RaisePropertyChanged(PropertyNames.ModuleName);
}
}
}
/// <summary>
/// Gets or sets the current initialization status of the module.
/// </summary>
/// <value>A ModuleInitializationStatus value.</value>
public ModuleInitializationStatus ModuleInitializationStatus
{
get
{
return this.moduleInitializationStatus;
}
set
{
if (this.moduleInitializationStatus != value)
{
this.moduleInitializationStatus = value;
this.RaisePropertyChanged(PropertyNames.ModuleInitializationStatus);
}
}
}
/// <summary>
/// Gets or sets how the module is expected to be discovered.
/// </summary>
/// <value>A DiscoveryMethod value.</value>
/// <remarks>
/// The actual discovery method is determined by the ModuleCatalog.
/// </remarks>
public DiscoveryMethod ExpectedDiscoveryMethod
{
get
{
return this.expectedDiscoveryMethod;
}
set
{
if (this.expectedDiscoveryMethod != value)
{
this.expectedDiscoveryMethod = value;
this.RaisePropertyChanged(PropertyNames.ExpectedDiscoveryMethod);
}
}
}
/// <summary>
/// Gets or sets how the module is expected to be initialized.
/// </summary>
/// <value>An InitializationModev value.</value>
/// <remarks>
/// The actual initialization mode is determiend by the ModuleCatalog.
/// </remarks>
public InitializationMode ExpectedInitializationMode
{
get
{
return this.expectedInitializationMode;
}
set
{
if (this.expectedInitializationMode != value)
{
this.expectedInitializationMode = value;
this.RaisePropertyChanged(PropertyNames.ExpectedInitializationMode);
}
}
}
/// <summary>
/// Gets or sets how the module is expected to be downloaded.
/// </summary>
/// <value>A DownloadTiming value.</value>
/// <remarks>
/// The actual download timing is determiend by the ModuleCatalog.
/// </remarks>
public DownloadTiming ExpectedDownloadTiming
{
get
{
return this.expectedDownloadTiming;
}
set
{
if (this.expectedDownloadTiming != value)
{
this.expectedDownloadTiming = value;
this.RaisePropertyChanged(PropertyNames.ExpectedDownloadTiming);
}
}
}
/// <summary>
/// Gets or sets the list of modules the module depends on.
/// </summary>
/// <value>A string description of module dependencies.</value>
/// <remarks>
/// This is a display string.
/// </remarks>
public string ConfiguredDependencies
{
get
{
return this.configuredDependencies;
}
set
{
if (this.configuredDependencies != value)
{
this.configuredDependencies = value;
this.RaisePropertyChanged(PropertyNames.ConfiguredDependencies);
}
}
}
/// <summary>
/// Gets or sets the number of bytes received as the module is loaded.
/// </summary>
/// <value>A number of bytes.</value>
public long BytesReceived
{
get
{
return this.bytesReceived;
}
set
{
if (this.bytesReceived != value)
{
this.bytesReceived = value;
this.RaisePropertyChanged(PropertyNames.BytesReceived);
this.RaisePropertyChanged(PropertyNames.DownloadProgressPercentage);
}
}
}
/// <summary>
/// Gets or sets the total bytes to receive to load the module.
/// </summary>
/// <value>A number of bytes.</value>
public long TotalBytesToReceive
{
get
{
return this.totalBytesToReceive;
}
set
{
if (this.totalBytesToReceive != value)
{
this.totalBytesToReceive = value;
this.RaisePropertyChanged(PropertyNames.TotalBytesToReceive);
this.RaisePropertyChanged(PropertyNames.DownloadProgressPercentage);
}
}
}
/// <summary>
/// Gets the percentage of BytesReceived/TotalByteToReceive.
/// </summary>
/// <value>A percentage number between 0 and 100.</value>
public int DownloadProgressPercentage
{
get
{
if (this.bytesReceived < this.totalBytesToReceive)
{
return (int)(this.bytesReceived * 100.0 / this.totalBytesToReceive);
}
else
{
return 100;
}
}
}
private void RaisePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
/// <summary>
/// Property names used with INotifyPropertyChanged.
/// </summary>
public static class PropertyNames
{
public const string ModuleName = "ModuleName";
public const string ModuleInitializationStatus = "ModuleInitializationStatus";
public const string ExpectedDiscoveryMethod = "ExpectedDiscoveryMethod";
public const string ExpectedInitializationMode = "ExpectedInitializationMode";
public const string ExpectedDownloadTiming = "ExpectedDownloadTiming";
public const string ConfiguredDependencies = "ConfiguredDependencies";
public const string BytesReceived = "BytesReceived";
public const string TotalBytesToReceive = "TotalBytesToReceive";
public const string DownloadProgressPercentage = "DownloadProgressPercentage";
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using Skybrud.Social.Http;
using Skybrud.Social.Interfaces;
namespace Skybrud.Social.OAuth {
/// <summary>
/// OAuth client following the OAuth 1.0a protocol. The client will handle
/// the necessary communication with the OAuth server (Service Provider).
/// This includes the technical part with signatures, authorization headers
/// and similar. The client can also be used for 3-legged logins.
/// </summary>
public class OAuthClient {
/// <summary>
/// The consumer key of your application.
/// </summary>
public string ConsumerKey { get; set; }
/// <summary>
/// The consumer secret of your application. The consumer secret is
/// sensitiveinformation used to identify your application. Users s
/// hould never beshown this value.
/// </summary>
public string ConsumerSecret { get; set; }
/// <summary>
/// A unique/random value specifying the <code>oauth_nonce</code>
/// parameter in the OAuth protocol. Along with <code>oauth_timestamp</code>,
/// it will make sure each request is only sent once to the OAUth server.
/// </summary>
public string Nonce { get; set; }
/// <summary>
/// The current UNIX timestamp specifying the <code>oauth_timestamp</code>
/// in the OAuth protocol. Along with <code>oauth_nonce</code>,
/// it will make sure each request is only sent once to the OAUth server.
/// </summary>
public string Timestamp { get; set; }
/// <summary>
/// The request token or access token used to access the OAuth server on behalf of a user.
/// </summary>
public string Token { get; set; }
/// <summary>
/// The request token secret or access token secret used to access the OAuth server on behalf of a user.
/// </summary>
public string TokenSecret { get; set; }
/// <summary>
/// The version of the OAuth protocol.
/// </summary>
public string Version { get; set; }
/// <summary>
/// A callback URL. This property specified the <code>oauth_callback</code> parameter
/// and is used for 3-legged logins. In most cases this proparty should be empty.
/// </summary>
public string Callback { get; set; }
/// <summary>
/// As the first step of the 3-legged login process, the client
/// must obtain a request token through this URL. If possible
/// this URL should always use HTTPS.
/// </summary>
public string RequestTokenUrl { get; set; }
/// <summary>
/// As the second step of the 3-legged login process, the user
/// is redirected to this URL for authorizing the login. If
/// possible this URL should always use HTTPS.
/// </summary>
public string AuthorizeUrl { get; set; }
/// <summary>
/// In the final step of the 3-legged login process, the OAuth
/// client will exchange the request token for an access token.
/// It will do so using this URL. If possible this URL should
/// always use HTTPS.
/// </summary>
public string AccessTokenUrl { get; set; }
/// <summary>
/// If <code>TRUE</code>, new requests will automatically reset
/// the <code>oauth_timestamp</code> and <code>oauth_nonce</code>
/// with new values. I should only be disabled for testing
/// purposes.
/// </summary>
public bool AutoReset { get; set; }
#region Constructors
public OAuthClient() {
AutoReset = true;
Nonce = OAuthUtils.GenerateNonce();
Timestamp = OAuthUtils.GetTimestamp();
Version = "1.0";
}
public OAuthClient(string consumerKey, string consumerSecret) {
AutoReset = true;
ConsumerKey = consumerKey;
ConsumerSecret = consumerSecret;
Nonce = OAuthUtils.GenerateNonce();
Timestamp = OAuthUtils.GetTimestamp();
Version = "1.0";
}
public OAuthClient(string consumerKey, string consumerSecret, string callback) {
AutoReset = true;
ConsumerKey = consumerKey;
ConsumerSecret = consumerSecret;
Callback = callback;
Nonce = OAuthUtils.GenerateNonce();
Timestamp = OAuthUtils.GetTimestamp();
Version = "1.0";
}
#endregion
/// <summary>
/// Updates the <code>oauth_timestamp</code> and <code>oauth_nonce</code>
/// parameters with new values for another request.
/// </summary>
public virtual void Reset() {
Nonce = OAuthUtils.GenerateNonce();
Timestamp = OAuthUtils.GetTimestamp();
}
/// <summary>
/// Generates the string for the authorization header based on the specified signature.
/// </summary>
/// <param name="signature">The signature.</param>
public virtual string GenerateHeaderString(string signature) {
string oauthHeaders = "OAuth realm=\"\",";
if (!String.IsNullOrEmpty(Callback)) oauthHeaders += "oauth_callback=\"" + Uri.EscapeDataString(Callback) + "\",";
oauthHeaders += "oauth_consumer_key=\"" + Uri.EscapeDataString(ConsumerKey) + "\",";
oauthHeaders += "oauth_nonce=\"" + Uri.EscapeDataString(Nonce) + "\",";
oauthHeaders += "oauth_signature=\"" + Uri.EscapeDataString(signature) + "\",";
oauthHeaders += "oauth_signature_method=\"HMAC-SHA1\",";
oauthHeaders += "oauth_timestamp=\"" + Timestamp + "\",";
if (!String.IsNullOrEmpty(Token)) oauthHeaders += "oauth_token=\"" + Uri.EscapeDataString(Token) + "\",";
oauthHeaders += "oauth_version=\"" + Version + "\"";
return oauthHeaders;
}
/// <summary>
/// Generates the the string of parameters used for making the signature.
/// </summary>
/// <param name="queryString">Values representing the query string.</param>
/// <param name="body">Values representing the POST body.</param>
public virtual string GenerateParameterString(NameValueCollection queryString, NameValueCollection body) {
// The parameters must be alphabetically sorted
SortedDictionary<string, string> sorted = new SortedDictionary<string, string>();
// Add parameters from the query string
if (queryString != null) {
foreach (string key in queryString) {
//if (key.StartsWith("oauth_")) continue;
sorted.Add(Uri.EscapeDataString(key), Uri.EscapeDataString(queryString[key]));
}
}
// Add parameters from the POST data
if (body != null) {
foreach (string key in body) {
//if (key.StartsWith("oauth_")) continue;
sorted.Add(Uri.EscapeDataString(key), Uri.EscapeDataString(body[key]));
}
}
// Add OAuth values
if (!String.IsNullOrEmpty(Callback)) sorted.Add("oauth_callback", Uri.EscapeDataString(Callback));
sorted.Add("oauth_consumer_key", Uri.EscapeDataString(ConsumerKey));
sorted.Add("oauth_nonce", Uri.EscapeDataString(Nonce));
sorted.Add("oauth_signature_method", "HMAC-SHA1");
sorted.Add("oauth_timestamp", Uri.EscapeDataString(Timestamp));
if (!String.IsNullOrEmpty(Token)) sorted.Add("oauth_token", Uri.EscapeDataString(Token));
sorted.Add("oauth_version", Uri.EscapeDataString(Version));
// Merge all parameters
return sorted.Aggregate("", (current, pair) => current + ("&" + pair.Key + "=" + pair.Value)).Substring(1);
}
/// <summary>
/// Generates the key used for making the signature.
/// </summary>
/// <returns></returns>
public virtual string GenerateSignatureKey() {
return Uri.EscapeDataString(ConsumerSecret ?? "") + "&" + Uri.EscapeDataString(TokenSecret ?? "");
}
/// <summary>
/// Generates the string value used for making the signature.
/// </summary>
/// <param name="method">The method for the HTTP request.</param>
/// <param name="url">The URL of the request.</param>
/// <param name="queryString">The query string.</param>
/// <param name="body">The POST data.</param>
/// <returns></returns>
public virtual string GenerateSignatureValue(string method, string url, NameValueCollection queryString, NameValueCollection body) {
return String.Format(
"{0}&{1}&{2}",
method,
Uri.EscapeDataString(url.Split('#')[0].Split('?')[0]),
Uri.EscapeDataString(GenerateParameterString(queryString, body))
);
}
/// <summary>
/// Generate the signature.
/// </summary>
/// <param name="method">The method for the HTTP request.</param>
/// <param name="url">The URL of the request.</param>
/// <param name="queryString">The query string.</param>
/// <param name="body">The POST data.</param>
public virtual string GenerateSignature(string method, string url, NameValueCollection queryString, NameValueCollection body) {
HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(GenerateSignatureKey()));
return Convert.ToBase64String(hasher.ComputeHash(new ASCIIEncoding().GetBytes(GenerateSignatureValue(method, url, queryString, body))));
}
/// <summary>
/// Gets a request token from the Twitter API. After acquiring a request token, the user
/// should be redirected to the Twitter website for approving the application. If successful,
/// the user will be redirected back to the specified callback URL where you then can exchange
/// the request token for an access token.
/// </summary>
public virtual OAuthRequestToken GetRequestToken() {
// Some error checking
if (RequestTokenUrl == null) throw new ArgumentNullException("RequestTokenUrl");
if (AuthorizeUrl == null) throw new ArgumentNullException("AuthorizeUrl");
// Get the request token
HttpStatusCode status;
string response = DoHttpRequestAsString("POST", RequestTokenUrl, null, null, out status);
// Check for errors
if (status != HttpStatusCode.OK) {
throw new OAuthException(status, response);
}
// Convert the query string to a NameValueCollection
NameValueCollection query = SocialUtils.ParseQueryString(response);
// Return the request token
return new OAuthRequestToken {
Token = query["oauth_token"],
TokenSecret = query["oauth_token_secret"],
CallbackConfirmed = query["oauth_callback_confirmed"] == "true",
AuthorizeUrl = AuthorizeUrl + "?oauth_token=" + query["oauth_token"]
};
}
/// <summary>
/// Following the 3-legged authorization, you can exchange a request token for an access token
/// using this method. This is the third and final step of the authorization process.
/// </summary>
/// <param name="verifier">The verification key received after the user has accepted the app.</param>
/// <see>
/// <cref>https://dev.twitter.com/docs/auth/3-legged-authorization</cref>
/// </see>
public virtual OAuthAccessToken GetAccessToken(string verifier) {
return OAuthAccessToken.Parse(GetAccessTokenQuery(verifier));
}
/// <summary>
/// Makes a signed GET request to the specified <code>url</code>.
/// </summary>
/// <param name="url">The URL to call.</param>
public virtual SocialHttpResponse DoHttpGetRequest(string url) {
return DoHttpGetRequest(url, default(NameValueCollection));
}
/// <summary>
/// Makes a signed GET request to the specified <code>url</code>.
/// </summary>
/// <param name="url">The URL to call.</param>
/// <param name="queryString">The query string.</param>
public virtual SocialHttpResponse DoHttpGetRequest(string url, NameValueCollection queryString) {
return SocialHttpResponse.GetFromWebResponse(DoHttpRequest("GET", url, queryString, null));
}
/// <summary>
/// Makes a signed GET request to the specified <code>url</code>.
/// </summary>
/// <param name="url">The URL to call.</param>
/// <param name="queryString">The query string.</param>
public virtual SocialHttpResponse DoHttpGetRequest(string url, SocialQueryString queryString) {
return SocialHttpResponse.GetFromWebResponse(DoHttpRequest("GET", url, queryString == null ? null : queryString.NameValueCollection, null));
}
/// <summary>
/// Makes a signed GET request to the specified <code>url</code>.
/// </summary>
/// <param name="url">The URL to call.</param>
/// <param name="options">The options for the call to the API.</param>
public virtual SocialHttpResponse DoHttpGetRequest(string url, IGetOptions options) {
NameValueCollection nvc = (options == null ? null : options.GetQueryString().NameValueCollection);
return SocialHttpResponse.GetFromWebResponse(DoHttpRequest("GET", url, nvc, null));
}
/// <summary>
/// Makes a signed POST request to the specified <code>url</code>.
/// </summary>
/// <param name="url">The URL to call.</param>
/// <param name="options">The options for the call to the API.</param>
public virtual SocialHttpResponse DoHttpPostRequest(string url, IPostOptions options) {
SocialQueryString query = (options == null ? null : options.GetQueryString());
SocialPostData postData = (options == null ? null : options.GetPostData());
NameValueCollection nvcQuery = (query == null ? null : query.NameValueCollection);
NameValueCollection nvcPostData = (postData == null ? null : postData.ToNameValueCollection());
// TODO: Converting the POST data to a NameValueCollection will not support multipart data
return SocialHttpResponse.GetFromWebResponse(DoHttpRequest("POST", url, nvcQuery, nvcPostData));
}
/// <summary>
/// Makes a signed request to the Twitter API based on the specified parameters.
/// </summary>
/// <param name="method">The HTTP method of the request.</param>
/// <param name="url">The base URL of the request (no query string).</param>
/// <param name="queryString">The query string.</param>
/// <param name="postData">The POST data.</param>
public virtual HttpWebResponse DoHttpRequest(string method, string url, NameValueCollection queryString, NameValueCollection postData) {
// Check if NULL
if (queryString == null) queryString = new NameValueCollection();
if (postData == null) postData = new NameValueCollection();
// Merge the query string
if (queryString.Count > 0) {
UriBuilder builder = new UriBuilder(url);
url += (url.Contains("?") ? "&" : "") + builder.MergeQueryString(queryString).Query;
}
// Initialize the request
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
// Generate the signature
string signature = GenerateSignature(method, url, queryString, postData);
// Generate the header
string header = GenerateHeaderString(signature);
// Add the authorization header
request.Headers.Add("Authorization", header);
// Set the method
request.Method = method;
// Add the request body (if a POST request)
if (method == "POST" && postData.Count > 0) {
string dataString = SocialUtils.NameValueCollectionToQueryString(postData);
//throw new Exception(dataString);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = dataString.Length;
using (Stream stream = request.GetRequestStream()) {
stream.Write(Encoding.UTF8.GetBytes(dataString), 0, dataString.Length);
}
}
// Make sure we reset the client (timestamp and nonce)
if (AutoReset) Reset();
// Get the response
try {
return (HttpWebResponse) request.GetResponse();
} catch (WebException ex) {
if (ex.Status != WebExceptionStatus.ProtocolError) throw;
return (HttpWebResponse) ex.Response;
}
}
/// <summary>
/// Makes a signed request to the Twitter API based on the specified parameters.
/// </summary>
/// <param name="method">The HTTP method of the request.</param>
/// <param name="url">The base URL of the request (no query string).</param>
/// <param name="queryString">The query string.</param>
public virtual HttpWebResponse DoHttpRequest(string method, string url, SocialQueryString queryString) {
// TODO: Should this method have is own implementation instead of calling another DoHttpRequest method?
NameValueCollection query = queryString == null ? null : queryString.NameValueCollection;
return DoHttpRequest(method, url, query, null);
}
/// <summary>
/// Makes a signed request to the Twitter API based on the specified parameters.
/// </summary>
/// <param name="method">The HTTP method of the request.</param>
/// <param name="url">The base URL of the request (no query string).</param>
/// <param name="options">The options for the call to the API.</param>
public virtual HttpWebResponse DoHttpRequest(string method, string url, IGetOptions options) {
SocialQueryString queryString = options == null ? null : options.GetQueryString();
return DoHttpRequest(method, url, queryString);
}
/// <summary>
/// Makes a signed request to the Twitter API based on the specified parameters.
/// </summary>
/// <param name="method">The HTTP method of the request.</param>
/// <param name="url">The base URL of the request (no query string).</param>
/// <param name="queryString">The query string.</param>
/// <param name="postData">The POST data.</param>
public virtual string DoHttpRequestAsString(string method, string url, NameValueCollection queryString = null, NameValueCollection postData = null) {
using (HttpWebResponse response = DoHttpRequest(method, url, queryString, postData)) {
StreamReader reader = new StreamReader(response.GetResponseStream());
return reader.ReadToEnd();
}
}
/// <summary>
/// Makes a signed request to the Twitter API based on the specified parameters.
/// </summary>
/// <param name="method">The HTTP method of the request.</param>
/// <param name="url">The base URL of the request (no query string).</param>
/// <param name="queryString">The query string.</param>
/// <param name="postData">The POST data.</param>
/// <param name="statusCode">The status code of the response.</param>
public virtual string DoHttpRequestAsString(string method, string url, NameValueCollection queryString, NameValueCollection postData, out HttpStatusCode statusCode) {
using (HttpWebResponse response = DoHttpRequest(method, url, queryString, postData)) {
statusCode = response.StatusCode;
StreamReader reader = new StreamReader(response.GetResponseStream());
return reader.ReadToEnd();
}
}
private NameValueCollection GetAccessTokenQuery(string verifier) {
// Some error checking
if (AccessTokenUrl == null) throw new ArgumentNullException("AccessTokenUrl");
// Get the access token
HttpStatusCode status;
string response = DoHttpRequestAsString("POST", AccessTokenUrl, null, new NameValueCollection {{"oauth_verifier", verifier}}, out status);
// Check for errors
if (status != HttpStatusCode.OK) {
throw new OAuthException(status, response);
}
// Convert the query string to a NameValueCollection
return SocialUtils.ParseQueryString(response);
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !SILVERLIGHT && !MONO
namespace NLog.UnitTests.Config
{
using NLog.Config;
using System;
using System.IO;
using System.Threading;
using Xunit;
public class ReloadTests : NLogTestBase
{
[Fact]
public void TestNoAutoReload()
{
string config1 = @"<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string config2 = @"<nlog>
<targets><target name='debug' type='Debug' layout='[${message}]' /></targets>
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tempPath);
string configFilePath = Path.Combine(tempPath, "noreload.nlog");
WriteConfigFile(configFilePath, config1);
try
{
LogManager.Configuration = new XmlLoggingConfiguration(configFilePath);
Assert.False(((XmlLoggingConfiguration)LogManager.Configuration).AutoReload);
var logger = LogManager.GetLogger("A");
logger.Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
ChangeAndReloadConfigFile(configFilePath, config2, assertDidReload: false);
logger.Debug("bbb");
// Assert that config1 is still loaded.
AssertDebugLastMessage("debug", "bbb");
}
finally
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Fact]
public void TestAutoReloadOnFileChange()
{
string config1 = @"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string config2 = @"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='[${message}]' /></targets>
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string badConfig = @"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='(${message})' /></targets>
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>";
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tempPath);
string configFilePath = Path.Combine(tempPath, "reload.nlog");
WriteConfigFile(configFilePath, config1);
try
{
LogManager.Configuration = new XmlLoggingConfiguration(configFilePath);
Assert.True(((XmlLoggingConfiguration)LogManager.Configuration).AutoReload);
var logger = LogManager.GetLogger("A");
logger.Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
ChangeAndReloadConfigFile(configFilePath, badConfig, assertDidReload: false);
logger.Debug("bbb");
// Assert that config1 is still loaded.
AssertDebugLastMessage("debug", "bbb");
ChangeAndReloadConfigFile(configFilePath, config2);
logger.Debug("ccc");
// Assert that config2 is loaded.
AssertDebugLastMessage("debug", "[ccc]");
}
finally
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Fact]
public void TestAutoReloadOnFileMove()
{
string config1 = @"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string config2 = @"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='[${message}]' /></targets>
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tempPath);
string configFilePath = Path.Combine(tempPath, "reload.nlog");
WriteConfigFile(configFilePath, config1);
string otherFilePath = Path.Combine(tempPath, "other.nlog");
try
{
LogManager.Configuration = new XmlLoggingConfiguration(configFilePath);
var logger = LogManager.GetLogger("A");
logger.Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
using (var reloadWaiter = new ConfigurationReloadWaiter())
{
File.Move(configFilePath, otherFilePath);
reloadWaiter.WaitForReload();
}
logger.Debug("bbb");
// Assert that config1 is still loaded.
AssertDebugLastMessage("debug", "bbb");
WriteConfigFile(otherFilePath, config2);
using (var reloadWaiter = new ConfigurationReloadWaiter())
{
File.Move(otherFilePath, configFilePath);
reloadWaiter.WaitForReload();
Assert.True(reloadWaiter.DidReload);
}
logger.Debug("ccc");
// Assert that config2 is loaded.
AssertDebugLastMessage("debug", "[ccc]");
}
finally
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Fact]
public void TestAutoReloadOnFileCopy()
{
string config1 = @"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string config2 = @"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='[${message}]' /></targets>
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tempPath);
string configFilePath = Path.Combine(tempPath, "reload.nlog");
WriteConfigFile(configFilePath, config1);
string otherFilePath = Path.Combine(tempPath, "other.nlog");
try
{
LogManager.Configuration = new XmlLoggingConfiguration(configFilePath);
var logger = LogManager.GetLogger("A");
logger.Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
using (var reloadWaiter = new ConfigurationReloadWaiter())
{
File.Delete(configFilePath);
reloadWaiter.WaitForReload();
}
logger.Debug("bbb");
// Assert that config1 is still loaded.
AssertDebugLastMessage("debug", "bbb");
WriteConfigFile(otherFilePath, config2);
using (var reloadWaiter = new ConfigurationReloadWaiter())
{
File.Copy(otherFilePath, configFilePath);
File.Delete(otherFilePath);
reloadWaiter.WaitForReload();
Assert.True(reloadWaiter.DidReload);
}
logger.Debug("ccc");
// Assert that config2 is loaded.
AssertDebugLastMessage("debug", "[ccc]");
}
finally
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Fact]
public void TestIncludedConfigNoReload()
{
string mainConfig1 = @"<nlog>
<include file='included.nlog' />
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string mainConfig2 = @"<nlog>
<include file='included.nlog' />
<rules><logger name='*' minlevel='Info' writeTo='debug' /></rules>
</nlog>";
string includedConfig1 = @"<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
</nlog>";
string includedConfig2 = @"<nlog>
<targets><target name='debug' type='Debug' layout='[${message}]' /></targets>
</nlog>";
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tempPath);
string mainConfigFilePath = Path.Combine(tempPath, "main.nlog");
WriteConfigFile(mainConfigFilePath, mainConfig1);
string includedConfigFilePath = Path.Combine(tempPath, "included.nlog");
WriteConfigFile(includedConfigFilePath, includedConfig1);
try
{
LogManager.Configuration = new XmlLoggingConfiguration(mainConfigFilePath);
var logger = LogManager.GetLogger("A");
logger.Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
ChangeAndReloadConfigFile(mainConfigFilePath, mainConfig2, assertDidReload: false);
logger.Debug("bbb");
// Assert that mainConfig1 is still loaded.
AssertDebugLastMessage("debug", "bbb");
WriteConfigFile(mainConfigFilePath, mainConfig1);
ChangeAndReloadConfigFile(includedConfigFilePath, includedConfig2, assertDidReload: false);
logger.Debug("ccc");
// Assert that includedConfig1 is still loaded.
AssertDebugLastMessage("debug", "ccc");
}
finally
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Fact]
public void TestIncludedConfigReload()
{
string mainConfig1 = @"<nlog>
<include file='included.nlog' />
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string mainConfig2 = @"<nlog>
<include file='included.nlog' />
<rules><logger name='*' minlevel='Info' writeTo='debug' /></rules>
</nlog>";
string includedConfig1 = @"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
</nlog>";
string includedConfig2 = @"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='[${message}]' /></targets>
</nlog>";
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tempPath);
string mainConfigFilePath = Path.Combine(tempPath, "main.nlog");
WriteConfigFile(mainConfigFilePath, mainConfig1);
string includedConfigFilePath = Path.Combine(tempPath, "included.nlog");
WriteConfigFile(includedConfigFilePath, includedConfig1);
try
{
LogManager.Configuration = new XmlLoggingConfiguration(mainConfigFilePath);
var logger = LogManager.GetLogger("A");
logger.Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
ChangeAndReloadConfigFile(mainConfigFilePath, mainConfig2, assertDidReload: false);
logger.Debug("bbb");
// Assert that mainConfig1 is still loaded.
AssertDebugLastMessage("debug", "bbb");
WriteConfigFile(mainConfigFilePath, mainConfig1);
ChangeAndReloadConfigFile(includedConfigFilePath, includedConfig2);
logger.Debug("ccc");
// Assert that includedConfig2 is loaded.
AssertDebugLastMessage("debug", "[ccc]");
}
finally
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Fact]
public void TestMainConfigReload()
{
string mainConfig1 = @"<nlog autoReload='true'>
<include file='included.nlog' />
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string mainConfig2 = @"<nlog autoReload='true'>
<include file='included2.nlog' />
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string included1Config = @"<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
</nlog>";
string included2Config1 = @"<nlog>
<targets><target name='debug' type='Debug' layout='[${message}]' /></targets>
</nlog>";
string included2Config2 = @"<nlog>
<targets><target name='debug' type='Debug' layout='(${message})' /></targets>
</nlog>";
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tempPath);
string mainConfigFilePath = Path.Combine(tempPath, "main.nlog");
WriteConfigFile(mainConfigFilePath, mainConfig1);
string included1ConfigFilePath = Path.Combine(tempPath, "included.nlog");
WriteConfigFile(included1ConfigFilePath, included1Config);
string included2ConfigFilePath = Path.Combine(tempPath, "included2.nlog");
WriteConfigFile(included2ConfigFilePath, included2Config1);
try
{
LogManager.Configuration = new XmlLoggingConfiguration(mainConfigFilePath);
var logger = LogManager.GetLogger("A");
logger.Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
ChangeAndReloadConfigFile(mainConfigFilePath, mainConfig2);
logger.Debug("bbb");
// Assert that mainConfig2 is loaded (which refers to included2.nlog).
AssertDebugLastMessage("debug", "[bbb]");
ChangeAndReloadConfigFile(included2ConfigFilePath, included2Config2);
logger.Debug("ccc");
// Assert that included2Config2 is loaded.
AssertDebugLastMessage("debug", "(ccc)");
}
finally
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Fact]
public void TestMainConfigReloadIncludedConfigNoReload()
{
string mainConfig1 = @"<nlog autoReload='true'>
<include file='included.nlog' />
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string mainConfig2 = @"<nlog autoReload='true'>
<include file='included2.nlog' />
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string included1Config = @"<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
</nlog>";
string included2Config1 = @"<nlog autoReload='false'>
<targets><target name='debug' type='Debug' layout='[${message}]' /></targets>
</nlog>";
string included2Config2 = @"<nlog autoReload='false'>
<targets><target name='debug' type='Debug' layout='(${message})' /></targets>
</nlog>";
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tempPath);
string mainConfigFilePath = Path.Combine(tempPath, "main.nlog");
WriteConfigFile(mainConfigFilePath, mainConfig1);
string included1ConfigFilePath = Path.Combine(tempPath, "included.nlog");
WriteConfigFile(included1ConfigFilePath, included1Config);
string included2ConfigFilePath = Path.Combine(tempPath, "included2.nlog");
WriteConfigFile(included2ConfigFilePath, included2Config1);
try
{
LogManager.Configuration = new XmlLoggingConfiguration(mainConfigFilePath);
var logger = LogManager.GetLogger("A");
logger.Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
ChangeAndReloadConfigFile(mainConfigFilePath, mainConfig2);
logger.Debug("bbb");
// Assert that mainConfig2 is loaded (which refers to included2.nlog).
AssertDebugLastMessage("debug", "[bbb]");
ChangeAndReloadConfigFile(included2ConfigFilePath, included2Config2, assertDidReload: false);
logger.Debug("ccc");
// Assert that included2Config1 is still loaded.
AssertDebugLastMessage("debug", "[ccc]");
}
finally
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
private static void WriteConfigFile(string configFilePath, string config)
{
using (StreamWriter writer = File.CreateText(configFilePath))
writer.Write(config);
}
private static void ChangeAndReloadConfigFile(string configFilePath, string config, bool assertDidReload = true)
{
using (var reloadWaiter = new ConfigurationReloadWaiter())
{
WriteConfigFile(configFilePath, config);
reloadWaiter.WaitForReload();
if (assertDidReload)
Assert.True(reloadWaiter.DidReload, "Config did not reload.");
}
}
private class ConfigurationReloadWaiter : IDisposable
{
private CountdownEvent counterEvent = new CountdownEvent(1);
public ConfigurationReloadWaiter()
{
LogManager.ConfigurationReloaded += SignalCounterEvent(counterEvent);
}
public bool DidReload { get { return counterEvent.CurrentCount == 0; } }
public void Dispose()
{
LogManager.ConfigurationReloaded -= SignalCounterEvent(counterEvent);
}
public void WaitForReload()
{
counterEvent.Wait(2000);
}
private static EventHandler<LoggingConfigurationReloadedEventArgs> SignalCounterEvent(CountdownEvent counterEvent)
{
return (sender, e) =>
{
if (counterEvent.CurrentCount > 0)
counterEvent.Signal();
};
}
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.Intrinsics;
namespace System.Runtime.Intrinsics.X86
{
/// <summary>
/// This class provides access to Intel SSE hardware instructions via intrinsics
/// </summary>
[CLSCompliant(false)]
public abstract class Sse
{
internal Sse() { }
public static bool IsSupported { get { return false; } }
/// <summary>
/// __m128 _mm_add_ps (__m128 a, __m128 b)
/// ADDPS xmm, xmm/m128
/// </summary>
public static Vector128<float> Add(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_add_ss (__m128 a, __m128 b)
/// ADDSS xmm, xmm/m32
/// </summary>
public static Vector128<float> AddScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_and_ps (__m128 a, __m128 b)
/// ANDPS xmm, xmm/m128
/// </summary>
public static Vector128<float> And(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_andnot_ps (__m128 a, __m128 b)
/// ANDNPS xmm, xmm/m128
/// </summary>
public static Vector128<float> AndNot(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_cmpeq_ps (__m128 a, __m128 b)
/// CMPPS xmm, xmm/m128, imm8(0)
/// </summary>
public static Vector128<float> CompareEqual(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_comieq_ss (__m128 a, __m128 b)
/// COMISS xmm, xmm/m32
/// </summary>
public static bool CompareEqualOrderedScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_ucomieq_ss (__m128 a, __m128 b)
/// UCOMISS xmm, xmm/m32
/// </summary>
public static bool CompareEqualUnorderedScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_cmpeq_ss (__m128 a, __m128 b)
/// CMPSS xmm, xmm/m32, imm8(0)
/// </summary>
public static Vector128<float> CompareEqualScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_cmpgt_ps (__m128 a, __m128 b)
/// CMPPS xmm, xmm/m128, imm8(6)
/// </summary>
public static Vector128<float> CompareGreaterThan(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_comigt_ss (__m128 a, __m128 b)
/// COMISS xmm, xmm/m32
/// </summary>
public static bool CompareGreaterThanOrderedScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_ucomigt_ss (__m128 a, __m128 b)
/// UCOMISS xmm, xmm/m32
/// </summary>
public static bool CompareGreaterThanUnorderedScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_cmpgt_ss (__m128 a, __m128 b)
/// CMPSS xmm, xmm/m32, imm8(6)
/// </summary>
public static Vector128<float> CompareGreaterThanScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_cmpge_ps (__m128 a, __m128 b)
/// CMPPS xmm, xmm/m128, imm8(5)
/// </summary>
public static Vector128<float> CompareGreaterThanOrEqual(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_comige_ss (__m128 a, __m128 b)
/// COMISS xmm, xmm/m32
/// </summary>
public static bool CompareGreaterThanOrEqualOrderedScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_ucomige_ss (__m128 a, __m128 b)
/// UCOMISS xmm, xmm/m32
/// </summary>
public static bool CompareGreaterThanOrEqualUnorderedScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_cmpge_ss (__m128 a, __m128 b)
/// CMPPS xmm, xmm/m32, imm8(5)
/// </summary>
public static Vector128<float> CompareGreaterThanOrEqualScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_cmplt_ps (__m128 a, __m128 b)
/// CMPPS xmm, xmm/m128, imm8(1)
/// </summary>
public static Vector128<float> CompareLessThan(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_comilt_ss (__m128 a, __m128 b)
/// COMISS xmm, xmm/m32
/// </summary>
public static bool CompareLessThanOrderedScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_ucomilt_ss (__m128 a, __m128 b)
/// UCOMISS xmm, xmm/m32
/// </summary>
public static bool CompareLessThanUnorderedScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_cmplt_ss (__m128 a, __m128 b)
/// CMPSS xmm, xmm/m32, imm8(1)
/// </summary>
public static Vector128<float> CompareLessThanScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_cmple_ps (__m128 a, __m128 b)
/// CMPPS xmm, xmm/m128, imm8(2)
/// </summary>
public static Vector128<float> CompareLessThanOrEqual(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_comile_ss (__m128 a, __m128 b)
/// COMISS xmm, xmm/m32
/// </summary>
public static bool CompareLessThanOrEqualOrderedScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_ucomile_ss (__m128 a, __m128 b)
/// UCOMISS xmm, xmm/m32
/// </summary>
public static bool CompareLessThanOrEqualUnorderedScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_cmple_ss (__m128 a, __m128 b)
/// CMPSS xmm, xmm/m32, imm8(2)
/// </summary>
public static Vector128<float> CompareLessThanOrEqualScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_cmpneq_ps (__m128 a, __m128 b)
/// CMPPS xmm, xmm/m128, imm8(4)
/// </summary>
public static Vector128<float> CompareNotEqual(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_comineq_ss (__m128 a, __m128 b)
/// COMISS xmm, xmm/m32
/// </summary>
public static bool CompareNotEqualOrderedScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_ucomineq_ss (__m128 a, __m128 b)
/// UCOMISS xmm, xmm/m32
/// </summary>
public static bool CompareNotEqualUnorderedScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_cmpneq_ss (__m128 a, __m128 b)
/// CMPSS xmm, xmm/m32, imm8(4)
/// </summary>
public static Vector128<float> CompareNotEqualScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_cmpngt_ps (__m128 a, __m128 b)
/// CMPPS xmm, xmm/m128, imm8(2)
/// </summary>
public static Vector128<float> CompareNotGreaterThan(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_cmpngt_ss (__m128 a, __m128 b)
/// CMPSS xmm, xmm/m32, imm8(2)
/// </summary>
public static Vector128<float> CompareNotGreaterThanScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_cmpnge_ps (__m128 a, __m128 b)
/// CMPPS xmm, xmm/m128, imm8(1)
/// </summary>
public static Vector128<float> CompareNotGreaterThanOrEqual(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_cmpnge_ss (__m128 a, __m128 b)
/// CMPSS xmm, xmm/m32, imm8(1)
/// </summary>
public static Vector128<float> CompareNotGreaterThanOrEqualScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_cmpnlt_ps (__m128 a, __m128 b)
/// CMPPS xmm, xmm/m128, imm8(5)
/// </summary>
public static Vector128<float> CompareNotLessThan(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_cmpnlt_ss (__m128 a, __m128 b)
/// CMPSS xmm, xmm/m32, imm8(5)
/// </summary>
public static Vector128<float> CompareNotLessThanScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_cmpnle_ps (__m128 a, __m128 b)
/// CMPPS xmm, xmm/m128, imm8(6)
/// </summary>
public static Vector128<float> CompareNotLessThanOrEqual(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_cmpnle_ss (__m128 a, __m128 b)
/// CMPSS xmm, xmm/m32, imm8(6)
/// </summary>
public static Vector128<float> CompareNotLessThanOrEqualScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_cmpord_ps (__m128 a, __m128 b)
/// CMPPS xmm, xmm/m128, imm8(7)
/// </summary>
public static Vector128<float> CompareOrdered(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_cmpord_ss (__m128 a, __m128 b)
/// CMPSS xmm, xmm/m32, imm8(7)
/// </summary>
public static Vector128<float> CompareOrderedScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_cmpunord_ps (__m128 a, __m128 b)
/// CMPPS xmm, xmm/m128, imm8(3)
/// </summary>
public static Vector128<float> CompareUnordered(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_cmpunord_ss (__m128 a, __m128 b)
/// CMPSS xmm, xmm/m32, imm8(3)
/// </summary>
public static Vector128<float> CompareUnorderedScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_cvtss_si32 (__m128 a)
/// CVTSS2SI r32, xmm/m32
/// </summary>
public static int ConvertToInt32(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __int64 _mm_cvtss_si64 (__m128 a)
/// CVTSS2SI r64, xmm/m32
/// </summary>
public static long ConvertToInt64(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// float _mm_cvtss_f32 (__m128 a)
/// HELPER: MOVSS
/// </summary>
public static float ConvertToSingle(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_cvtsi32_ss (__m128 a, int b)
/// CVTSI2SS xmm, reg/m32
/// </summary>
public static Vector128<float> ConvertScalarToVector128Single(Vector128<float> upper, int value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_cvtsi64_ss (__m128 a, __int64 b)
/// CVTSI2SS xmm, reg/m64
/// </summary>
public static Vector128<float> ConvertScalarToVector128Single(Vector128<float> upper, long value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_cvttss_si32 (__m128 a)
/// CVTTSS2SI r32, xmm/m32
/// </summary>
public static int ConvertToInt32WithTruncation(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __int64 _mm_cvttss_si64 (__m128 a)
/// CVTTSS2SI r64, xmm/m32
/// </summary>
public static long ConvertToInt64WithTruncation(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_div_ps (__m128 a, __m128 b)
/// DIVPS xmm, xmm/m128
/// </summary>
public static Vector128<float> Divide(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_div_ss (__m128 a, __m128 b)
/// DIVSS xmm, xmm/m32
/// </summary>
public static Vector128<float> DivideScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_loadu_ps (float const* mem_address)
/// MOVUPS xmm, m128
/// </summary>
public static unsafe Vector128<float> LoadVector128(float* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_load_ss (float const* mem_address)
/// MOVSS xmm, m32
/// </summary>
public static unsafe Vector128<float> LoadScalarVector128(float* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_load_ps (float const* mem_address)
/// MOVAPS xmm, m128
/// </summary>
public static unsafe Vector128<float> LoadAlignedVector128(float* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_loadh_pi (__m128 a, __m64 const* mem_addr)
/// MOVHPS xmm, m64
/// </summary>
public static unsafe Vector128<float> LoadHigh(Vector128<float> lower, float* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_loadl_pi (__m128 a, __m64 const* mem_addr)
/// MOVLPS xmm, m64
/// </summary>
public static unsafe Vector128<float> LoadLow(Vector128<float> upper, float* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_max_ps (__m128 a, __m128 b)
/// MAXPS xmm, xmm/m128
/// </summary>
public static Vector128<float> Max(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_max_ss (__m128 a, __m128 b)
/// MAXSS xmm, xmm/m32
/// </summary>
public static Vector128<float> MaxScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_min_ps (__m128 a, __m128 b)
/// MINPS xmm, xmm/m128
/// </summary>
public static Vector128<float> Min(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_min_ss (__m128 a, __m128 b)
/// MINSS xmm, xmm/m32
/// </summary>
public static Vector128<float> MinScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_move_ss (__m128 a, __m128 b)
/// MOVSS xmm, xmm
/// </summary>
public static Vector128<float> MoveScalar(Vector128<float> upper, Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_movehl_ps (__m128 a, __m128 b)
/// MOVHLPS xmm, xmm
/// </summary>
public static Vector128<float> MoveHighToLow(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_movelh_ps (__m128 a, __m128 b)
/// MOVLHPS xmm, xmm
/// </summary>
public static Vector128<float> MoveLowToHigh(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_movemask_ps (__m128 a)
/// MOVMSKPS reg, xmm
/// </summary>
public static int MoveMask(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_mul_ps (__m128 a, __m128 b)
/// MULPS xmm, xmm/m128
/// </summary>
public static Vector128<float> Multiply(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_mul_ss (__m128 a, __m128 b)
/// MULPS xmm, xmm/m32
/// </summary>
public static Vector128<float> MultiplyScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// void _mm_prefetch(char* p, int i)
/// PREFETCHT0 m8
/// </summary>
public static unsafe void Prefetch0(void* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// void _mm_prefetch(char* p, int i)
/// PREFETCHT1 m8
/// </summary>
public static unsafe void Prefetch1(void* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// void _mm_prefetch(char* p, int i)
/// PREFETCHT2 m8
/// </summary>
public static unsafe void Prefetch2(void* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// void _mm_prefetch(char* p, int i)
/// PREFETCHNTA m8
/// </summary>
public static unsafe void PrefetchNonTemporal(void* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_or_ps (__m128 a, __m128 b)
/// ORPS xmm, xmm/m128
/// </summary>
public static Vector128<float> Or(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_rcp_ps (__m128 a)
/// RCPPS xmm, xmm/m128
/// </summary>
public static Vector128<float> Reciprocal(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_rcp_ss (__m128 a)
/// RCPSS xmm, xmm/m32
/// </summary>
public static Vector128<float> ReciprocalScalar(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_rcp_ss (__m128 a, __m128 b)
/// RCPSS xmm, xmm/m32
/// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs.
/// </summary>
public static Vector128<float> ReciprocalScalar(Vector128<float> upper, Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_rsqrt_ps (__m128 a)
/// RSQRTPS xmm, xmm/m128
/// </summary>
public static Vector128<float> ReciprocalSqrt(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_rsqrt_ss (__m128 a)
/// RSQRTSS xmm, xmm/m32
/// </summary>
public static Vector128<float> ReciprocalSqrtScalar(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_rsqrt_ss (__m128 a, __m128 b)
/// RSQRTSS xmm, xmm/m32
/// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs.
/// </summary>
public static Vector128<float> ReciprocalSqrtScalar(Vector128<float> upper, Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_set_ps (float e3, float e2, float e1, float e0)
/// </summary>
public static Vector128<float> SetVector128(float e3, float e2, float e1, float e0) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_set_ss (float a)
/// HELPER
/// </summary>
public static Vector128<float> SetScalarVector128(float value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_set1_ps (float a)
/// HELPER
/// </summary>
public static Vector128<float> SetAllVector128(float value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_setzero_ps (void)
/// HELPER - XORPS
/// </summary>
public static Vector128<float> SetZeroVector128() { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_castpd_ps (__m128d a)
/// HELPER - No Codegen
/// __m128i _mm_castpd_si128 (__m128d a)
/// HELPER - No Codegen
/// __m128d _mm_castps_pd (__m128 a)
/// HELPER - No Codegen
/// __m128i _mm_castps_si128 (__m128 a)
/// HELPER - No Codegen
/// __m128d _mm_castsi128_pd (__m128i a)
/// HELPER - No Codegen
/// __m128 _mm_castsi128_ps (__m128i a)
/// HELPER - No Codegen
/// </summary>
public static Vector128<U> StaticCast<T, U>(Vector128<T> value) where T : struct where U : struct { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_shuffle_ps (__m128 a, __m128 b, unsigned int control)
/// SHUFPS xmm, xmm/m128, imm8
/// </summary>
public static Vector128<float> Shuffle(Vector128<float> left, Vector128<float> right, byte control) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_sqrt_ps (__m128 a)
/// SQRTPS xmm, xmm/m128
/// </summary>
public static Vector128<float> Sqrt(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_sqrt_ss (__m128 a)
/// SQRTSS xmm, xmm/m32
/// </summary>
public static Vector128<float> SqrtScalar(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_sqrt_ss (__m128 a, __m128 b)
/// SQRTSS xmm, xmm/m32
/// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs.
/// </summary>
public static Vector128<float> SqrtScalar(Vector128<float> upper, Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// void _mm_store_ps (float* mem_addr, __m128 a)
/// MOVAPS m128, xmm
/// </summary>
public static unsafe void StoreAligned(float* address, Vector128<float> source) { throw new PlatformNotSupportedException(); }
/// <summary>
/// void _mm_stream_ps (float* mem_addr, __m128 a)
/// MOVNTPS m128, xmm
/// </summary>
public static unsafe void StoreAlignedNonTemporal(float* address, Vector128<float> source) { throw new PlatformNotSupportedException(); }
/// <summary>
/// void _mm_storeu_ps (float* mem_addr, __m128 a)
/// MOVUPS m128, xmm
/// </summary>
public static unsafe void Store(float* address, Vector128<float> source) { throw new PlatformNotSupportedException(); }
/// <summary>
/// void _mm_sfence(void)
/// SFENCE
/// </summary>
public static void StoreFence() { throw new PlatformNotSupportedException(); }
/// <summary>
/// void _mm_store_ss (float* mem_addr, __m128 a)
/// MOVSS m32, xmm
/// </summary>
public static unsafe void StoreScalar(float* address, Vector128<float> source) { throw new PlatformNotSupportedException(); }
/// <summary>
/// void _mm_storeh_pi (__m64* mem_addr, __m128 a)
/// MOVHPS m64, xmm
/// </summary>
public static unsafe void StoreHigh(float* address, Vector128<float> source) { throw new PlatformNotSupportedException(); }
/// <summary>
/// void _mm_storel_pi (__m64* mem_addr, __m128 a)
/// MOVLPS m64, xmm
/// </summary>
public static unsafe void StoreLow(float* address, Vector128<float> source) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_sub_ps (__m128d a, __m128d b)
/// SUBPS xmm, xmm/m128
/// </summary>
public static Vector128<float> Subtract(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_sub_ss (__m128 a, __m128 b)
/// SUBSS xmm, xmm/m32
/// </summary>
public static Vector128<float> SubtractScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_unpackhi_ps (__m128 a, __m128 b)
/// UNPCKHPS xmm, xmm/m128
/// </summary>
public static Vector128<float> UnpackHigh(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_unpacklo_ps (__m128 a, __m128 b)
/// UNPCKLPS xmm, xmm/m128
/// </summary>
public static Vector128<float> UnpackLow(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_xor_ps (__m128 a, __m128 b)
/// XORPS xmm, xmm/m128
/// </summary>
public static Vector128<float> Xor(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); }
}
}
| |
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 SearchCTC.WebAPI.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;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace System.Threading
{
/// <summary>
/// Propagates notification that operations should be canceled.
/// </summary>
/// <remarks>
/// <para>
/// A <see cref="CancellationToken"/> may be created directly in an unchangeable canceled or non-canceled state
/// using the CancellationToken's constructors. However, to have a CancellationToken that can change
/// from a non-canceled to a canceled state,
/// <see cref="System.Threading.CancellationTokenSource">CancellationTokenSource</see> must be used.
/// CancellationTokenSource exposes the associated CancellationToken that may be canceled by the source through its
/// <see cref="System.Threading.CancellationTokenSource.Token">Token</see> property.
/// </para>
/// <para>
/// Once canceled, a token may not transition to a non-canceled state, and a token whose
/// <see cref="CanBeCanceled"/> is false will never change to one that can be canceled.
/// </para>
/// <para>
/// All members of this struct are thread-safe and may be used concurrently from multiple threads.
/// </para>
/// </remarks>
[DebuggerDisplay("IsCancellationRequested = {IsCancellationRequested}")]
public struct CancellationToken
{
private readonly static Action<object> s_actionToActionObjShunt = obj => ((Action)obj)();
// The backing TokenSource.
// if null, it implicitly represents the same thing as new CancellationToken(false).
// When required, it will be instantiated to reflect this.
private readonly CancellationTokenSource _source;
//!! warning. If more fields are added, the assumptions in CreateLinkedToken may no longer be valid
/// <summary>
/// Returns an empty CancellationToken value.
/// </summary>
/// <remarks>
/// The <see cref="CancellationToken"/> value returned by this property will be non-cancelable by default.
/// </remarks>
public static CancellationToken None => default(CancellationToken);
/// <summary>
/// Gets whether cancellation has been requested for this token.
/// </summary>
/// <value>Whether cancellation has been requested for this token.</value>
/// <remarks>
/// <para>
/// This property indicates whether cancellation has been requested for this token,
/// either through the token initially being constructed in a canceled state, or through
/// calling <see cref="System.Threading.CancellationTokenSource.Cancel()">Cancel</see>
/// on the token's associated <see cref="CancellationTokenSource"/>.
/// </para>
/// <para>
/// If this property is true, it only guarantees that cancellation has been requested.
/// It does not guarantee that every registered handler
/// has finished executing, nor that cancellation requests have finished propagating
/// to all registered handlers. Additional synchronization may be required,
/// particularly in situations where related objects are being canceled concurrently.
/// </para>
/// </remarks>
public bool IsCancellationRequested => _source != null && _source.IsCancellationRequested;
/// <summary>
/// Gets whether this token is capable of being in the canceled state.
/// </summary>
/// <remarks>
/// If CanBeCanceled returns false, it is guaranteed that the token will never transition
/// into a canceled state, meaning that <see cref="IsCancellationRequested"/> will never
/// return true.
/// </remarks>
public bool CanBeCanceled => _source != null;
/// <summary>
/// Gets a <see cref="T:System.Threading.WaitHandle"/> that is signaled when the token is canceled.</summary>
/// <remarks>
/// Accessing this property causes a <see cref="T:System.Threading.WaitHandle">WaitHandle</see>
/// to be instantiated. It is preferable to only use this property when necessary, and to then
/// dispose the associated <see cref="CancellationTokenSource"/> instance at the earliest opportunity (disposing
/// the source will dispose of this allocated handle). The handle should not be closed or disposed directly.
/// </remarks>
/// <exception cref="T:System.ObjectDisposedException">The associated <see
/// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception>
public WaitHandle WaitHandle => (_source ?? CancellationTokenSource.s_neverCanceledSource).WaitHandle;
// public CancellationToken()
// this constructor is implicit for structs
// -> this should behaves exactly as for new CancellationToken(false)
/// <summary>
/// Internal constructor only a CancellationTokenSource should create a CancellationToken
/// </summary>
internal CancellationToken(CancellationTokenSource source) => _source = source;
/// <summary>
/// Initializes the <see cref="T:System.Threading.CancellationToken">CancellationToken</see>.
/// </summary>
/// <param name="canceled">
/// The canceled state for the token.
/// </param>
/// <remarks>
/// Tokens created with this constructor will remain in the canceled state specified
/// by the <paramref name="canceled"/> parameter. If <paramref name="canceled"/> is false,
/// both <see cref="CanBeCanceled"/> and <see cref="IsCancellationRequested"/> will be false.
/// If <paramref name="canceled"/> is true,
/// both <see cref="CanBeCanceled"/> and <see cref="IsCancellationRequested"/> will be true.
/// </remarks>
public CancellationToken(bool canceled) : this(canceled ? CancellationTokenSource.s_canceledSource : null)
{
}
/// <summary>
/// Registers a delegate that will be called when this <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.
/// </summary>
/// <remarks>
/// <para>
/// If this token is already in the canceled state, the
/// delegate will be run immediately and synchronously. Any exception the delegate generates will be
/// propagated out of this method call.
/// </para>
/// <para>
/// The current <see cref="System.Threading.ExecutionContext">ExecutionContext</see>, if one exists, will be captured
/// along with the delegate and will be used when executing it.
/// </para>
/// </remarks>
/// <param name="callback">The delegate to be executed when the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.</param>
/// <returns>The <see cref="T:System.Threading.CancellationTokenRegistration"/> instance that can
/// be used to deregister the callback.</returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="callback"/> is null.</exception>
public CancellationTokenRegistration Register(Action callback) =>
Register(
s_actionToActionObjShunt,
callback ?? throw new ArgumentNullException(nameof(callback)),
useSyncContext: false,
useExecutionContext: true);
/// <summary>
/// Registers a delegate that will be called when this
/// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.
/// </summary>
/// <remarks>
/// <para>
/// If this token is already in the canceled state, the
/// delegate will be run immediately and synchronously. Any exception the delegate generates will be
/// propagated out of this method call.
/// </para>
/// <para>
/// The current <see cref="System.Threading.ExecutionContext">ExecutionContext</see>, if one exists, will be captured
/// along with the delegate and will be used when executing it.
/// </para>
/// </remarks>
/// <param name="callback">The delegate to be executed when the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.</param>
/// <param name="useSynchronizationContext">A Boolean value that indicates whether to capture
/// the current <see cref="T:System.Threading.SynchronizationContext">SynchronizationContext</see> and use it
/// when invoking the <paramref name="callback"/>.</param>
/// <returns>The <see cref="T:System.Threading.CancellationTokenRegistration"/> instance that can
/// be used to deregister the callback.</returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="callback"/> is null.</exception>
public CancellationTokenRegistration Register(Action callback, bool useSynchronizationContext) =>
Register(
s_actionToActionObjShunt,
callback ?? throw new ArgumentNullException(nameof(callback)),
useSynchronizationContext,
useExecutionContext: true);
/// <summary>
/// Registers a delegate that will be called when this
/// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.
/// </summary>
/// <remarks>
/// <para>
/// If this token is already in the canceled state, the
/// delegate will be run immediately and synchronously. Any exception the delegate generates will be
/// propagated out of this method call.
/// </para>
/// <para>
/// The current <see cref="System.Threading.ExecutionContext">ExecutionContext</see>, if one exists, will be captured
/// along with the delegate and will be used when executing it.
/// </para>
/// </remarks>
/// <param name="callback">The delegate to be executed when the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.</param>
/// <param name="state">The state to pass to the <paramref name="callback"/> when the delegate is invoked. This may be null.</param>
/// <returns>The <see cref="T:System.Threading.CancellationTokenRegistration"/> instance that can
/// be used to deregister the callback.</returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="callback"/> is null.</exception>
public CancellationTokenRegistration Register(Action<object> callback, object state) =>
Register(callback, state, useSyncContext: false, useExecutionContext: true);
/// <summary>
/// Registers a delegate that will be called when this
/// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.
/// </summary>
/// <remarks>
/// <para>
/// If this token is already in the canceled state, the
/// delegate will be run immediately and synchronously. Any exception the delegate generates will be
/// propagated out of this method call.
/// </para>
/// <para>
/// The current <see cref="System.Threading.ExecutionContext">ExecutionContext</see>, if one exists,
/// will be captured along with the delegate and will be used when executing it.
/// </para>
/// </remarks>
/// <param name="callback">The delegate to be executed when the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.</param>
/// <param name="state">The state to pass to the <paramref name="callback"/> when the delegate is invoked. This may be null.</param>
/// <param name="useSynchronizationContext">A Boolean value that indicates whether to capture
/// the current <see cref="T:System.Threading.SynchronizationContext">SynchronizationContext</see> and use it
/// when invoking the <paramref name="callback"/>.</param>
/// <returns>The <see cref="T:System.Threading.CancellationTokenRegistration"/> instance that can
/// be used to deregister the callback.</returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="callback"/> is null.</exception>
/// <exception cref="T:System.ObjectDisposedException">The associated <see
/// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception>
public CancellationTokenRegistration Register(Action<object> callback, object state, bool useSynchronizationContext) =>
Register(callback, state, useSynchronizationContext, useExecutionContext: true);
// helper for internal registration needs that don't require an EC capture (e.g. creating linked token sources, or registering unstarted TPL tasks)
// has a handy signature, and skips capturing execution context.
internal CancellationTokenRegistration InternalRegisterWithoutEC(Action<object> callback, object state) =>
Register(callback, state, useSyncContext: false, useExecutionContext: false);
// the real work..
private CancellationTokenRegistration Register(Action<object> callback, object state, bool useSyncContext, bool useExecutionContext)
{
if (callback == null)
{
throw new ArgumentNullException(nameof(callback));
}
CancellationTokenSource source = _source;
return source != null ?
source.InternalRegister(callback, state, useSyncContext ? SynchronizationContext.Current : null, useExecutionContext ? ExecutionContext.Capture() : null) :
default(CancellationTokenRegistration); // Nothing to do for tokens than can never reach the canceled state. Give back a dummy registration.
}
/// <summary>
/// Determines whether the current <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instance is equal to the
/// specified token.
/// </summary>
/// <param name="other">The other <see cref="T:System.Threading.CancellationToken">CancellationToken</see> to which to compare this
/// instance.</param>
/// <returns>True if the instances are equal; otherwise, false. Two tokens are equal if they are associated
/// with the same <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> or if they were both constructed
/// from public CancellationToken constructors and their <see cref="IsCancellationRequested"/> values are equal.</returns>
public bool Equals(CancellationToken other) => _source == other._source;
/// <summary>
/// Determines whether the current <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instance is equal to the
/// specified <see cref="T:System.Object"/>.
/// </summary>
/// <param name="other">The other object to which to compare this instance.</param>
/// <returns>True if <paramref name="other"/> is a <see cref="T:System.Threading.CancellationToken">CancellationToken</see>
/// and if the two instances are equal; otherwise, false. Two tokens are equal if they are associated
/// with the same <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> or if they were both constructed
/// from public CancellationToken constructors and their <see cref="IsCancellationRequested"/> values are equal.</returns>
/// <exception cref="T:System.ObjectDisposedException">An associated <see
/// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception>
public override bool Equals(object other) => other is CancellationToken && Equals((CancellationToken)other);
/// <summary>
/// Serves as a hash function for a <see cref="T:System.Threading.CancellationToken">CancellationToken</see>.
/// </summary>
/// <returns>A hash code for the current <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instance.</returns>
public override int GetHashCode() => (_source ?? CancellationTokenSource.s_neverCanceledSource).GetHashCode();
/// <summary>
/// Determines whether two <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instances are equal.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>True if the instances are equal; otherwise, false.</returns>
/// <exception cref="T:System.ObjectDisposedException">An associated <see
/// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception>
public static bool operator ==(CancellationToken left, CancellationToken right) => left.Equals(right);
/// <summary>
/// Determines whether two <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instances are not equal.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>True if the instances are not equal; otherwise, false.</returns>
/// <exception cref="T:System.ObjectDisposedException">An associated <see
/// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception>
public static bool operator !=(CancellationToken left, CancellationToken right) => !left.Equals(right);
/// <summary>
/// Throws a <see cref="T:System.OperationCanceledException">OperationCanceledException</see> if
/// this token has had cancellation requested.
/// </summary>
/// <remarks>
/// This method provides functionality equivalent to:
/// <code>
/// if (token.IsCancellationRequested)
/// throw new OperationCanceledException(token);
/// </code>
/// </remarks>
/// <exception cref="System.OperationCanceledException">The token has had cancellation requested.</exception>
/// <exception cref="T:System.ObjectDisposedException">The associated <see
/// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception>
public void ThrowIfCancellationRequested()
{
if (IsCancellationRequested)
{
ThrowOperationCanceledException();
}
}
// Throws an OCE; separated out to enable better inlining of ThrowIfCancellationRequested
private void ThrowOperationCanceledException() =>
throw new OperationCanceledException(SR.OperationCanceled, this);
private static void ThrowObjectDisposedException() =>
throw new ObjectDisposedException(null, SR.CancellationToken_SourceDisposed);
}
}
| |
using OpenSim.Region.CoreModules.Scripting;
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyrightD
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using OMV = OpenMetaverse;
namespace OpenSim.Region.Physics.BulletSPlugin
{
public sealed class BSLinksetConstraints : BSLinkset
{
// private static string LogHeader = "[BULLETSIM LINKSET CONSTRAINTS]";
private static string LogHeader = "[BULLETSIM LINKSET CONSTRAINT]";
public BSLinksetConstraints(BSScene scene, BSPrimLinkable parent)
: base(scene, parent)
{
LinksetImpl = LinksetImplementation.Constraint;
}
// The object is going dynamic (physical). Do any setup necessary
// for a dynamic linkset.
// Only the state of the passed object can be modified. The rest of the linkset
// has not yet been fully constructed.
// Return 'true' if any properties updated on the passed object.
// Called at taint-time!
public override bool MakeDynamic(BSPrimLinkable child)
{
bool ret = false;
DetailLog("{0},BSLinksetConstraints.MakeDynamic,call,IsRoot={1}", child.LocalID, IsRoot(child));
if (IsRoot(child))
{
// The root is going dynamic. Rebuild the linkset so parts and mass get computed properly.
Refresh(LinksetRoot);
}
return ret;
}
// The object is going static (non-physical). Do any setup necessary for a static linkset.
// Return 'true' if any properties updated on the passed object.
// This doesn't normally happen -- OpenSim removes the objects from the physical
// world if it is a static linkset.
// Called at taint-time!
public override bool MakeStatic(BSPrimLinkable child)
{
bool ret = false;
DetailLog("{0},BSLinksetConstraint.MakeStatic,call,IsRoot={1}", child.LocalID, IsRoot(child));
child.ClearDisplacement();
if (IsRoot(child))
{
// Schedule a rebuild to verify that the root shape is set to the real shape.
Refresh(LinksetRoot);
}
return ret;
}
// When physical properties are changed the linkset needs to recalculate
// its internal properties.
// This is queued in the 'post taint' queue so the
// refresh will happen once after all the other taints are applied.
public override void Refresh(BSPrimLinkable requestor)
{
ScheduleRebuild(requestor);
base.Refresh(requestor);
}
// Routine called when rebuilding the body of some member of the linkset.
// Destroy all the constraints have have been made to root and set
// up to rebuild the constraints before the next simulation step.
// Returns 'true' of something was actually removed and would need restoring
// Called at taint-time!!
public override bool RemoveDependencies(BSPrimLinkable child)
{
bool ret = false;
DetailLog("{0},BSLinksetConstraint.RemoveDependencies,removeChildrenForRoot,rID={1},rBody={2}",
child.LocalID, LinksetRoot.LocalID, LinksetRoot.PhysBody.AddrString);
m_linksetActivityLock.AcquireWriterLock(-1);
try
{
// Just undo all the constraints for this linkset. Rebuild at the end of the step.
ret = PhysicallyUnlinkAllChildrenFromRoot(LinksetRoot);
// Cause the constraints, et al to be rebuilt before the next simulation step.
Refresh(LinksetRoot);
}
finally
{
m_linksetActivityLock.ReleaseWriterLock();
}
return ret;
}
// Called at taint-time!!
public override void UpdateProperties(UpdatedProperties whichUpdated, BSPrimLinkable pObj)
{
// Nothing to do for constraints on property updates
}
// Add a new child to the linkset.
// Called while LinkActivity is locked.
protected override void AddChildToLinkset(BSPrimLinkable child)
{
if (!HasChild(child))
{
m_children.Add(child, new BSLinkInfoConstraint(child));
DetailLog("{0},BSLinksetConstraints.AddChildToLinkset,call,child={1}", LinksetRoot.LocalID, child.LocalID);
// Cause constraints and assorted properties to be recomputed before the next simulation step.
Refresh(LinksetRoot);
}
return;
}
// ================================================================
// Remove the specified child from the linkset.
// Safe to call even if the child is not really in my linkset.
protected override void RemoveChildFromLinkset(BSPrimLinkable child, bool inTaintTime)
{
if (m_children.Remove(child))
{
BSPrimLinkable rootx = LinksetRoot; // capture the root and body as of now
BSPrimLinkable childx = child;
DetailLog("{0},BSLinksetConstraints.RemoveChildFromLinkset,call,rID={1},rBody={2},cID={3},cBody={4}",
childx.LocalID,
rootx.LocalID, rootx.PhysBody.AddrString,
childx.LocalID, childx.PhysBody.AddrString);
m_physicsScene.TaintedObject(inTaintTime, childx.LocalID, "BSLinksetConstraints.RemoveChildFromLinkset", delegate()
{
PhysicallyUnlinkAChildFromRoot(rootx, childx);
});
// See that the linkset parameters are recomputed at the end of the taint time.
Refresh(LinksetRoot);
}
else
{
// Non-fatal occurance.
// PhysicsScene.Logger.ErrorFormat("{0}: Asked to remove child from linkset that was not in linkset", LogHeader);
}
return;
}
// Create a static constraint between the two passed objects
private BSConstraint BuildConstraint(BSPrimLinkable rootPrim, BSLinkInfo li)
{
BSLinkInfoConstraint linkInfo = li as BSLinkInfoConstraint;
if (linkInfo == null)
return null;
// Zero motion for children so they don't interpolate
li.member.ZeroMotion(true);
BSConstraint constrain = null;
switch (linkInfo.constraintType)
{
case ConstraintType.FIXED_CONSTRAINT_TYPE:
case ConstraintType.D6_CONSTRAINT_TYPE:
// Relative position normalized to the root prim
// Essentually a vector pointing from center of rootPrim to center of li.member
OMV.Vector3 childRelativePosition = linkInfo.member.Position - rootPrim.Position;
// real world coordinate of midpoint between the two objects
OMV.Vector3 midPoint = rootPrim.Position + (childRelativePosition / 2);
DetailLog("{0},BSLinksetConstraint.BuildConstraint,6Dof,rBody={1},cBody={2},rLoc={3},cLoc={4},midLoc={5}",
rootPrim.LocalID, rootPrim.PhysBody, linkInfo.member.PhysBody,
rootPrim.Position, linkInfo.member.Position, midPoint);
// create a constraint that allows no freedom of movement between the two objects
// http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=4818
constrain = new BSConstraint6Dof(
m_physicsScene.World, rootPrim.PhysBody, linkInfo.member.PhysBody, midPoint, true, true);
/* NOTE: below is an attempt to build constraint with full frame computation, etc.
* Using the midpoint is easier since it lets the Bullet code manipulate the transforms
* of the objects.
* Code left for future programmers.
// ==================================================================================
// relative position normalized to the root prim
OMV.Quaternion invThisOrientation = OMV.Quaternion.Inverse(rootPrim.Orientation);
OMV.Vector3 childRelativePosition = (liConstraint.member.Position - rootPrim.Position) * invThisOrientation;
// relative rotation of the child to the parent
OMV.Quaternion childRelativeRotation = invThisOrientation * liConstraint.member.Orientation;
OMV.Quaternion inverseChildRelativeRotation = OMV.Quaternion.Inverse(childRelativeRotation);
DetailLog("{0},BSLinksetConstraint.PhysicallyLinkAChildToRoot,taint,root={1},child={2}", rootPrim.LocalID, rootPrim.LocalID, liConstraint.member.LocalID);
constrain = new BS6DofConstraint(
PhysicsScene.World, rootPrim.Body, liConstraint.member.Body,
OMV.Vector3.Zero,
OMV.Quaternion.Inverse(rootPrim.Orientation),
OMV.Vector3.Zero,
OMV.Quaternion.Inverse(liConstraint.member.Orientation),
true,
true
);
// ==================================================================================
*/
break;
case ConstraintType.D6_SPRING_CONSTRAINT_TYPE:
constrain = new BSConstraintSpring(m_physicsScene.World, rootPrim.PhysBody, linkInfo.member.PhysBody,
linkInfo.frameInAloc, linkInfo.frameInArot, linkInfo.frameInBloc, linkInfo.frameInBrot,
linkInfo.useLinearReferenceFrameA,
true /*disableCollisionsBetweenLinkedBodies*/);
DetailLog("{0},BSLinksetConstraint.BuildConstraint,spring,root={1},rBody={2},child={3},cBody={4},rLoc={5},cLoc={6}",
rootPrim.LocalID,
rootPrim.LocalID, rootPrim.PhysBody.AddrString,
linkInfo.member.LocalID, linkInfo.member.PhysBody.AddrString,
rootPrim.Position, linkInfo.member.Position);
break;
default:
break;
}
linkInfo.SetLinkParameters(constrain);
m_physicsScene.Constraints.AddConstraint(constrain);
return constrain;
}
// Create a constraint between me (root of linkset) and the passed prim (the child).
// Called at taint time!
private void PhysicallyLinkAChildToRoot(BSPrimLinkable rootPrim, BSPrimLinkable childPrim)
{
// Don't build the constraint when asked. Put it off until just before the simulation step.
Refresh(rootPrim);
}
// Remove linkage between the linkset root and a particular child
// The root and child bodies are passed in because we need to remove the constraint between
// the bodies that were present at unlink time.
// Called at taint time!
private bool PhysicallyUnlinkAChildFromRoot(BSPrimLinkable rootPrim, BSPrimLinkable childPrim)
{
bool ret = false;
DetailLog("{0},BSLinksetConstraint.PhysicallyUnlinkAChildFromRoot,taint,root={1},rBody={2},child={3},cBody={4}",
rootPrim.LocalID,
rootPrim.LocalID, rootPrim.PhysBody.AddrString,
childPrim.LocalID, childPrim.PhysBody.AddrString);
// If asked to unlink root from root, just remove all the constraints
if (rootPrim == childPrim || childPrim == LinksetRoot)
{
PhysicallyUnlinkAllChildrenFromRoot(LinksetRoot);
ret = true;
}
else
{
// Find the constraint for this link and get rid of it from the overall collection and from my list
if (m_physicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.PhysBody, childPrim.PhysBody))
{
// Make the child refresh its location
m_physicsScene.PE.PushUpdate(childPrim.PhysBody);
ret = true;
}
}
return ret;
}
// Remove linkage between myself and any possible children I might have.
// Returns 'true' of any constraints were destroyed.
// Called at taint time!
private bool PhysicallyUnlinkAllChildrenFromRoot(BSPrimLinkable rootPrim)
{
DetailLog("{0},BSLinksetConstraint.PhysicallyUnlinkAllChildren,taint", rootPrim.LocalID);
return m_physicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.PhysBody);
}
// Call each of the constraints that make up this linkset and recompute the
// various transforms and variables. Create constraints of not created yet.
// Called before the simulation step to make sure the constraint based linkset
// is all initialized.
// Called at taint time!!
private void RecomputeLinksetConstraints()
{
float linksetMass = LinksetMass;
LinksetRoot.UpdatePhysicalMassProperties(linksetMass, true);
DetailLog("{0},BSLinksetConstraint.RecomputeLinksetConstraints,set,rBody={1},linksetMass={2}",
LinksetRoot.LocalID, LinksetRoot.PhysBody.AddrString, linksetMass);
try
{
Rebuilding = true;
// There is no reason to build all this physical stuff for a non-physical linkset.
if (!LinksetRoot.IsPhysicallyActive || !HasAnyChildren)
{
DetailLog("{0},BSLinksetConstraint.RecomputeLinksetCompound,notPhysicalOrNoChildren", LinksetRoot.LocalID);
return; // Note the 'finally' clause at the botton which will get executed.
}
ForEachLinkInfo((li) =>
{
// A child in the linkset physically shows the mass of the whole linkset.
// This allows Bullet to apply enough force on the child to move the whole linkset.
// (Also do the mass stuff before recomputing the constraint so mass is not zero.)
li.member.UpdatePhysicalMassProperties(linksetMass, true);
BSConstraint constrain;
if (!m_physicsScene.Constraints.TryGetConstraint(LinksetRoot.PhysBody, li.member.PhysBody, out constrain))
{
// If constraint doesn't exist yet, create it.
constrain = BuildConstraint(LinksetRoot, li);
}
li.SetLinkParameters(constrain);
constrain.RecomputeConstraintVariables(linksetMass);
// PhysicsScene.PE.DumpConstraint(PhysicsScene.World, constrain.Constraint); // DEBUG DEBUG
return false; // 'false' says to keep processing other members
});
}
finally
{
Rebuilding = false;
}
}
private void ScheduleRebuild(BSPrimLinkable requestor)
{
DetailLog("{0},BSLinksetConstraint.ScheduleRebuild,,rebuilding={1},hasChildren={2},actuallyScheduling={3}",
requestor.LocalID, Rebuilding, HasAnyChildren, (!Rebuilding && HasAnyChildren));
// When rebuilding, it is possible to set properties that would normally require a rebuild.
// If already rebuilding, don't request another rebuild.
// If a linkset with just a root prim (simple non-linked prim) don't bother rebuilding.
if (!Rebuilding && HasAnyChildren)
{
// Queue to happen after all the other taint processing
m_physicsScene.PostTaintObject("BSLinksetContraints.Refresh", requestor.LocalID, delegate()
{
if (HasAnyChildren)
{
// Constraints that have not been changed are not rebuild but make sure
// the constraint of the requestor is rebuilt.
PhysicallyUnlinkAChildFromRoot(LinksetRoot, requestor);
// Rebuild the linkset and all its constraints.
RecomputeLinksetConstraints();
}
});
}
}
public class BSLinkInfoConstraint : BSLinkInfo
{
public OMV.Vector3 angularLimitHigh;
public OMV.Vector3 angularLimitLow;
public float cfm;
public BSConstraint constraint;
public ConstraintType constraintType;
public bool enableTransMotor;
public float erp;
//
public OMV.Vector3 frameInAloc;
public OMV.Quaternion frameInArot;
public OMV.Vector3 frameInBloc;
public OMV.Quaternion frameInBrot;
public OMV.Vector3 linearLimitHigh;
public OMV.Vector3 linearLimitLow;
public float solverIterations;
public OMV.Vector3 springAngularEquilibriumPoint;
// Spring
public bool[] springAxisEnable;
public float[] springDamping;
public OMV.Vector3 springLinearEquilibriumPoint;
public float[] springStiffness;
public float transMotorMaxForce;
public float transMotorMaxVel;
public bool useFrameOffset;
public bool useLinearReferenceFrameA;
public BSLinkInfoConstraint(BSPrimLinkable pMember)
: base(pMember)
{
constraint = null;
ResetLink();
member.PhysScene.DetailLog("{0},BSLinkInfoConstraint.creation", member.LocalID);
}
// Set all the parameters for this constraint to a fixed, non-movable constraint.
public override void ResetLink()
{
// constraintType = ConstraintType.D6_CONSTRAINT_TYPE;
constraintType = ConstraintType.FIXED_CONSTRAINT_TYPE;
linearLimitLow = OMV.Vector3.Zero;
linearLimitHigh = OMV.Vector3.Zero;
angularLimitLow = OMV.Vector3.Zero;
angularLimitHigh = OMV.Vector3.Zero;
useFrameOffset = BSParam.LinkConstraintUseFrameOffset;
enableTransMotor = BSParam.LinkConstraintEnableTransMotor;
transMotorMaxVel = BSParam.LinkConstraintTransMotorMaxVel;
transMotorMaxForce = BSParam.LinkConstraintTransMotorMaxForce;
cfm = BSParam.LinkConstraintCFM;
erp = BSParam.LinkConstraintERP;
solverIterations = BSParam.LinkConstraintSolverIterations;
frameInAloc = OMV.Vector3.Zero;
frameInArot = OMV.Quaternion.Identity;
frameInBloc = OMV.Vector3.Zero;
frameInBrot = OMV.Quaternion.Identity;
useLinearReferenceFrameA = true;
springAxisEnable = new bool[6];
springDamping = new float[6];
springStiffness = new float[6];
for (int ii = 0; ii < springAxisEnable.Length; ii++)
{
springAxisEnable[ii] = false;
springDamping[ii] = BSAPITemplate.SPRING_NOT_SPECIFIED;
springStiffness[ii] = BSAPITemplate.SPRING_NOT_SPECIFIED;
}
springLinearEquilibriumPoint = OMV.Vector3.Zero;
springAngularEquilibriumPoint = OMV.Vector3.Zero;
member.PhysScene.DetailLog("{0},BSLinkInfoConstraint.ResetLink", member.LocalID);
}
// Given a constraint, apply the current constraint parameters to same.
public override void SetLinkParameters(BSConstraint constrain)
{
member.PhysScene.DetailLog("{0},BSLinkInfoConstraint.SetLinkParameters,type={1}", member.LocalID, constraintType);
switch (constraintType)
{
case ConstraintType.FIXED_CONSTRAINT_TYPE:
case ConstraintType.D6_CONSTRAINT_TYPE:
BSConstraint6Dof constrain6dof = constrain as BSConstraint6Dof;
if (constrain6dof != null)
{
// NOTE: D6_SPRING_CONSTRAINT_TYPE should be updated if you change any of this code.
// zero linear and angular limits makes the objects unable to move in relation to each other
constrain6dof.SetLinearLimits(linearLimitLow, linearLimitHigh);
constrain6dof.SetAngularLimits(angularLimitLow, angularLimitHigh);
// tweek the constraint to increase stability
constrain6dof.UseFrameOffset(useFrameOffset);
constrain6dof.TranslationalLimitMotor(enableTransMotor, transMotorMaxVel, transMotorMaxForce);
constrain6dof.SetCFMAndERP(cfm, erp);
if (solverIterations != 0f)
{
constrain6dof.SetSolverIterations(solverIterations);
}
}
break;
case ConstraintType.D6_SPRING_CONSTRAINT_TYPE:
BSConstraintSpring constrainSpring = constrain as BSConstraintSpring;
if (constrainSpring != null)
{
// zero linear and angular limits makes the objects unable to move in relation to each other
constrainSpring.SetLinearLimits(linearLimitLow, linearLimitHigh);
constrainSpring.SetAngularLimits(angularLimitLow, angularLimitHigh);
// tweek the constraint to increase stability
constrainSpring.UseFrameOffset(useFrameOffset);
constrainSpring.TranslationalLimitMotor(enableTransMotor, transMotorMaxVel, transMotorMaxForce);
constrainSpring.SetCFMAndERP(cfm, erp);
if (solverIterations != 0f)
{
constrainSpring.SetSolverIterations(solverIterations);
}
for (int ii = 0; ii < springAxisEnable.Length; ii++)
{
constrainSpring.SetAxisEnable(ii, springAxisEnable[ii]);
if (springDamping[ii] != BSAPITemplate.SPRING_NOT_SPECIFIED)
constrainSpring.SetDamping(ii, springDamping[ii]);
if (springStiffness[ii] != BSAPITemplate.SPRING_NOT_SPECIFIED)
constrainSpring.SetStiffness(ii, springStiffness[ii]);
}
constrainSpring.CalculateTransforms();
if (springLinearEquilibriumPoint != OMV.Vector3.Zero)
constrainSpring.SetEquilibriumPoint(springLinearEquilibriumPoint, springAngularEquilibriumPoint);
else
constrainSpring.SetEquilibriumPoint(BSAPITemplate.SPRING_NOT_SPECIFIED, BSAPITemplate.SPRING_NOT_SPECIFIED);
}
break;
default:
break;
}
}
// Return 'true' if the property updates from the physics engine should be reported
// to the simulator.
// If the constraint is fixed, we don't need to report as the simulator and viewer will
// report the right things.
public override bool ShouldUpdateChildProperties()
{
bool ret = true;
if (constraintType == ConstraintType.FIXED_CONSTRAINT_TYPE)
ret = false;
return ret;
}
}
#region Extension
public override object Extension(string pFunct, params object[] pParams)
{
object ret = null;
switch (pFunct)
{
// pParams = [ BSPhysObject root, BSPhysObject child, integer linkType ]
case ExtendedPhysics.PhysFunctChangeLinkType:
if (pParams.Length > 2)
{
int requestedType = (int)pParams[2];
DetailLog("{0},BSLinksetConstraint.ChangeLinkType,requestedType={1}", LinksetRoot.LocalID, requestedType);
if (requestedType == (int)ConstraintType.FIXED_CONSTRAINT_TYPE
|| requestedType == (int)ConstraintType.D6_CONSTRAINT_TYPE
|| requestedType == (int)ConstraintType.D6_SPRING_CONSTRAINT_TYPE
|| requestedType == (int)ConstraintType.HINGE_CONSTRAINT_TYPE
|| requestedType == (int)ConstraintType.CONETWIST_CONSTRAINT_TYPE
|| requestedType == (int)ConstraintType.SLIDER_CONSTRAINT_TYPE)
{
BSPrimLinkable child = pParams[1] as BSPrimLinkable;
if (child != null)
{
DetailLog("{0},BSLinksetConstraint.ChangeLinkType,rootID={1},childID={2},type={3}",
LinksetRoot.LocalID, LinksetRoot.LocalID, child.LocalID, requestedType);
m_physicsScene.TaintedObject(child.LocalID, "BSLinksetConstraint.PhysFunctChangeLinkType", delegate()
{
// Pick up all the constraints currently created.
RemoveDependencies(child);
BSLinkInfo linkInfo = null;
if (TryGetLinkInfo(child, out linkInfo))
{
BSLinkInfoConstraint linkInfoC = linkInfo as BSLinkInfoConstraint;
if (linkInfoC != null)
{
linkInfoC.constraintType = (ConstraintType)requestedType;
ret = (object)true;
DetailLog("{0},BSLinksetConstraint.ChangeLinkType,link={1},type={2}",
linkInfo.member.LocalID, linkInfo.member.LocalID, linkInfoC.constraintType);
}
else
{
DetailLog("{0},BSLinksetConstraint.ChangeLinkType,linkInfoNotConstraint,childID={1}", LinksetRoot.LocalID, child.LocalID);
}
}
else
{
DetailLog("{0},BSLinksetConstraint.ChangeLinkType,noLinkInfoForChild,childID={1}", LinksetRoot.LocalID, child.LocalID);
}
// Cause the whole linkset to be rebuilt in post-taint time.
Refresh(child);
});
}
else
{
DetailLog("{0},BSLinksetConstraint.SetLinkType,childNotBSPrimLinkable", LinksetRoot.LocalID);
}
}
else
{
DetailLog("{0},BSLinksetConstraint.SetLinkType,illegalRequestedType,reqested={1},spring={2}",
LinksetRoot.LocalID, requestedType, ((int)ConstraintType.D6_SPRING_CONSTRAINT_TYPE));
}
}
break;
// pParams = [ BSPhysObject root, BSPhysObject child ]
case ExtendedPhysics.PhysFunctGetLinkType:
if (pParams.Length > 0)
{
BSPrimLinkable child = pParams[1] as BSPrimLinkable;
if (child != null)
{
BSLinkInfo linkInfo = null;
if (TryGetLinkInfo(child, out linkInfo))
{
BSLinkInfoConstraint linkInfoC = linkInfo as BSLinkInfoConstraint;
if (linkInfoC != null)
{
ret = (object)(int)linkInfoC.constraintType;
DetailLog("{0},BSLinksetConstraint.GetLinkType,link={1},type={2}",
linkInfo.member.LocalID, linkInfo.member.LocalID, linkInfoC.constraintType);
}
}
}
}
break;
// pParams = [ BSPhysObject root, BSPhysObject child, int op, object opParams, int op, object opParams, ... ]
case ExtendedPhysics.PhysFunctChangeLinkParams:
// There should be two parameters: the childActor and a list of parameters to set
if (pParams.Length > 2)
{
BSPrimLinkable child = pParams[1] as BSPrimLinkable;
BSLinkInfo baseLinkInfo = null;
if (TryGetLinkInfo(child, out baseLinkInfo))
{
BSLinkInfoConstraint linkInfo = baseLinkInfo as BSLinkInfoConstraint;
if (linkInfo != null)
{
int valueInt;
float valueFloat;
bool valueBool;
OMV.Vector3 valueVector;
OMV.Vector3 valueVector2;
OMV.Quaternion valueQuaternion;
int axisLow, axisHigh;
int opIndex = 2;
while (opIndex < pParams.Length)
{
int thisOp = 0;
string errMsg = "";
try
{
thisOp = (int)pParams[opIndex];
DetailLog("{0},BSLinksetConstraint.ChangeLinkParams2,op={1},val={2}",
linkInfo.member.LocalID, thisOp, pParams[opIndex + 1]);
switch (thisOp)
{
case ExtendedPhysics.PHYS_PARAM_LINK_TYPE:
valueInt = (int)pParams[opIndex + 1];
ConstraintType valueType = (ConstraintType)valueInt;
if (valueType == ConstraintType.FIXED_CONSTRAINT_TYPE
|| valueType == ConstraintType.D6_CONSTRAINT_TYPE
|| valueType == ConstraintType.D6_SPRING_CONSTRAINT_TYPE
|| valueType == ConstraintType.HINGE_CONSTRAINT_TYPE
|| valueType == ConstraintType.CONETWIST_CONSTRAINT_TYPE
|| valueType == ConstraintType.SLIDER_CONSTRAINT_TYPE)
{
linkInfo.constraintType = valueType;
}
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_FRAMEINA_LOC:
errMsg = "PHYS_PARAM_FRAMEINA_LOC takes one parameter of type vector";
valueVector = (OMV.Vector3)pParams[opIndex + 1];
linkInfo.frameInAloc = valueVector;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_FRAMEINA_ROT:
errMsg = "PHYS_PARAM_FRAMEINA_ROT takes one parameter of type rotation";
valueQuaternion = (OMV.Quaternion)pParams[opIndex + 1];
linkInfo.frameInArot = valueQuaternion;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_FRAMEINB_LOC:
errMsg = "PHYS_PARAM_FRAMEINB_LOC takes one parameter of type vector";
valueVector = (OMV.Vector3)pParams[opIndex + 1];
linkInfo.frameInBloc = valueVector;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_FRAMEINB_ROT:
errMsg = "PHYS_PARAM_FRAMEINB_ROT takes one parameter of type rotation";
valueQuaternion = (OMV.Quaternion)pParams[opIndex + 1];
linkInfo.frameInBrot = valueQuaternion;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_LINEAR_LIMIT_LOW:
errMsg = "PHYS_PARAM_LINEAR_LIMIT_LOW takes one parameter of type vector";
valueVector = (OMV.Vector3)pParams[opIndex + 1];
linkInfo.linearLimitLow = valueVector;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_LINEAR_LIMIT_HIGH:
errMsg = "PHYS_PARAM_LINEAR_LIMIT_HIGH takes one parameter of type vector";
valueVector = (OMV.Vector3)pParams[opIndex + 1];
linkInfo.linearLimitHigh = valueVector;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_ANGULAR_LIMIT_LOW:
errMsg = "PHYS_PARAM_ANGULAR_LIMIT_LOW takes one parameter of type vector";
valueVector = (OMV.Vector3)pParams[opIndex + 1];
linkInfo.angularLimitLow = valueVector;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_ANGULAR_LIMIT_HIGH:
errMsg = "PHYS_PARAM_ANGULAR_LIMIT_HIGH takes one parameter of type vector";
valueVector = (OMV.Vector3)pParams[opIndex + 1];
linkInfo.angularLimitHigh = valueVector;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_USE_FRAME_OFFSET:
errMsg = "PHYS_PARAM_USE_FRAME_OFFSET takes one parameter of type integer (bool)";
valueBool = ((int)pParams[opIndex + 1]) != 0;
linkInfo.useFrameOffset = valueBool;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_ENABLE_TRANSMOTOR:
errMsg = "PHYS_PARAM_ENABLE_TRANSMOTOR takes one parameter of type integer (bool)";
valueBool = ((int)pParams[opIndex + 1]) != 0;
linkInfo.enableTransMotor = valueBool;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_TRANSMOTOR_MAXVEL:
errMsg = "PHYS_PARAM_TRANSMOTOR_MAXVEL takes one parameter of type float";
valueFloat = (float)pParams[opIndex + 1];
linkInfo.transMotorMaxVel = valueFloat;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_TRANSMOTOR_MAXFORCE:
errMsg = "PHYS_PARAM_TRANSMOTOR_MAXFORCE takes one parameter of type float";
valueFloat = (float)pParams[opIndex + 1];
linkInfo.transMotorMaxForce = valueFloat;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_CFM:
errMsg = "PHYS_PARAM_CFM takes one parameter of type float";
valueFloat = (float)pParams[opIndex + 1];
linkInfo.cfm = valueFloat;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_ERP:
errMsg = "PHYS_PARAM_ERP takes one parameter of type float";
valueFloat = (float)pParams[opIndex + 1];
linkInfo.erp = valueFloat;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_SOLVER_ITERATIONS:
errMsg = "PHYS_PARAM_SOLVER_ITERATIONS takes one parameter of type float";
valueFloat = (float)pParams[opIndex + 1];
linkInfo.solverIterations = valueFloat;
opIndex += 2;
break;
case ExtendedPhysics.PHYS_PARAM_SPRING_AXIS_ENABLE:
errMsg = "PHYS_PARAM_SPRING_AXIS_ENABLE takes two parameters of types integer and integer (bool)";
valueInt = (int)pParams[opIndex + 1];
valueBool = ((int)pParams[opIndex + 2]) != 0;
GetAxisRange(valueInt, out axisLow, out axisHigh);
for (int ii = axisLow; ii <= axisHigh; ii++)
linkInfo.springAxisEnable[ii] = valueBool;
opIndex += 3;
break;
case ExtendedPhysics.PHYS_PARAM_SPRING_DAMPING:
errMsg = "PHYS_PARAM_SPRING_DAMPING takes two parameters of types integer and float";
valueInt = (int)pParams[opIndex + 1];
valueFloat = (float)pParams[opIndex + 2];
GetAxisRange(valueInt, out axisLow, out axisHigh);
for (int ii = axisLow; ii <= axisHigh; ii++)
linkInfo.springDamping[ii] = valueFloat;
opIndex += 3;
break;
case ExtendedPhysics.PHYS_PARAM_SPRING_STIFFNESS:
errMsg = "PHYS_PARAM_SPRING_STIFFNESS takes two parameters of types integer and float";
valueInt = (int)pParams[opIndex + 1];
valueFloat = (float)pParams[opIndex + 2];
GetAxisRange(valueInt, out axisLow, out axisHigh);
for (int ii = axisLow; ii <= axisHigh; ii++)
linkInfo.springStiffness[ii] = valueFloat;
opIndex += 3;
break;
case ExtendedPhysics.PHYS_PARAM_SPRING_EQUILIBRIUM_POINT:
errMsg = "PHYS_PARAM_SPRING_EQUILIBRIUM_POINT takes two parameters of type vector";
valueVector = (OMV.Vector3)pParams[opIndex + 1];
valueVector2 = (OMV.Vector3)pParams[opIndex + 2];
linkInfo.springLinearEquilibriumPoint = valueVector;
linkInfo.springAngularEquilibriumPoint = valueVector2;
opIndex += 3;
break;
case ExtendedPhysics.PHYS_PARAM_USE_LINEAR_FRAMEA:
errMsg = "PHYS_PARAM_USE_LINEAR_FRAMEA takes one parameter of type integer (bool)";
valueBool = ((int)pParams[opIndex + 1]) != 0;
linkInfo.useLinearReferenceFrameA = valueBool;
opIndex += 2;
break;
default:
break;
}
}
catch (InvalidCastException e)
{
m_physicsScene.Logger.WarnFormat("{0} value of wrong type in physSetLinksetParams: {1}, err={2}",
LogHeader, errMsg, e);
}
catch (Exception e)
{
m_physicsScene.Logger.WarnFormat("{0} bad parameters in physSetLinksetParams: {1}", LogHeader, e);
}
}
}
// Something changed so a rebuild is in order
Refresh(child);
}
}
break;
default:
ret = base.Extension(pFunct, pParams);
break;
}
return ret;
}
// Bullet constraints keep some limit parameters for each linear and angular axis.
// Setting same is easier if there is an easy way to see all or types.
// This routine returns the array limits for the set of axis.
private void GetAxisRange(int rangeSpec, out int low, out int high)
{
switch (rangeSpec)
{
case ExtendedPhysics.PHYS_AXIS_LINEAR_ALL:
low = 0;
high = 2;
break;
case ExtendedPhysics.PHYS_AXIS_ANGULAR_ALL:
low = 3;
high = 5;
break;
case ExtendedPhysics.PHYS_AXIS_ALL:
low = 0;
high = 5;
break;
default:
low = high = rangeSpec;
break;
}
return;
}
#endregion Extension
}
}
| |
#region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
using Grpc.Core.Internal;
using Grpc.Core.Utils;
using NUnit.Framework;
namespace Grpc.Core.Tests
{
public class MetadataTest
{
[Test]
public void AsciiEntry()
{
var entry = new Metadata.Entry("ABC", "XYZ");
Assert.IsFalse(entry.IsBinary);
Assert.AreEqual("abc", entry.Key); // key is in lowercase.
Assert.AreEqual("XYZ", entry.Value);
CollectionAssert.AreEqual(new[] { (byte)'X', (byte)'Y', (byte)'Z' }, entry.ValueBytes);
Assert.Throws(typeof(ArgumentException), () => new Metadata.Entry("abc-bin", "xyz"));
Assert.AreEqual("[Entry: key=abc, value=XYZ]", entry.ToString());
}
[Test]
public void BinaryEntry()
{
var bytes = new byte[] { 1, 2, 3 };
var entry = new Metadata.Entry("ABC-BIN", bytes);
Assert.IsTrue(entry.IsBinary);
Assert.AreEqual("abc-bin", entry.Key); // key is in lowercase.
Assert.Throws(typeof(InvalidOperationException), () => { var v = entry.Value; });
CollectionAssert.AreEqual(bytes, entry.ValueBytes);
Assert.Throws(typeof(ArgumentException), () => new Metadata.Entry("abc", bytes));
Assert.AreEqual("[Entry: key=abc-bin, valueBytes=System.Byte[]]", entry.ToString());
}
[Test]
public void AsciiEntry_KeyValidity()
{
new Metadata.Entry("ABC", "XYZ");
new Metadata.Entry("0123456789abc", "XYZ");
new Metadata.Entry("-abc", "XYZ");
new Metadata.Entry("a_bc_", "XYZ");
new Metadata.Entry("abc.xyz", "XYZ");
new Metadata.Entry("abc.xyz-bin", new byte[] {1, 2, 3});
Assert.Throws(typeof(ArgumentException), () => new Metadata.Entry("abc[", "xyz"));
Assert.Throws(typeof(ArgumentException), () => new Metadata.Entry("abc/", "xyz"));
}
[Test]
public void KeysAreNormalized_UppercaseKey()
{
var uppercaseKey = "ABC";
var entry = new Metadata.Entry(uppercaseKey, "XYZ");
Assert.AreEqual("abc", entry.Key);
}
[Test]
public void KeysAreNormalized_LowercaseKey()
{
var lowercaseKey = "abc";
var entry = new Metadata.Entry(lowercaseKey, "XYZ");
// no allocation if key already lowercase
Assert.AreSame(lowercaseKey, entry.Key);
}
[Test]
public void Entry_ConstructionPreconditions()
{
Assert.Throws(typeof(ArgumentNullException), () => new Metadata.Entry(null, "xyz"));
Assert.Throws(typeof(ArgumentNullException), () => new Metadata.Entry("abc", (string)null));
Assert.Throws(typeof(ArgumentNullException), () => new Metadata.Entry("abc-bin", (byte[])null));
}
[Test]
public void Entry_Immutable()
{
var origBytes = new byte[] { 1, 2, 3 };
var bytes = new byte[] { 1, 2, 3 };
var entry = new Metadata.Entry("ABC-BIN", bytes);
bytes[0] = 255; // changing the array passed to constructor should have any effect.
CollectionAssert.AreEqual(origBytes, entry.ValueBytes);
entry.ValueBytes[0] = 255;
CollectionAssert.AreEqual(origBytes, entry.ValueBytes);
}
[Test]
public void Entry_CreateUnsafe_Ascii()
{
var bytes = new byte[] { (byte)'X', (byte)'y' };
var entry = Metadata.Entry.CreateUnsafe("abc", bytes);
Assert.IsFalse(entry.IsBinary);
Assert.AreEqual("abc", entry.Key);
Assert.AreEqual("Xy", entry.Value);
CollectionAssert.AreEqual(bytes, entry.ValueBytes);
}
[Test]
public void Entry_CreateUnsafe_Binary()
{
var bytes = new byte[] { 1, 2, 3 };
var entry = Metadata.Entry.CreateUnsafe("abc-bin", bytes);
Assert.IsTrue(entry.IsBinary);
Assert.AreEqual("abc-bin", entry.Key);
Assert.Throws(typeof(InvalidOperationException), () => { var v = entry.Value; });
CollectionAssert.AreEqual(bytes, entry.ValueBytes);
}
[Test]
public void IndexOf()
{
var metadata = CreateMetadata();
Assert.AreEqual(0, metadata.IndexOf(metadata[0]));
Assert.AreEqual(1, metadata.IndexOf(metadata[1]));
}
[Test]
public void Insert()
{
var metadata = CreateMetadata();
metadata.Insert(0, new Metadata.Entry("new-key", "new-value"));
Assert.AreEqual(3, metadata.Count);
Assert.AreEqual("new-key", metadata[0].Key);
Assert.AreEqual("abc", metadata[1].Key);
}
[Test]
public void RemoveAt()
{
var metadata = CreateMetadata();
metadata.RemoveAt(0);
Assert.AreEqual(1, metadata.Count);
Assert.AreEqual("xyz", metadata[0].Key);
}
[Test]
public void Remove()
{
var metadata = CreateMetadata();
metadata.Remove(metadata[0]);
Assert.AreEqual(1, metadata.Count);
Assert.AreEqual("xyz", metadata[0].Key);
}
[Test]
public void Indexer_Set()
{
var metadata = CreateMetadata();
var entry = new Metadata.Entry("new-key", "new-value");
metadata[1] = entry;
Assert.AreEqual(entry, metadata[1]);
}
[Test]
public void Clear()
{
var metadata = CreateMetadata();
metadata.Clear();
Assert.AreEqual(0, metadata.Count);
}
[Test]
public void Contains()
{
var metadata = CreateMetadata();
Assert.IsTrue(metadata.Contains(metadata[0]));
Assert.IsFalse(metadata.Contains(new Metadata.Entry("new-key", "new-value")));
}
[Test]
public void CopyTo()
{
var metadata = CreateMetadata();
var array = new Metadata.Entry[metadata.Count + 1];
metadata.CopyTo(array, 1);
Assert.AreEqual(default(Metadata.Entry), array[0]);
Assert.AreEqual(metadata[0], array[1]);
}
[Test]
public void IEnumerableGetEnumerator()
{
var metadata = CreateMetadata();
var enumerator = (metadata as System.Collections.IEnumerable).GetEnumerator();
int i = 0;
while (enumerator.MoveNext())
{
Assert.AreEqual(metadata[i], enumerator.Current);
i++;
}
}
[Test]
public void FreezeMakesReadOnly()
{
var entry = new Metadata.Entry("new-key", "new-value");
var metadata = CreateMetadata().Freeze();
Assert.IsTrue(metadata.IsReadOnly);
Assert.Throws<InvalidOperationException>(() => metadata.Insert(0, entry));
Assert.Throws<InvalidOperationException>(() => metadata.RemoveAt(0));
Assert.Throws<InvalidOperationException>(() => metadata[0] = entry);
Assert.Throws<InvalidOperationException>(() => metadata.Add(entry));
Assert.Throws<InvalidOperationException>(() => metadata.Add("new-key", "new-value"));
Assert.Throws<InvalidOperationException>(() => metadata.Add("new-key-bin", new byte[] { 0xaa }));
Assert.Throws<InvalidOperationException>(() => metadata.Clear());
Assert.Throws<InvalidOperationException>(() => metadata.Remove(metadata[0]));
}
private Metadata CreateMetadata()
{
return new Metadata
{
{ "abc", "abc-value" },
{ "xyz", "xyz-value" },
};
}
}
}
| |
/********************************************************************++
* Copyright (c) Microsoft Corporation. All rights reserved.
* --********************************************************************/
namespace System.Management.Automation.Runspaces
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using Dbg = System.Management.Automation.Diagnostics;
using System.Management.Automation.Internal;
#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings
/// <summary>
/// This class has common base implementation for Pipeline class.
/// LocalPipeline and RemotePipeline classes derives from it.
/// </summary>
internal abstract class PipelineBase : Pipeline
{
#region constructors
/// <summary>
/// Create a pipeline initialized with a command string
/// </summary>
/// <param name="runspace">The associated Runspace/>.</param>
/// <param name="command">command string</param>
/// <param name="addToHistory">if true, add pipeline to history</param>
/// <param name="isNested">True for nested pipeline</param>
/// <exception cref="ArgumentNullException">
/// Command is null and add to history is true
/// </exception>
protected PipelineBase(Runspace runspace, string command, bool addToHistory, bool isNested)
: base(runspace)
{
Initialize(runspace, command, addToHistory, isNested);
//Initialize streams
InputStream = new ObjectStream();
OutputStream = new ObjectStream();
ErrorStream = new ObjectStream();
}
/// <summary>
/// Create a Pipeline with an existing command string.
/// Caller should validate all the parameters.
/// </summary>
/// <param name="runspace">
/// The LocalRunspace to associate with this pipeline.
/// </param>
/// <param name="command">
/// The command to invoke.
/// </param>
/// <param name="addToHistory">
/// If true, add the command to history.
/// </param>
/// <param name="isNested">
/// If true, mark this pipeline as a nested pipeline.
/// </param>
/// <param name="inputStream">
/// Stream to use for reading input objects.
/// </param>
/// <param name="errorStream">
/// Stream to use for writing error objects.
/// </param>
/// <param name="outputStream">
/// Stream to use for writing output objects.
/// </param>
/// <param name="infoBuffers">
/// Buffers used to write progress, verbose, debug, warning, information
/// information of an invocation.
/// </param>
/// <exception cref="ArgumentNullException">
/// Command is null and add to history is true
/// </exception>
/// <exception cref="ArgumentNullException">
/// 1. InformationalBuffers is null
/// </exception>
protected PipelineBase(Runspace runspace,
CommandCollection command,
bool addToHistory,
bool isNested,
ObjectStreamBase inputStream,
ObjectStreamBase outputStream,
ObjectStreamBase errorStream,
PSInformationalBuffers infoBuffers)
: base(runspace, command)
{
Dbg.Assert(null != inputStream, "Caller Should validate inputstream parameter");
Dbg.Assert(null != outputStream, "Caller Should validate outputStream parameter");
Dbg.Assert(null != errorStream, "Caller Should validate errorStream parameter");
Dbg.Assert(null != infoBuffers, "Caller Should validate informationalBuffers parameter");
Dbg.Assert(null != command, "Command cannot be null");
// Since we are constructing this pipeline using a commandcollection we dont need
// to add cmd to CommandCollection again (Initialize does this).. because of this
// I am handling history here..
Initialize(runspace, null, false, isNested);
if (true == addToHistory)
{
// get command text for history..
string cmdText = command.GetCommandStringForHistory();
HistoryString = cmdText;
AddToHistory = addToHistory;
}
//Initialize streams
InputStream = inputStream;
OutputStream = outputStream;
ErrorStream = errorStream;
InformationalBuffers = infoBuffers;
}
/// <summary>
/// Copy constructor to support cloning
/// </summary>
/// <param name="pipeline">The source pipeline</param>
/// <remarks>
/// The copy constructor's intent is to support the scenario
/// where a host needs to run the same set of commands multiple
/// times. This is accomplished via creating a master pipeline
/// then cloning it and executing the cloned copy.
/// </remarks>
protected PipelineBase(PipelineBase pipeline)
: this(pipeline.Runspace, null, false, pipeline.IsNested)
{
// NTRAID#Windows Out Of Band Releases-915851-2005/09/13
if (null == pipeline)
{
throw PSTraceSource.NewArgumentNullException("pipeline");
}
if (pipeline._disposed)
{
throw PSTraceSource.NewObjectDisposedException("pipeline");
}
AddToHistory = pipeline.AddToHistory;
HistoryString = pipeline.HistoryString;
foreach (Command command in pipeline.Commands)
{
Command clone = command.Clone();
// Attach the cloned Command to this pipeline.
Commands.Add(clone);
}
}
#endregion constructors
#region properties
private Runspace _runspace;
/// <summary>
/// Access the runspace this pipeline is created on.
/// </summary>
public override Runspace Runspace
{
get
{
return _runspace;
}
}
/// <summary>
/// This internal method doesn't do the _disposed check.
/// </summary>
/// <returns></returns>
internal Runspace GetRunspace()
{
return _runspace;
}
private bool _isNested;
/// <summary>
/// Is this pipeline nested
/// </summary>
public override bool IsNested
{
get
{
return _isNested;
}
}
/// <summary>
/// Is this a pulse pipeline (created by the EventManager)
/// </summary>
internal bool IsPulsePipeline { get; set; }
private PipelineStateInfo _pipelineStateInfo = new PipelineStateInfo(PipelineState.NotStarted);
/// <summary>
/// Info about current state of the pipeline.
/// </summary>
/// <remarks>
/// This value indicates the state of the pipeline after the change.
/// </remarks>
public override PipelineStateInfo PipelineStateInfo
{
get
{
lock (SyncRoot)
{
//Note:We do not return internal state.
return _pipelineStateInfo.Clone();
}
}
}
// 913921-2005/07/08 ObjectWriter can be retrieved on a closed stream
/// <summary>
/// Access the input writer for this pipeline.
/// </summary>
public override PipelineWriter Input
{
get
{
return InputStream.ObjectWriter;
}
}
/// <summary>
/// Access the output reader for this pipeline.
/// </summary>
public override PipelineReader<PSObject> Output
{
get
{
return OutputStream.PSObjectReader;
}
}
/// <summary>
/// Access the error output reader for this pipeline.
/// </summary>
/// <remarks>
/// This is the non-terminating error stream from the command.
/// In this release, the objects read from this PipelineReader
/// are PSObjects wrapping ErrorRecords.
/// </remarks>
public override PipelineReader<object> Error
{
get
{
return _errorStream.ObjectReader;
}
}
/// <summary>
/// Is this pipeline a child pipeline?
///
/// IsChild flag makes it possible for the pipeline to differentiate between
/// a true v1 nested pipeline and the cmdlets calling cmdlets case. See bug
/// 211462.
/// </summary>
internal override bool IsChild { get; set; }
#endregion properties
#region stop
/// <summary>
/// Synchronous call to stop the running pipeline.
/// </summary>
public override void Stop()
{
CoreStop(true);
}
/// <summary>
/// Asynchronous call to stop the running pipeline.
/// </summary>
public override void StopAsync()
{
CoreStop(false);
}
/// <summary>
/// Stop the running pipeline.
/// </summary>
/// <param name="syncCall">If true pipeline is stoped synchronously
/// else asynchronously.</param>
private void CoreStop(bool syncCall)
{
//Is pipeline already in stopping state.
bool alreadyStopping = false;
lock (SyncRoot)
{
switch (PipelineState)
{
case PipelineState.NotStarted:
SetPipelineState(PipelineState.Stopping);
SetPipelineState(PipelineState.Stopped);
break;
//If pipeline execution has failed or completed or
//stoped, return silently.
case PipelineState.Stopped:
case PipelineState.Completed:
case PipelineState.Failed:
return;
//If pipeline is in Stopping state, ignore the second
//stop.
case PipelineState.Stopping:
alreadyStopping = true;
break;
case PipelineState.Running:
SetPipelineState(PipelineState.Stopping);
break;
}
}
//If pipeline is already in stopping state. Wait for pipeline
//to finish. We do need to raise any events here as no
//change of state has occurred.
if (alreadyStopping)
{
if (syncCall)
{
PipelineFinishedEvent.WaitOne();
}
return;
}
//Raise the event outside the lock
RaisePipelineStateEvents();
//A pipeline can be stoped before it is started. See NotStarted
//case in above switch statement. This is done to allow stoping a pipeline
//in another thread before it has been started.
lock (SyncRoot)
{
if (PipelineState == PipelineState.Stopped)
{
//Note:if we have reached here, Stopped state was set
//in PipelineState.NotStarted case above. Only other
//way Stopped can be set when this method calls
//StopHelper below
return;
}
}
//Start stop operation in derived class
ImplementStop(syncCall);
}
/// <summary>
/// Stop execution of pipeline
/// </summary>
/// <param name="syncCall">If false, call is asynchronous</param>
protected abstract void ImplementStop(bool syncCall);
#endregion stop
#region invoke
/// <summary>
/// Invoke the pipeline, synchronously, returning the results as an
/// array of objects.
/// </summary>
/// <param name="input">an array of input objects to pass to the pipeline.
/// Array may be empty but may not be null</param>
/// <returns>An array of zero or more result objects</returns>
/// <remarks>Caller of synchronous exectute should not close
/// input objectWriter. Synchronous invoke will always close the input
/// objectWriter.
///
/// On Synchronous Invoke if output is throttled and no one is reading from
/// output pipe, Execution will block after buffer is full.
/// </remarks>
public override Collection<PSObject> Invoke(IEnumerable input)
{
// NTRAID#Windows Out Of Band Releases-915851-2005/09/13
if (_disposed)
{
throw PSTraceSource.NewObjectDisposedException("pipeline");
}
CoreInvoke(input, true);
//Wait for pipeline to finish execution
PipelineFinishedEvent.WaitOne();
if (SyncInvokeCall)
{
//Raise the pipeline completion events. These events are set in
//pipeline execution thread. However for Synchornous execution
//we raise the event in the main thread.
RaisePipelineStateEvents();
}
if (PipelineStateInfo.State == PipelineState.Stopped)
{
return new Collection<PSObject>();
}
else if (PipelineStateInfo.State == PipelineState.Failed && PipelineStateInfo.Reason != null)
{
// If this is an error pipe for a hosting applicationand we are logging,
// then log the error.
if (this.Runspace.GetExecutionContext.EngineHostInterface.UI.IsTranscribing)
{
this.Runspace.ExecutionContext.InternalHost.UI.TranscribeResult(this.Runspace, PipelineStateInfo.Reason.Message);
}
throw PipelineStateInfo.Reason;
}
//Execution completed successfully
// 2004/06/30-JonN was ReadAll() which was non-blocking
return Output.NonBlockingRead(Int32.MaxValue);
}
/// <summary>
/// Invoke the pipeline asynchronously
/// </summary>
/// <remarks>
/// Results are returned through the <see cref="Pipeline.Output"/> reader.
/// </remarks>
public override void InvokeAsync()
{
CoreInvoke(null, false);
}
/// <summary>
/// This parameter is true if Invoke is called.
/// It is false if InvokeAsync is called.
/// </summary>
protected bool SyncInvokeCall { get; private set; }
/// <summary>
/// Invoke the pipeline asynchronously with input.
/// </summary>
/// <param name="input">input to provide to pipeline. Input is
/// used only for synchronous execution</param>
/// <param name="syncCall">True if this method is called from
/// synchronous invoke else false</param>
/// <remarks>
/// Results are returned through the <see cref="Pipeline.Output"/> reader.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// No command is added to pipeline
/// </exception>
/// <exception cref="InvalidPipelineStateException">
/// PipelineState is not NotStarted.
/// </exception>
/// <exception cref="InvalidOperationException">
/// 1) A pipeline is already executing. Pipeline cannot execute
/// concurrently.
/// 2) InvokeAsync is called on nested pipeline. Nested pipeline
/// cannot be executed Asynchronously.
/// 3) Attempt is made to invoke a nested pipeline directly. Nested
/// pipeline must be invoked from a running pipeline.
/// </exception>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is not Open
/// </exception>
/// <exception cref="ObjectDisposedException">
/// Pipeline already disposed
/// </exception>
private void CoreInvoke(IEnumerable input, bool syncCall)
{
lock (SyncRoot)
{
// NTRAID#Windows Out Of Band Releases-915851-2005/09/13
if (_disposed)
{
throw PSTraceSource.NewObjectDisposedException("pipeline");
}
if (Commands == null || Commands.Count == 0)
{
throw PSTraceSource.NewInvalidOperationException(
RunspaceStrings.NoCommandInPipeline);
}
if (PipelineState != PipelineState.NotStarted)
{
InvalidPipelineStateException e =
new InvalidPipelineStateException
(
StringUtil.Format(RunspaceStrings.PipelineReInvokeNotAllowed),
PipelineState,
PipelineState.NotStarted
);
throw e;
}
if (syncCall && !(InputStream is PSDataCollectionStream<PSObject> || InputStream is PSDataCollectionStream<object>))
{
//Method is called from synchronous invoke.
if (input != null)
{
//TO-DO-Add a test make sure that ObjectDisposed
//exception is thrown
//Write input data in to inputStream and close the input
//pipe. If Input stream is already closed an
//ObjectDisposed exception will be thrown
foreach (object temp in input)
{
InputStream.Write(temp);
}
}
InputStream.Close();
}
SyncInvokeCall = syncCall;
//Create event which will be signalled when pipeline execution
//is completed/failed/stoped.
//Note:Runspace.Close waits for all the running pipeline
//to finish. This Event must be created before pipeline is
//added to list of running pipelines. This avoids the race condition
//where Close is called after pipeline is added to list of
//running pipeline but before event is created.
PipelineFinishedEvent = new ManualResetEvent(false);
//1) Do the check to ensure that pipeline no other
// pipeline is running.
//2) Runspace object maintains a list of pipelines in
//execution. Add this pipeline to the list.
RunspaceBase.DoConcurrentCheckAndAddToRunningPipelines(this, syncCall);
//Note: Set PipelineState to Running only after adding pipeline to list
//of pipelines in exectuion. AddForExecution checks that runspace is in
//state where pipeline can be run.
//StartPipelineExecution raises this event. See Windows Bug 1160481 for
//more details.
SetPipelineState(PipelineState.Running);
}
try
{
//Let the derived class start the pipeline execution.
StartPipelineExecution();
}
catch (Exception exception)
{
CommandProcessorBase.CheckForSevereException(exception);
//If we fail in any of the above three steps, set the correct states.
RunspaceBase.RemoveFromRunningPipelineList(this);
SetPipelineState(PipelineState.Failed, exception);
//Note: we are not raising the events in this case. However this is
//fine as user is getting the exception.
throw;
}
}
/// <summary>
/// Invokes a remote command and immediately disconnects if
/// transport layer supports it.
/// </summary>
internal override void InvokeAsyncAndDisconnect()
{
throw new NotSupportedException();
}
/// <summary>
/// Starts execution of pipeline.
/// </summary>
protected abstract void StartPipelineExecution();
#region concurrent pipeline check
private bool _performNestedCheck = true;
/// <summary>
/// For nested pipeline, system checks that Execute is called from
/// currently executing pipeline.
/// If PerformNestedCheck is false, this check is bypassed. This
/// is set to true by remote provider. In remote provider case all
/// the checks are done by the client proxy.
/// </summary>
internal bool PerformNestedCheck
{
set
{
_performNestedCheck = value;
}
}
/// <summary>
/// This is the thread on which NestedPipeline can be executed.
/// In case of LocalPipeline, this is the thread of execution
/// of LocalPipeline. In case of RemotePipeline, this is thread
/// on which EnterNestedPrompt is called.
/// RemotePipeline proxy should set it on at the begining of
/// EnterNestedPrompt and clear it on return.
/// </summary>
internal Thread NestedPipelineExecutionThread { get; set; }
/// <summary>
/// Check if anyother pipeline is executing.
/// In case of nested pipeline, checks that it is called
/// from currently executing pipeline's thread.
/// </summary>
/// <param name="syncCall">True if method is called from Invoke, false
/// if called from InvokeAsync</param>
/// <param name="syncObject">The sync object on which the lock is acquired</param>
/// <param name="isInLock">True if the method is invoked in a critical secion</param>
/// <exception cref="InvalidOperationException">
/// 1) A pipeline is already executing. Pipeline cannot execute
/// concurrently.
/// 2) InvokeAsync is called on nested pipeline. Nested pipeline
/// cannot be executed Asynchronously.
/// 3) Attempt is made to invoke a nested pipeline directly. Nested
/// pipeline must be invoked from a running pipeline.
/// </exception>
internal void DoConcurrentCheck(bool syncCall, object syncObject, bool isInLock)
{
PipelineBase currentPipeline = (PipelineBase)RunspaceBase.GetCurrentlyRunningPipeline();
if (IsNested == false)
{
if (currentPipeline == null)
{
return;
}
else
{
// Detect if we're running a pulse pipeline, or we're running a nested pipeline
// in a pulse pipeline
if (currentPipeline == RunspaceBase.PulsePipeline ||
(currentPipeline.IsNested && RunspaceBase.PulsePipeline != null))
{
// If so, wait and try again
if (isInLock)
{
// If the method is invoked in the lock statement, release the
// lock before wait on the pulse pipeline
Monitor.Exit(syncObject);
}
try
{
RunspaceBase.WaitForFinishofPipelines();
}
finally
{
if (isInLock)
{
// If the method is invoked in the lock statement, acquire the
// lock before we carry on with the rest operations
Monitor.Enter(syncObject);
}
}
DoConcurrentCheck(syncCall, syncObject, isInLock);
return;
}
throw PSTraceSource.NewInvalidOperationException(
RunspaceStrings.ConcurrentInvokeNotAllowed);
}
}
else
{
if (_performNestedCheck)
{
if (syncCall == false)
{
throw PSTraceSource.NewInvalidOperationException(
RunspaceStrings.NestedPipelineInvokeAsync);
}
if (currentPipeline == null)
{
if (this.IsChild)
{
// OK it's not really a nested pipeline but a call with RunspaceMode=UseCurrentRunspace
// This shouldn't fail so we'll clear the IsNested and IsChild flags and then return
// That way executions proceeds but everything gets clean up at the end when the pipeline completes
this.IsChild = false;
_isNested = false;
return;
}
throw PSTraceSource.NewInvalidOperationException(
RunspaceStrings.NestedPipelineNoParentPipeline);
}
Dbg.Assert(currentPipeline.NestedPipelineExecutionThread != null, "Current pipeline should always have NestedPipelineExecutionThread set");
Thread th = Thread.CurrentThread;
if (currentPipeline.NestedPipelineExecutionThread.Equals(th) == false)
{
throw PSTraceSource.NewInvalidOperationException(
RunspaceStrings.NestedPipelineNoParentPipeline);
}
}
}
}
#endregion concurrent pipeline check
#endregion invoke
#region Connect
/// <summary>
/// Connects synchronously to a running command on a remote server.
/// The pipeline object must be in the disconnected state.
/// </summary>
/// <returns>A collection of result objects.</returns>
public override Collection<PSObject> Connect()
{
// Connect semantics not supported on local (non-remoting) pipelines.
throw PSTraceSource.NewNotSupportedException(PipelineStrings.ConnectNotSupported);
}
/// <summary>
/// Connects asynchronously to a running command on a remote server.
/// </summary>
public override void ConnectAsync()
{
// Connect semantics not supported on local (non-remoting) pipelines.
throw PSTraceSource.NewNotSupportedException(PipelineStrings.ConnectNotSupported);
}
#endregion
#region state change event
/// <summary>
/// Event raised when Pipeline's state changes.
/// </summary>
public override event EventHandler<PipelineStateEventArgs> StateChanged = null;
/// <summary>
/// Current state of the pipeline.
/// </summary>
/// <remarks>
/// This value indicates the state of the pipeline after the change.
/// </remarks>
protected PipelineState PipelineState
{
get
{
return _pipelineStateInfo.State;
}
}
/// <summary>
/// This returns true if pipeline state is Completed, Failed or Stopped
/// </summary>
/// <returns></returns>
protected bool IsPipelineFinished()
{
return (PipelineState == PipelineState.Completed ||
PipelineState == PipelineState.Failed ||
PipelineState == PipelineState.Stopped);
}
/// <summary>
/// This is queue of all the state change event which have occured for
/// this pipeline. RaisePipelineStateEvents raises event for each
/// item in this queue. We don't raise the event with in SetPipelineState
/// because often SetPipelineState is called with in a lock.
/// Raising event in lock introduces chances of deadlock in GUI applications.
/// </summary>
private Queue<ExecutionEventQueueItem> _executionEventQueue = new Queue<ExecutionEventQueueItem>();
private class ExecutionEventQueueItem
{
public ExecutionEventQueueItem(PipelineStateInfo pipelineStateInfo, RunspaceAvailability currentAvailability, RunspaceAvailability newAvailability)
{
this.PipelineStateInfo = pipelineStateInfo;
this.CurrentRunspaceAvailability = currentAvailability;
this.NewRunspaceAvailability = newAvailability;
}
public PipelineStateInfo PipelineStateInfo;
public RunspaceAvailability CurrentRunspaceAvailability;
public RunspaceAvailability NewRunspaceAvailability;
}
/// <summary>
/// Sets the new execution state.
/// </summary>
/// <param name="state">the new state</param>
/// <param name="reason">
/// An exception indicating that state change is the result of an error,
/// otherwise; null.
/// </param>
/// <remarks>
/// Sets the internal execution state information member variable. It
/// also adds PipelineStateInfo to a queue. RaisePipelineStateEvents
/// raises event for each item in this queue.
/// </remarks>
protected void SetPipelineState(PipelineState state, Exception reason)
{
lock (SyncRoot)
{
if (state != PipelineState)
{
_pipelineStateInfo = new PipelineStateInfo(state, reason);
//Add _pipelineStateInfo to _executionEventQueue.
//RaisePipelineStateEvents will raise event for each item
//in this queue.
//Note:We are doing clone here instead of passing the member
//_pipelineStateInfo because we donot want outside
//to change pipeline state.
RunspaceAvailability previousAvailability = _runspace.RunspaceAvailability;
_runspace.UpdateRunspaceAvailability(_pipelineStateInfo.State, false);
_executionEventQueue.Enqueue(
new ExecutionEventQueueItem(
_pipelineStateInfo.Clone(),
previousAvailability,
_runspace.RunspaceAvailability));
}
}
}
/// <summary>
/// Set the new execution state
/// </summary>
/// <param name="state">the new state</param>
protected void SetPipelineState(PipelineState state)
{
SetPipelineState(state, null);
}
/// <summary>
/// Raises events for changes in execution state.
/// </summary>
protected void RaisePipelineStateEvents()
{
Queue<ExecutionEventQueueItem> tempEventQueue = null;
EventHandler<PipelineStateEventArgs> stateChanged = null;
bool runspaceHasAvailabilityChangedSubscribers = false;
lock (SyncRoot)
{
stateChanged = this.StateChanged;
runspaceHasAvailabilityChangedSubscribers = _runspace.HasAvailabilityChangedSubscribers;
if (stateChanged != null || runspaceHasAvailabilityChangedSubscribers)
{
tempEventQueue = _executionEventQueue;
_executionEventQueue = new Queue<ExecutionEventQueueItem>();
}
else
{
//Clear the events if there are no EventHandlers. This
//ensures that events do not get called for state
//changes prior to their registration.
_executionEventQueue.Clear();
}
}
if (tempEventQueue != null)
{
while (tempEventQueue.Count > 0)
{
ExecutionEventQueueItem queueItem = tempEventQueue.Dequeue();
if (runspaceHasAvailabilityChangedSubscribers && queueItem.NewRunspaceAvailability != queueItem.CurrentRunspaceAvailability)
{
_runspace.RaiseAvailabilityChangedEvent(queueItem.NewRunspaceAvailability);
}
// this is shipped as part of V1. So disabling the warning here.
#pragma warning disable 56500
//Exception rasied in the eventhandler are not error in pipeline.
//silently ignore them.
if (stateChanged != null)
{
try
{
stateChanged(this, new PipelineStateEventArgs(queueItem.PipelineStateInfo));
}
catch (Exception exception) // ignore non-severe exceptions
{
CommandProcessorBase.CheckForSevereException(exception);
}
}
#pragma warning restore 56500
}
}
}
/// <summary>
/// ManualResetEvent which is signaled when pipeline execution is
/// completed/failed/stoped.
/// </summary>
internal ManualResetEvent PipelineFinishedEvent { get; private set; }
#endregion
#region streams
/// <summary>
/// OutputStream from PipelineProcessor. Host will read on
/// ObjectReader of this stream. PipelineProcessor will write to
/// ObjectWriter of this stream.
/// </summary>
protected ObjectStreamBase OutputStream { get; }
private ObjectStreamBase _errorStream;
/// <summary>
/// ErrorStream from PipelineProcessor. Host will read on
/// ObjectReader of this stream. PipelineProcessor will write to
/// ObjectWriter of this stream.
/// </summary>
protected ObjectStreamBase ErrorStream
{
get
{
return _errorStream;
}
private set
{
Dbg.Assert(value != null, "ErrorStream cannot be null");
_errorStream = value;
_errorStream.DataReady += new EventHandler(OnErrorStreamDataReady);
}
}
// Winblue: 26115. This handler is used to populate Pipeline.HadErrors.
private void OnErrorStreamDataReady(object sender, EventArgs e)
{
if (_errorStream.Count > 0)
{
// unsubscribe from further event notifications as
// this notification is suffice to say there is an
// error.
_errorStream.DataReady -= new EventHandler(OnErrorStreamDataReady);
SetHadErrors(true);
}
}
/// <summary>
/// Informational Buffers that represent verbose, debug, progress,
/// warning emanating from the command execution.
/// </summary>
/// <remarks>
/// Informational buffers are introduced after 1.0. This can be
/// null if executing command as part of 1.0 hosting interfaces.
/// </remarks>
protected PSInformationalBuffers InformationalBuffers { get; }
/// <summary>
/// Stream for providing input to PipelineProcessor. Host will write on
/// ObjectWriter of this stream. PipelineProcessor will read from
/// ObjectReader of this stream.
/// </summary>
protected ObjectStreamBase InputStream { get; }
#endregion streams
#region history
//History information is internal so that Pipeline serialization code
//can access it.
/// <summary>
/// if true, this pipeline is added in history
/// </summary>
internal bool AddToHistory { get; set; }
/// <summary>
/// String which is added in the history
/// </summary>
/// <remarks>This needs to be internal so that it can be replaced
/// by invoke-cmd to place correct string in history.</remarks>
internal string HistoryString { get; set; }
#endregion history
#region misc
/// <summary>
/// Initialized the current pipeline instance with the supplied data.
/// </summary>
/// <param name="runspace"></param>
/// <param name="command"></param>
/// <param name="addToHistory"></param>
/// <param name="isNested"></param>
/// <exception cref="ArgumentNullException">
/// 1. addToHistory is true and command is null.
/// </exception>
private void Initialize(Runspace runspace, string command, bool addToHistory, bool isNested)
{
Dbg.Assert(runspace != null, "caller should validate the parameter");
_runspace = runspace;
_isNested = isNested;
if (addToHistory && command == null)
{
throw PSTraceSource.NewArgumentNullException("command");
}
if (command != null)
{
Commands.Add(new Command(command, true, false));
}
AddToHistory = addToHistory;
if (AddToHistory)
{
HistoryString = command;
}
}
private RunspaceBase RunspaceBase
{
get
{
return (RunspaceBase)Runspace;
}
}
/// <summary>
/// Object used for synchronization
/// </summary>
protected internal object SyncRoot { get; } = new object();
#endregion misc
#region IDisposable Members
/// <summary>
/// Set to true when object is disposed
/// </summary>
private bool _disposed;
/// <summary>
/// Protected dispose which can be overridden by derived classes.
/// </summary>
/// <param name="disposing"></param>
protected override
void
Dispose(bool disposing)
{
try
{
if (_disposed == false)
{
_disposed = true;
if (disposing)
{
InputStream.Close();
OutputStream.Close();
_errorStream.DataReady -= new EventHandler(OnErrorStreamDataReady);
_errorStream.Close();
_executionEventQueue.Clear();
}
}
}
finally
{
base.Dispose(disposing);
}
}
#endregion IDisposable Members
}
}
| |
namespace Nancy.Tests.Unit.ModelBinding
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Xml.Serialization;
using FakeItEasy;
using Fakes;
using Nancy.IO;
using Nancy.Json;
using Nancy.ModelBinding;
using Nancy.ModelBinding.DefaultBodyDeserializers;
using Nancy.ModelBinding.DefaultConverters;
using Nancy.Tests.Unit.ModelBinding.DefaultBodyDeserializers;
using Xunit.Extensions;
using Xunit;
public class DefaultBinderFixture
{
private readonly IFieldNameConverter passthroughNameConverter;
private readonly BindingDefaults emptyDefaults;
private readonly JavaScriptSerializer serializer;
private readonly BindingContext defaultBindingContext;
public DefaultBinderFixture()
{
this.defaultBindingContext = new BindingContext();
this.passthroughNameConverter = A.Fake<IFieldNameConverter>();
A.CallTo(() => this.passthroughNameConverter.Convert(null)).WithAnyArguments()
.ReturnsLazily(f => (string)f.Arguments[0]);
this.emptyDefaults = A.Fake<BindingDefaults>();
A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(new IBodyDeserializer[] { });
A.CallTo(() => this.emptyDefaults.DefaultTypeConverters).Returns(new ITypeConverter[] { });
this.serializer = new JavaScriptSerializer();
this.serializer.RegisterConverters(JsonSettings.Converters);
}
[Fact]
public void Should_throw_if_type_converters_is_null()
{
// Given, When
var result = Record.Exception(() => new DefaultBinder(null, new IBodyDeserializer[] { }, A.Fake<IFieldNameConverter>(), new BindingDefaults()));
// Then
result.ShouldBeOfType(typeof(ArgumentNullException));
}
[Fact]
public void Should_throw_if_body_deserializers_is_null()
{
// Given, When
var result = Record.Exception(() => new DefaultBinder(new ITypeConverter[] { }, null, A.Fake<IFieldNameConverter>(), new BindingDefaults()));
// Then
result.ShouldBeOfType(typeof(ArgumentNullException));
}
[Fact]
public void Should_throw_if_field_name_converter_is_null()
{
// Given, When
var result = Record.Exception(() => new DefaultBinder(new ITypeConverter[] { }, new IBodyDeserializer[] { }, null, new BindingDefaults()));
// Then
result.ShouldBeOfType(typeof(ArgumentNullException));
}
[Fact]
public void Should_throw_if_defaults_is_null()
{
// Given, When
var result = Record.Exception(() => new DefaultBinder(new ITypeConverter[] { }, new IBodyDeserializer[] { }, A.Fake<IFieldNameConverter>(), null));
// Then
result.ShouldBeOfType(typeof(ArgumentNullException));
}
[Fact]
public void Should_call_body_deserializer_if_one_matches()
{
// Given
var deserializer = A.Fake<IBodyDeserializer>();
A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true);
var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
binder.Bind(context, this.GetType(), null, BindingConfig.Default);
// Then
A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments()
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_not_call_body_deserializer_if_doesnt_match()
{
// Given
var deserializer = A.Fake<IBodyDeserializer>();
A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(false);
var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
binder.Bind(context, this.GetType(), null, BindingConfig.Default);
// Then
A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments()
.MustNotHaveHappened();
}
[Fact]
public void Should_pass_request_content_type_to_can_deserialize()
{
// Then
var deserializer = A.Fake<IBodyDeserializer>();
var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
binder.Bind(context, this.GetType(), null, BindingConfig.Default);
// Then
A.CallTo(() => deserializer.CanDeserialize("application/xml", A<BindingContext>._))
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_pass_binding_context_to_can_deserialize()
{
// Then
var deserializer = A.Fake<IBodyDeserializer>();
var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
binder.Bind(context, this.GetType(), null, BindingConfig.Default);
// Then
A.CallTo(() => deserializer.CanDeserialize("application/xml", A<BindingContext>.That.Not.IsNull()))
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_use_object_from_deserializer_if_one_returned()
{
// Given
var modelObject = new TestModel { StringProperty = "Hello!" };
var deserializer = A.Fake<IBodyDeserializer>();
A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true);
A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments().Returns(modelObject);
var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
var result = binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.ShouldBeOfType<TestModel>();
((TestModel)result).StringProperty.ShouldEqual("Hello!");
}
[Fact]
public void Should_use_object_from_deserializer_if_one_returned_and_overwrite_when_allowed()
{
// Given
var modelObject = new TestModel { StringPropertyWithDefaultValue = "Hello!" };
var deserializer = A.Fake<IBodyDeserializer>();
A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true);
A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments().Returns(modelObject);
var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
var result = binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.ShouldBeOfType<TestModel>();
((TestModel)result).StringPropertyWithDefaultValue.ShouldEqual("Hello!");
}
[Fact]
public void Should_use_object_from_deserializer_if_one_returned_and_not_overwrite_when_not_allowed()
{
// Given
var modelObject = new TestModel { StringPropertyWithDefaultValue = "Hello!" };
var deserializer = A.Fake<IBodyDeserializer>();
A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true);
A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments().Returns(modelObject);
var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
var result = binder.Bind(context, typeof(TestModel), null, BindingConfig.NoOverwrite);
// Then
result.ShouldBeOfType<TestModel>();
((TestModel)result).StringPropertyWithDefaultValue.ShouldEqual("Default Value");
}
[Fact]
public void Should_see_if_a_type_converter_is_available_for_each_property_on_the_model_where_incoming_value_exists()
{
// Given
var typeConverter = A.Fake<ITypeConverter>();
A.CallTo(() => typeConverter.CanConvertTo(null, null)).WithAnyArguments().Returns(false);
var binder = this.GetBinder(typeConverters: new[] { typeConverter });
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["StringProperty"] = "Test";
context.Request.Form["IntProperty"] = "12";
// When
binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
A.CallTo(() => typeConverter.CanConvertTo(null, null)).WithAnyArguments()
.MustHaveHappened(Repeated.Exactly.Times(2));
}
[Fact]
public void Should_call_convert_on_type_converter_if_available()
{
// Given
var typeConverter = A.Fake<ITypeConverter>();
A.CallTo(() => typeConverter.CanConvertTo(typeof(string), null)).WithAnyArguments().Returns(true);
A.CallTo(() => typeConverter.Convert(null, null, null)).WithAnyArguments().Returns(null);
var binder = this.GetBinder(typeConverters: new[] { typeConverter });
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["StringProperty"] = "Test";
// When
binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
A.CallTo(() => typeConverter.Convert(null, null, null)).WithAnyArguments()
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_ignore_properties_that_cannot_be_converted()
{
// Given
var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() });
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["StringProperty"] = "Test";
context.Request.Form["IntProperty"] = "12";
context.Request.Form["DateProperty"] = "Broken";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(12);
result.DateProperty.ShouldEqual(default(DateTime));
}
[Fact]
public void Should_throw_ModelBindingException_if_convertion_of_a_property_fails()
{
// Given
var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() });
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["IntProperty"] = "badint";
context.Request.Form["AnotherIntProperty"] = "morebad";
// Then
Assert.Throws<ModelBindingException>(() => binder.Bind(context, typeof(TestModel), null, BindingConfig.Default))
.ShouldMatch(exception =>
exception.BoundType == typeof(TestModel)
&& exception.PropertyBindingExceptions.Any(pe =>
pe.PropertyName == "IntProperty"
&& pe.AttemptedValue == "badint"
&& pe.InnerException.Message == "badint is not a valid value for Int32.")
&& exception.PropertyBindingExceptions.Any(pe =>
pe.PropertyName == "AnotherIntProperty"
&& pe.AttemptedValue == "morebad"
&& pe.InnerException.Message == "morebad is not a valid value for Int32."));
}
[Fact]
public void Should_not_throw_ModelBindingException_if_convertion_of_property_fails_and_ignore_error_is_true()
{
// Given
var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() });
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["IntProperty"] = "badint";
context.Request.Form["AnotherIntProperty"] = "morebad";
var config = new BindingConfig {IgnoreErrors = true};
// When
// Then
Assert.DoesNotThrow(() => binder.Bind(context, typeof(TestModel), null, config));
}
[Fact]
public void Should_set_remaining_properties_when_one_fails_and_ignore_error_is_enabled()
{
// Given
var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() });
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["IntProperty"] = "badint";
context.Request.Form["AnotherIntProperty"] = 10;
var config = new BindingConfig { IgnoreErrors = true };
// When
var model = binder.Bind(context, typeof(TestModel), null, config) as TestModel;
// Then
model.AnotherIntProperty.ShouldEqual(10);
}
[Fact]
public void Should_ignore_indexer_properties()
{
// Given
var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
var validProperties = 0;
var deserializer = A.Fake<IBodyDeserializer>();
A.CallTo(() => deserializer.CanDeserialize(A<string>.Ignored, A<BindingContext>._)).Returns(true);
A.CallTo(() => deserializer.Deserialize(A<string>.Ignored, A<Stream>.Ignored, A<BindingContext>.Ignored))
.Invokes(f =>
{
validProperties = f.Arguments.Get<BindingContext>(2).ValidModelProperties.Count();
})
.Returns(new TestModel());
A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(new[] { deserializer });
// When
binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
validProperties.ShouldEqual(10);
}
[Fact]
public void Should_pass_binding_context_to_default_deserializer()
{
// Given
var deserializer = A.Fake<IBodyDeserializer>();
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(new[] { deserializer });
// When
binder.Bind(context, this.GetType(), null, BindingConfig.Default);
// Then
A.CallTo(() => deserializer.CanDeserialize("application/xml", A<BindingContext>.That.Not.IsNull()))
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_use_field_name_converter_for_each_field()
{
// Given
var binder = this.GetBinder();
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["StringProperty"] = "Test";
context.Request.Form["IntProperty"] = "12";
// When
binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
A.CallTo(() => this.passthroughNameConverter.Convert(null)).WithAnyArguments()
.MustHaveHappened(Repeated.Exactly.Times(2));
}
[Fact]
public void Should_not_bind_anything_on_blacklist()
{
// Given
var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() });
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["StringProperty"] = "Test";
context.Request.Form["IntProperty"] = "12";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default, "IntProperty");
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(0);
}
[Fact]
public void Should_not_bind_anything_on_blacklist_when_the_blacklist_is_specified_by_expressions()
{
// Given
var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() });
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["StringProperty"] = "Test";
context.Request.Form["IntProperty"] = "12";
var fakeModule = A.Fake<INancyModule>();
var fakeModelBinderLocator = A.Fake<IModelBinderLocator>();
A.CallTo(() => fakeModule.Context).Returns(context);
A.CallTo(() => fakeModule.ModelBinderLocator).Returns(fakeModelBinderLocator);
A.CallTo(() => fakeModelBinderLocator.GetBinderForType(typeof (TestModel), context)).Returns(binder);
// When
var result = fakeModule.Bind<TestModel>(tm => tm.IntProperty);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(0);
}
[Fact]
public void Should_use_default_body_deserializer_if_one_found()
{
// Given
var deserializer = A.Fake<IBodyDeserializer>();
A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true);
A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(new[] { deserializer });
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
binder.Bind(context, this.GetType(), null, BindingConfig.Default);
// Then
A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments()
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_use_default_type_converter_if_one_found()
{
// Given
var typeConverter = A.Fake<ITypeConverter>();
A.CallTo(() => typeConverter.CanConvertTo(typeof(string), null)).WithAnyArguments().Returns(true);
A.CallTo(() => typeConverter.Convert(null, null, null)).WithAnyArguments().Returns(null);
A.CallTo(() => this.emptyDefaults.DefaultTypeConverters).Returns(new[] { typeConverter });
var binder = this.GetBinder(new ITypeConverter[] { });
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["StringProperty"] = "Test";
// When
binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
A.CallTo(() => typeConverter.Convert(null, null, null)).WithAnyArguments()
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void User_body_serializer_should_take_precedence_over_default_one()
{
// Given
var userDeserializer = A.Fake<IBodyDeserializer>();
A.CallTo(() => userDeserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true);
var defaultDeserializer = A.Fake<IBodyDeserializer>();
A.CallTo(() => defaultDeserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true);
A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(new[] { defaultDeserializer });
var binder = this.GetBinder(bodyDeserializers: new[] { userDeserializer });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
binder.Bind(context, this.GetType(), null, BindingConfig.Default);
// Then
A.CallTo(() => userDeserializer.Deserialize(null, null, null)).WithAnyArguments()
.MustHaveHappened(Repeated.Exactly.Once);
A.CallTo(() => defaultDeserializer.Deserialize(null, null, null)).WithAnyArguments()
.MustNotHaveHappened();
}
[Fact]
public void User_type_converter_should_take_precedence_over_default_one()
{
// Given
var userTypeConverter = A.Fake<ITypeConverter>();
A.CallTo(() => userTypeConverter.CanConvertTo(typeof(string), null)).WithAnyArguments().Returns(true);
A.CallTo(() => userTypeConverter.Convert(null, null, null)).WithAnyArguments().Returns(null);
var defaultTypeConverter = A.Fake<ITypeConverter>();
A.CallTo(() => defaultTypeConverter.CanConvertTo(typeof(string), null)).WithAnyArguments().Returns(true);
A.CallTo(() => defaultTypeConverter.Convert(null, null, null)).WithAnyArguments().Returns(null);
A.CallTo(() => this.emptyDefaults.DefaultTypeConverters).Returns(new[] { defaultTypeConverter });
var binder = this.GetBinder(new[] { userTypeConverter });
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["StringProperty"] = "Test";
// When
binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
A.CallTo(() => userTypeConverter.Convert(null, null, null)).WithAnyArguments()
.MustHaveHappened(Repeated.Exactly.Once);
A.CallTo(() => defaultTypeConverter.Convert(null, null, null)).WithAnyArguments()
.MustNotHaveHappened();
}
[Fact]
public void Should_bind_model_from_request()
{
// Given
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Request.Query["StringProperty"] = "Test";
context.Request.Query["IntProperty"] = "3";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(3);
}
[Fact]
public void Should_bind_model_from_context_parameters()
{
// Given
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Parameters["StringProperty"] = "Test";
context.Parameters["IntProperty"] = "3";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(3);
}
[Fact]
public void Form_properties_should_take_precendence_over_request_properties()
{
// Given
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Request.Form["StringProperty"] = "Test";
context.Request.Form["IntProperty"] = "3";
context.Request.Query["StringProperty"] = "Test2";
context.Request.Query["IntProperty"] = "1";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(3);
}
[Fact]
public void Should_bind_multiple_Form_properties_to_list()
{
//Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["StringProperty_0"] = "Test";
context.Request.Form["IntProperty_0"] = "1";
context.Request.Form["StringProperty_1"] = "Test2";
context.Request.Form["IntProperty_1"] = "2";
// When
var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);
// Then
result.First().StringProperty.ShouldEqual("Test");
result.First().IntProperty.ShouldEqual(1);
result.Last().StringProperty.ShouldEqual("Test2");
result.Last().IntProperty.ShouldEqual(2);
}
[Fact]
public void Should_bind_more_than_10_multiple_Form_properties_to_list()
{
//Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["IntProperty_0"] = "1";
context.Request.Form["IntProperty_01"] = "2";
context.Request.Form["IntProperty_02"] = "3";
context.Request.Form["IntProperty_03"] = "4";
context.Request.Form["IntProperty_04"] = "5";
context.Request.Form["IntProperty_05"] = "6";
context.Request.Form["IntProperty_06"] = "7";
context.Request.Form["IntProperty_07"] = "8";
context.Request.Form["IntProperty_08"] = "9";
context.Request.Form["IntProperty_09"] = "10";
context.Request.Form["IntProperty_10"] = "11";
context.Request.Form["IntProperty_11"] = "12";
context.Request.Form["IntProperty_12"] = "13";
// When
var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);
// Then
result.First().IntProperty.ShouldEqual(1);
result.ElementAt(1).IntProperty.ShouldEqual(2);
result.Last().IntProperty.ShouldEqual(13);
}
[Fact]
public void Should_bind_more_than_10_multiple_Form_properties_to_list_should_work_with_padded_zeros()
{
//Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["IntProperty_00"] = "1";
context.Request.Form["IntProperty_01"] = "2";
context.Request.Form["IntProperty_02"] = "3";
context.Request.Form["IntProperty_03"] = "4";
context.Request.Form["IntProperty_04"] = "5";
context.Request.Form["IntProperty_05"] = "6";
context.Request.Form["IntProperty_06"] = "7";
context.Request.Form["IntProperty_07"] = "8";
context.Request.Form["IntProperty_08"] = "9";
context.Request.Form["IntProperty_09"] = "10";
context.Request.Form["IntProperty_10"] = "11";
context.Request.Form["IntProperty_11"] = "12";
context.Request.Form["IntProperty_12"] = "13";
// When
var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);
// Then
result.First().IntProperty.ShouldEqual(1);
result.Last().IntProperty.ShouldEqual(13);
}
[Fact]
public void Should_bind_more_than_10_multiple_Form_properties_to_list_starting_counting_from_1()
{
//Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["IntProperty_01"] = "1";
context.Request.Form["IntProperty_02"] = "2";
context.Request.Form["IntProperty_03"] = "3";
context.Request.Form["IntProperty_04"] = "4";
context.Request.Form["IntProperty_05"] = "5";
context.Request.Form["IntProperty_06"] = "6";
context.Request.Form["IntProperty_07"] = "7";
context.Request.Form["IntProperty_08"] = "8";
context.Request.Form["IntProperty_09"] = "9";
context.Request.Form["IntProperty_10"] = "10";
context.Request.Form["IntProperty_11"] = "11";
context.Request.Form["IntProperty_12"] = "12";
// When
var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);
// Then
result.First().IntProperty.ShouldEqual(1);
result.Last().IntProperty.ShouldEqual(12);
}
[Fact]
public void Should_be_able_to_bind_more_than_once_should_ignore_non_list_properties_when_binding_to_a_list()
{
// Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["StringProperty"] = "Test";
context.Request.Form["IntProperty"] = "3";
context.Request.Form["NestedIntProperty[0]"] = "1";
context.Request.Form["NestedStringProperty[0]"] = "one";
context.Request.Form["NestedIntProperty[1]"] = "2";
context.Request.Form["NestedStringProperty[1]"] = "two";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
var result2 = (List<AnotherTestModel>)binder.Bind(context, typeof(List<AnotherTestModel>), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(3);
result2.First().NestedIntProperty.ShouldEqual(1);
result2.First().NestedStringProperty.ShouldEqual("one");
result2.Last().NestedIntProperty.ShouldEqual(2);
result2.Last().NestedStringProperty.ShouldEqual("two");
}
[Fact]
public void Should_bind_more_than_10_multiple_Form_properties_to_list_starting_with_jagged_ids()
{
//Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["IntProperty_01"] = "1";
context.Request.Form["IntProperty_04"] = "2";
context.Request.Form["IntProperty_05"] = "3";
context.Request.Form["IntProperty_06"] = "4";
context.Request.Form["IntProperty_09"] = "5";
context.Request.Form["IntProperty_11"] = "6";
context.Request.Form["IntProperty_57"] = "7";
context.Request.Form["IntProperty_199"] = "8";
context.Request.Form["IntProperty_1599"] = "9";
context.Request.Form["StringProperty_1599"] = "nine";
context.Request.Form["IntProperty_233"] = "10";
context.Request.Form["IntProperty_14"] = "11";
context.Request.Form["IntProperty_12"] = "12";
// When
var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);
// Then
result.First().IntProperty.ShouldEqual(1);
result.Last().IntProperty.ShouldEqual(9);
result.Last().StringProperty.ShouldEqual("nine");
}
[Fact]
public void Should_bind_to_IEnumerable_from_Form()
{
//Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["IntValues"] = "1,2,3,4";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.IntValues.ShouldHaveCount(4);
}
[Fact]
public void Should_bind_to_IEnumerable_from_Form_with_multiple_inputs()
{
// Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["IntValues_0"] = "1,2,3,4";
context.Request.Form["IntValues_1"] = "5,6,7,8";
// When
var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);
// Then
result.First().IntValues.ShouldHaveCount(4);
result.First().IntValues.ShouldEqualSequence(new[] { 1, 2, 3, 4 });
result.Last().IntValues.ShouldHaveCount(4);
result.Last().IntValues.ShouldEqualSequence(new[] { 5, 6, 7, 8 });
}
[Fact]
public void Should_bind_to_IEnumerable_from_Form_with_multiple_inputs_using_brackets_and_specifying_an_instance()
{
// Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["IntValues[0]"] = "1,2,3,4";
context.Request.Form["IntValues[1]"] = "5,6,7,8";
// When
var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), new List<TestModel> { new TestModel {AnotherStringProprety = "Test"} }, new BindingConfig { Overwrite = false});
// Then
result.First().AnotherStringProprety.ShouldEqual("Test");
result.First().IntValues.ShouldHaveCount(4);
result.First().IntValues.ShouldEqualSequence(new[] { 1, 2, 3, 4 });
result.Last().IntValues.ShouldHaveCount(4);
result.Last().IntValues.ShouldEqualSequence(new[] { 5, 6, 7, 8 });
}
[Fact]
public void Should_bind_to_IEnumerable_from_Form_with_multiple_inputs_using_brackets()
{
// Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["IntValues[0]"] = "1,2,3,4";
context.Request.Form["IntValues[1]"] = "5,6,7,8";
// When
var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);
// Then
result.First().IntValues.ShouldHaveCount(4);
result.First().IntValues.ShouldEqualSequence(new[] { 1, 2, 3, 4 });
result.Last().IntValues.ShouldHaveCount(4);
result.Last().IntValues.ShouldEqualSequence(new[] { 5, 6, 7, 8 });
}
[Fact]
public void Form_properties_should_take_precendence_over_request_properties_and_context_properties()
{
// Given
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Request.Form["StringProperty"] = "Test";
context.Request.Form["IntProperty"] = "3";
context.Request.Query["StringProperty"] = "Test2";
context.Request.Query["IntProperty"] = "1";
context.Parameters["StringProperty"] = "Test3";
context.Parameters["IntProperty"] = "2";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(3);
}
[Fact]
public void Request_properties_should_take_precendence_over_context_properties()
{
// Given
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Request.Query["StringProperty"] = "Test";
context.Request.Query["IntProperty"] = "12";
context.Parameters["StringProperty"] = "Test2";
context.Parameters["IntProperty"] = "13";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(12);
}
[Fact]
public void Should_be_able_to_bind_from_form_and_request_simultaneously()
{
// Given
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Request.Form["StringProperty"] = "Test";
context.Request.Query["IntProperty"] = "12";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(12);
}
[Theory]
[InlineData("de-DE", 4.50)]
[InlineData("en-GB", 450)]
[InlineData("en-US", 450)]
[InlineData("sv-SE", 4.50)]
[InlineData("ru-RU", 4.50)]
[InlineData("zh-TW", 450)]
public void Should_be_able_to_bind_culturally_aware_form_properties_if_numeric(string culture, double expected)
{
// Given
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Culture = new CultureInfo(culture);
context.Request.Form["DoubleProperty"] = "4,50";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.DoubleProperty.ShouldEqual(expected);
}
[Theory]
[InlineData("12/25/2012", 12, 25, 2012, "en-US")]
[InlineData("12/12/2012", 12, 12, 2012, "en-US")]
[InlineData("25/12/2012", 12, 25, 2012, "en-GB")]
[InlineData("12/12/2012", 12, 12, 2012, "en-GB")]
[InlineData("12/12/2012", 12, 12, 2012, "ru-RU")]
[InlineData("25/12/2012", 12, 25, 2012, "ru-RU")]
[InlineData("2012-12-25", 12, 25, 2012, "zh-TW")]
[InlineData("2012-12-12", 12, 12, 2012, "zh-TW")]
public void Should_be_able_to_bind_culturally_aware_form_properties_if_datetime(string date, int month, int day, int year, string culture)
{
// Given
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Culture = new CultureInfo(culture);
context.Request.Form["DateProperty"] = date;
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.DateProperty.Date.Month.ShouldEqual(month);
result.DateProperty.Date.Day.ShouldEqual(day);
result.DateProperty.Date.Year.ShouldEqual(year);
}
[Fact]
public void Should_be_able_to_bind_from_request_and_context_simultaneously()
{
// Given
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Request.Query["StringProperty"] = "Test";
context.Parameters["IntProperty"] = "12";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(12);
}
[Fact]
public void Should_not_overwrite_nullable_property_if_already_set_and_overwriting_is_not_allowed()
{
// Given
var binder = this.GetBinder();
var existing = new TestModel { StringProperty = "Existing Value" };
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Request.Query["StringProperty"] = "Test";
context.Request.Query["IntProperty"] = "12";
context.Parameters["StringProperty"] = "Test2";
context.Parameters["IntProperty"] = "1";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.NoOverwrite);
// Then
result.StringProperty.ShouldEqual("Existing Value");
result.IntProperty.ShouldEqual(12);
}
[Fact]
public void Should_not_overwrite_non_nullable_property_if_already_set_and_overwriting_is_not_allowed()
{
// Given
var binder = this.GetBinder();
var existing = new TestModel { IntProperty = 27 };
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Request.Query["StringProperty"] = "Test";
context.Request.Query["IntProperty"] = "12";
context.Parameters["StringProperty"] = "Test2";
context.Parameters["IntProperty"] = "1";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.NoOverwrite);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(27);
}
[Fact]
public void Should_overwrite_nullable_property_if_already_set_and_overwriting_is_allowed()
{
// Given
var binder = this.GetBinder();
var existing = new TestModel { StringProperty = "Existing Value" };
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Parameters["StringProperty"] = "Test2";
context.Parameters["IntProperty"] = "1";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test2");
result.IntProperty.ShouldEqual(1);
}
[Fact]
public void Should_overwrite_non_nullable_property_if_already_set_and_overwriting_is_allowed()
{
// Given
var binder = this.GetBinder();
var existing = new TestModel { IntProperty = 27 };
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Parameters["StringProperty"] = "Test2";
context.Parameters["IntProperty"] = "1";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test2");
result.IntProperty.ShouldEqual(1);
}
[Fact]
public void Should_bind_list_model_from_body()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new XmlBodyDeserializer() });
var body = XmlBodyDeserializerFixture.ToXmlString(new List<TestModel>(new[] { new TestModel { StringProperty = "Test" }, new TestModel { StringProperty = "AnotherTest" } }));
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body);
// When
var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);
// Then
result.First().StringProperty.ShouldEqual("Test");
result.Last().StringProperty.ShouldEqual("AnotherTest");
}
[Fact]
public void Should_bind_array_model_from_body()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new XmlBodyDeserializer() });
var body = XmlBodyDeserializerFixture.ToXmlString(new List<TestModel>(new[] { new TestModel { StringProperty = "Test" }, new TestModel { StringProperty = "AnotherTest" } }));
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body);
// When
var result = (TestModel[])binder.Bind(context, typeof(TestModel[]), null, BindingConfig.Default);
// Then
result.First().StringProperty.ShouldEqual("Test");
result.Last().StringProperty.ShouldEqual("AnotherTest");
}
[Fact]
public void Should_bind_string_array_model_from_body()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer() });
var body = serializer.Serialize(new[] { "Test","AnotherTest"});
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body);
// When
var result = (string[])binder.Bind(context, typeof(string[]), null, BindingConfig.Default);
// Then
result.First().ShouldEqual("Test");
result.Last().ShouldEqual("AnotherTest");
}
[Fact]
public void Should_bind_ienumerable_model_from_body()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer() });
var body = serializer.Serialize(new List<TestModel>(new[] { new TestModel { StringProperty = "Test" }, new TestModel { StringProperty = "AnotherTest" } }));
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body);
// When
var result = (IEnumerable<TestModel>)binder.Bind(context, typeof(IEnumerable<TestModel>), null, BindingConfig.Default);
// Then
result.First().StringProperty.ShouldEqual("Test");
result.Last().StringProperty.ShouldEqual("AnotherTest");
}
[Fact]
public void Should_bind_ienumerable_model_with_instance_from_body()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer() });
var body = serializer.Serialize(new List<TestModel>(new[] { new TestModel { StringProperty = "Test" }, new TestModel { StringProperty = "AnotherTest" } }));
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body);
var then = DateTime.Now;
var instance = new List<TestModel> { new TestModel{ DateProperty = then }, new TestModel { IntProperty = 9, AnotherStringProprety = "Bananas" } };
// When
var result = (IEnumerable<TestModel>)binder.Bind(context, typeof(IEnumerable<TestModel>), instance, new BindingConfig{Overwrite = false});
// Then
result.First().StringProperty.ShouldEqual("Test");
result.First().DateProperty.ShouldEqual(then);
result.Last().StringProperty.ShouldEqual("AnotherTest");
result.Last().IntProperty.ShouldEqual(9);
result.Last().AnotherStringProprety.ShouldEqual("Bananas");
}
[Fact]
public void Should_bind_model_with_instance_from_body()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new XmlBodyDeserializer() });
var body = XmlBodyDeserializerFixture.ToXmlString(new TestModel { StringProperty = "Test" });
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body);
var then = DateTime.Now;
var instance = new TestModel { DateProperty = then, IntProperty = 6, AnotherStringProprety = "Beers" };
// Wham
var result = (TestModel)binder.Bind(context, typeof(TestModel), instance, new BindingConfig { Overwrite = false });
// Then
result.StringProperty.ShouldEqual("Test");
result.DateProperty.ShouldEqual(then);
result.IntProperty.ShouldEqual(6);
result.AnotherStringProprety.ShouldEqual("Beers");
}
[Fact]
public void Should_bind_model_from_body_that_contains_an_array()
{
//Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters, new List<IBodyDeserializer> { new JsonBodyDeserializer() });
var body = serializer.Serialize(new TestModel {StringProperty = "Test", SomeStrings = new[] {"E", "A", "D", "G", "B", "E"}});
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body);
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.SomeStrings.ShouldHaveCount(6);
result.SomeStrings.ShouldEqualSequence(new[] { "E", "A", "D", "G", "B", "E" });
}
[Fact]
public void Should_bind_array_model_from_body_that_contains_an_array()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer() });
var body =
serializer.Serialize(new[]
{
new TestModel {StringProperty = "Test", SomeStrings = new[] {"E", "A", "D", "G", "B", "E"}},
new TestModel {StringProperty = "AnotherTest", SomeStrings = new[] {"E", "A", "D", "G", "B", "E"}}
});
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body);
// When
var result = (TestModel[])binder.Bind(context, typeof(TestModel[]), null, BindingConfig.Default, "SomeStrings");
// Then
result.First().SomeStrings.ShouldBeNull();
result.Last().SomeStrings.ShouldBeNull();
}
[Fact]
public void Form_request_and_context_properties_should_take_precedence_over_body_properties()
{
// Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var bodyDeserializers = new IBodyDeserializer[] { new XmlBodyDeserializer() };
var binder = this.GetBinder(typeConverters, bodyDeserializers);
var body = XmlBodyDeserializerFixture.ToXmlString(new TestModel { IntProperty = 0, StringProperty = "From body" });
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body);
context.Request.Form["StringProperty"] = "From form";
context.Request.Query["IntProperty"] = "1";
context.Parameters["AnotherStringProprety"] = "From context";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("From form");
result.AnotherStringProprety.ShouldEqual("From context");
result.IntProperty.ShouldEqual(1);
}
[Fact]
public void Form_request_and_context_properties_should_be_ignored_in_body_only_mode_when_there_is_a_body()
{
// Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var bodyDeserializers = new IBodyDeserializer[] { new XmlBodyDeserializer() };
var binder = GetBinder(typeConverters, bodyDeserializers);
var body = XmlBodyDeserializerFixture.ToXmlString(new TestModel { IntProperty = 2, StringProperty = "From body" });
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body);
context.Request.Form["StringProperty"] = "From form";
context.Request.Query["IntProperty"] = "1";
context.Parameters["AnotherStringProprety"] = "From context";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, new BindingConfig { BodyOnly = true });
// Then
result.StringProperty.ShouldEqual("From body");
result.AnotherStringProprety.ShouldBeNull(); // not in body, so default value
result.IntProperty.ShouldEqual(2);
}
[Fact]
public void Form_request_and_context_properties_should_NOT_be_used_in_body_only_mode_if_there_is_no_body()
{
// Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Request.Form["StringProperty"] = "From form";
context.Request.Query["IntProperty"] = "1";
context.Parameters["AnotherStringProprety"] = "From context";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, new BindingConfig { BodyOnly = true });
// Then
result.StringProperty.ShouldEqual(null);
result.AnotherStringProprety.ShouldEqual(null);
result.IntProperty.ShouldEqual(0);
}
[Fact]
public void Should_be_able_to_bind_body_request_form_and_context_properties()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new XmlBodyDeserializer() });
var body = XmlBodyDeserializerFixture.ToXmlString(new TestModel { DateProperty = new DateTime(2012, 8, 16) });
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body);
context.Request.Form["IntProperty"] = "0";
context.Request.Query["StringProperty"] = "From Query";
context.Parameters["AnotherStringProprety"] = "From Context";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("From Query");
result.IntProperty.ShouldEqual(0);
result.DateProperty.ShouldEqual(new DateTime(2012, 8, 16));
result.AnotherStringProprety.ShouldEqual("From Context");
}
[Fact]
public void Should_ignore_existing_instance_if_type_doesnt_match()
{
//Given
var binder = this.GetBinder();
var existing = new object();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.Default);
// Then
result.ShouldNotBeSameAs(existing);
}
[Fact]
public void Should_bind_to_valuetype_from_body()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer() });
var body = serializer.Serialize(1);
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body);
// When
var result = (int)binder.Bind(context, typeof(int), null, BindingConfig.Default);
// Then
result.ShouldEqual(1);
}
[Fact]
public void Should_bind_ienumerable_model__of_valuetype_from_body()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer() });
var body = serializer.Serialize(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 });
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body);
// When
var result = (IEnumerable<int>)binder.Bind(context, typeof(IEnumerable<int>), null, BindingConfig.Default);
// Then
result.ShouldEqualSequence(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 });
}
private IBinder GetBinder(IEnumerable<ITypeConverter> typeConverters = null, IEnumerable<IBodyDeserializer> bodyDeserializers = null, IFieldNameConverter nameConverter = null, BindingDefaults bindingDefaults = null)
{
var converters = typeConverters ?? new ITypeConverter[] { new DateTimeConverter(), new NumericConverter(), new FallbackConverter() };
var deserializers = bodyDeserializers ?? new IBodyDeserializer[] { };
var converter = nameConverter ?? this.passthroughNameConverter;
var defaults = bindingDefaults ?? this.emptyDefaults;
return new DefaultBinder(converters, deserializers, converter, defaults);
}
private static NancyContext CreateContextWithHeader(string name, IEnumerable<string> values)
{
var header = new Dictionary<string, IEnumerable<string>>
{
{ name, values }
};
return new NancyContext
{
Request = new FakeRequest("GET", "/", header),
Parameters = DynamicDictionary.Empty
};
}
private static NancyContext CreateContextWithHeaderAndBody(string name, IEnumerable<string> values, string body)
{
var header = new Dictionary<string, IEnumerable<string>>
{
{ name, values }
};
byte[] byteArray = Encoding.UTF8.GetBytes(body);
var bodyStream = RequestStream.FromStream(new MemoryStream(byteArray));
return new NancyContext
{
Request = new FakeRequest("GET", "/", header, bodyStream, "http", string.Empty),
Parameters = DynamicDictionary.Empty
};
}
public class TestModel
{
public TestModel()
{
this.StringPropertyWithDefaultValue = "Default Value";
}
public string StringProperty { get; set; }
public string AnotherStringProprety { get; set; }
public int IntProperty { get; set; }
public int AnotherIntProperty { get; set; }
public DateTime DateProperty { get; set; }
public string StringPropertyWithDefaultValue { get; set; }
public double DoubleProperty { get; set; }
[XmlIgnore]
public IEnumerable<int> IntValues { get; set; }
public string[] SomeStrings { get; set; }
public int this[int index]
{
get { return 0; }
set { }
}
public List<AnotherTestModel> Models { get; set; }
}
public class AnotherTestModel
{
public string NestedStringProperty { get; set; }
public int NestedIntProperty { get; set; }
public double NestedDoubleProperty { get; set; }
}
}
public class BindingConfigFixture
{
[Fact]
public void Should_allow_overwrite_on_new_instance()
{
// Given
// When
var instance = new BindingConfig();
// Then
instance.Overwrite.ShouldBeTrue();
}
}
}
| |
namespace android.gesture
{
[global::MonoJavaBridge.JavaClass()]
public partial class GestureOverlayView : android.widget.FrameLayout
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected GestureOverlayView(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.gesture.GestureOverlayView.OnGestureListener_))]
public partial interface OnGestureListener : global::MonoJavaBridge.IJavaObject
{
void onGestureStarted(android.gesture.GestureOverlayView arg0, android.view.MotionEvent arg1);
void onGesture(android.gesture.GestureOverlayView arg0, android.view.MotionEvent arg1);
void onGestureEnded(android.gesture.GestureOverlayView arg0, android.view.MotionEvent arg1);
void onGestureCancelled(android.gesture.GestureOverlayView arg0, android.view.MotionEvent arg1);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.gesture.GestureOverlayView.OnGestureListener))]
internal sealed partial class OnGestureListener_ : java.lang.Object, OnGestureListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal OnGestureListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
void android.gesture.GestureOverlayView.OnGestureListener.onGestureStarted(android.gesture.GestureOverlayView arg0, android.view.MotionEvent arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.OnGestureListener_.staticClass, "onGestureStarted", "(Landroid/gesture/GestureOverlayView;Landroid/view/MotionEvent;)V", ref global::android.gesture.GestureOverlayView.OnGestureListener_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m1;
void android.gesture.GestureOverlayView.OnGestureListener.onGesture(android.gesture.GestureOverlayView arg0, android.view.MotionEvent arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.OnGestureListener_.staticClass, "onGesture", "(Landroid/gesture/GestureOverlayView;Landroid/view/MotionEvent;)V", ref global::android.gesture.GestureOverlayView.OnGestureListener_._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m2;
void android.gesture.GestureOverlayView.OnGestureListener.onGestureEnded(android.gesture.GestureOverlayView arg0, android.view.MotionEvent arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.OnGestureListener_.staticClass, "onGestureEnded", "(Landroid/gesture/GestureOverlayView;Landroid/view/MotionEvent;)V", ref global::android.gesture.GestureOverlayView.OnGestureListener_._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m3;
void android.gesture.GestureOverlayView.OnGestureListener.onGestureCancelled(android.gesture.GestureOverlayView arg0, android.view.MotionEvent arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.OnGestureListener_.staticClass, "onGestureCancelled", "(Landroid/gesture/GestureOverlayView;Landroid/view/MotionEvent;)V", ref global::android.gesture.GestureOverlayView.OnGestureListener_._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
static OnGestureListener_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.gesture.GestureOverlayView.OnGestureListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/gesture/GestureOverlayView$OnGestureListener"));
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.gesture.GestureOverlayView.OnGesturePerformedListener_))]
public partial interface OnGesturePerformedListener : global::MonoJavaBridge.IJavaObject
{
void onGesturePerformed(android.gesture.GestureOverlayView arg0, android.gesture.Gesture arg1);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.gesture.GestureOverlayView.OnGesturePerformedListener))]
internal sealed partial class OnGesturePerformedListener_ : java.lang.Object, OnGesturePerformedListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal OnGesturePerformedListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
void android.gesture.GestureOverlayView.OnGesturePerformedListener.onGesturePerformed(android.gesture.GestureOverlayView arg0, android.gesture.Gesture arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.OnGesturePerformedListener_.staticClass, "onGesturePerformed", "(Landroid/gesture/GestureOverlayView;Landroid/gesture/Gesture;)V", ref global::android.gesture.GestureOverlayView.OnGesturePerformedListener_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
static OnGesturePerformedListener_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.gesture.GestureOverlayView.OnGesturePerformedListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/gesture/GestureOverlayView$OnGesturePerformedListener"));
}
}
public delegate void OnGesturePerformedListenerDelegate(android.gesture.GestureOverlayView arg0, android.gesture.Gesture arg1);
internal partial class OnGesturePerformedListenerDelegateWrapper : java.lang.Object, OnGesturePerformedListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected OnGesturePerformedListenerDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public OnGesturePerformedListenerDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.gesture.GestureOverlayView.OnGesturePerformedListenerDelegateWrapper._m0.native == global::System.IntPtr.Zero)
global::android.gesture.GestureOverlayView.OnGesturePerformedListenerDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.OnGesturePerformedListenerDelegateWrapper.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.gesture.GestureOverlayView.OnGesturePerformedListenerDelegateWrapper.staticClass, global::android.gesture.GestureOverlayView.OnGesturePerformedListenerDelegateWrapper._m0);
Init(@__env, handle);
}
static OnGesturePerformedListenerDelegateWrapper()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.gesture.GestureOverlayView.OnGesturePerformedListenerDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/gesture/GestureOverlayView_OnGesturePerformedListenerDelegateWrapper"));
}
}
internal partial class OnGesturePerformedListenerDelegateWrapper
{
private OnGesturePerformedListenerDelegate myDelegate;
public void onGesturePerformed(android.gesture.GestureOverlayView arg0, android.gesture.Gesture arg1)
{
myDelegate(arg0, arg1);
}
public static implicit operator OnGesturePerformedListenerDelegateWrapper(OnGesturePerformedListenerDelegate d)
{
global::android.gesture.GestureOverlayView.OnGesturePerformedListenerDelegateWrapper ret = new global::android.gesture.GestureOverlayView.OnGesturePerformedListenerDelegateWrapper();
ret.myDelegate = d;
global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret);
return ret;
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.gesture.GestureOverlayView.OnGesturingListener_))]
public partial interface OnGesturingListener : global::MonoJavaBridge.IJavaObject
{
void onGesturingStarted(android.gesture.GestureOverlayView arg0);
void onGesturingEnded(android.gesture.GestureOverlayView arg0);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.gesture.GestureOverlayView.OnGesturingListener))]
internal sealed partial class OnGesturingListener_ : java.lang.Object, OnGesturingListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal OnGesturingListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
void android.gesture.GestureOverlayView.OnGesturingListener.onGesturingStarted(android.gesture.GestureOverlayView arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.OnGesturingListener_.staticClass, "onGesturingStarted", "(Landroid/gesture/GestureOverlayView;)V", ref global::android.gesture.GestureOverlayView.OnGesturingListener_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m1;
void android.gesture.GestureOverlayView.OnGesturingListener.onGesturingEnded(android.gesture.GestureOverlayView arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.OnGesturingListener_.staticClass, "onGesturingEnded", "(Landroid/gesture/GestureOverlayView;)V", ref global::android.gesture.GestureOverlayView.OnGesturingListener_._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
static OnGesturingListener_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.gesture.GestureOverlayView.OnGesturingListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/gesture/GestureOverlayView$OnGesturingListener"));
}
}
private static global::MonoJavaBridge.MethodId _m0;
public virtual void clear(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.staticClass, "clear", "(Z)V", ref global::android.gesture.GestureOverlayView._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m1;
public override void draw(android.graphics.Canvas arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.staticClass, "draw", "(Landroid/graphics/Canvas;)V", ref global::android.gesture.GestureOverlayView._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m2;
protected override void onDetachedFromWindow()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.staticClass, "onDetachedFromWindow", "()V", ref global::android.gesture.GestureOverlayView._m2);
}
private static global::MonoJavaBridge.MethodId _m3;
public override bool dispatchTouchEvent(android.view.MotionEvent arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.gesture.GestureOverlayView.staticClass, "dispatchTouchEvent", "(Landroid/view/MotionEvent;)Z", ref global::android.gesture.GestureOverlayView._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m4;
public virtual void setOrientation(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.staticClass, "setOrientation", "(I)V", ref global::android.gesture.GestureOverlayView._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new int Orientation
{
get
{
return getOrientation();
}
set
{
setOrientation(value);
}
}
private static global::MonoJavaBridge.MethodId _m5;
public virtual int getOrientation()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.gesture.GestureOverlayView.staticClass, "getOrientation", "()I", ref global::android.gesture.GestureOverlayView._m5);
}
public new global::java.util.ArrayList CurrentStroke
{
get
{
return getCurrentStroke();
}
}
private static global::MonoJavaBridge.MethodId _m6;
public virtual global::java.util.ArrayList getCurrentStroke()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.gesture.GestureOverlayView.staticClass, "getCurrentStroke", "()Ljava/util/ArrayList;", ref global::android.gesture.GestureOverlayView._m6) as java.util.ArrayList;
}
private static global::MonoJavaBridge.MethodId _m7;
public virtual void setGestureColor(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.staticClass, "setGestureColor", "(I)V", ref global::android.gesture.GestureOverlayView._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m8;
public virtual void setUncertainGestureColor(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.staticClass, "setUncertainGestureColor", "(I)V", ref global::android.gesture.GestureOverlayView._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new int UncertainGestureColor
{
get
{
return getUncertainGestureColor();
}
set
{
setUncertainGestureColor(value);
}
}
private static global::MonoJavaBridge.MethodId _m9;
public virtual int getUncertainGestureColor()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.gesture.GestureOverlayView.staticClass, "getUncertainGestureColor", "()I", ref global::android.gesture.GestureOverlayView._m9);
}
public new int GestureColor
{
get
{
return getGestureColor();
}
set
{
setGestureColor(value);
}
}
private static global::MonoJavaBridge.MethodId _m10;
public virtual int getGestureColor()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.gesture.GestureOverlayView.staticClass, "getGestureColor", "()I", ref global::android.gesture.GestureOverlayView._m10);
}
public new float GestureStrokeWidth
{
get
{
return getGestureStrokeWidth();
}
set
{
setGestureStrokeWidth(value);
}
}
private static global::MonoJavaBridge.MethodId _m11;
public virtual float getGestureStrokeWidth()
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.gesture.GestureOverlayView.staticClass, "getGestureStrokeWidth", "()F", ref global::android.gesture.GestureOverlayView._m11);
}
private static global::MonoJavaBridge.MethodId _m12;
public virtual void setGestureStrokeWidth(float arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.staticClass, "setGestureStrokeWidth", "(F)V", ref global::android.gesture.GestureOverlayView._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new int GestureStrokeType
{
get
{
return getGestureStrokeType();
}
set
{
setGestureStrokeType(value);
}
}
private static global::MonoJavaBridge.MethodId _m13;
public virtual int getGestureStrokeType()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.gesture.GestureOverlayView.staticClass, "getGestureStrokeType", "()I", ref global::android.gesture.GestureOverlayView._m13);
}
private static global::MonoJavaBridge.MethodId _m14;
public virtual void setGestureStrokeType(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.staticClass, "setGestureStrokeType", "(I)V", ref global::android.gesture.GestureOverlayView._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new float GestureStrokeLengthThreshold
{
get
{
return getGestureStrokeLengthThreshold();
}
set
{
setGestureStrokeLengthThreshold(value);
}
}
private static global::MonoJavaBridge.MethodId _m15;
public virtual float getGestureStrokeLengthThreshold()
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.gesture.GestureOverlayView.staticClass, "getGestureStrokeLengthThreshold", "()F", ref global::android.gesture.GestureOverlayView._m15);
}
private static global::MonoJavaBridge.MethodId _m16;
public virtual void setGestureStrokeLengthThreshold(float arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.staticClass, "setGestureStrokeLengthThreshold", "(F)V", ref global::android.gesture.GestureOverlayView._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new float GestureStrokeSquarenessTreshold
{
get
{
return getGestureStrokeSquarenessTreshold();
}
set
{
setGestureStrokeSquarenessTreshold(value);
}
}
private static global::MonoJavaBridge.MethodId _m17;
public virtual float getGestureStrokeSquarenessTreshold()
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.gesture.GestureOverlayView.staticClass, "getGestureStrokeSquarenessTreshold", "()F", ref global::android.gesture.GestureOverlayView._m17);
}
private static global::MonoJavaBridge.MethodId _m18;
public virtual void setGestureStrokeSquarenessTreshold(float arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.staticClass, "setGestureStrokeSquarenessTreshold", "(F)V", ref global::android.gesture.GestureOverlayView._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new float GestureStrokeAngleThreshold
{
get
{
return getGestureStrokeAngleThreshold();
}
set
{
setGestureStrokeAngleThreshold(value);
}
}
private static global::MonoJavaBridge.MethodId _m19;
public virtual float getGestureStrokeAngleThreshold()
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.gesture.GestureOverlayView.staticClass, "getGestureStrokeAngleThreshold", "()F", ref global::android.gesture.GestureOverlayView._m19);
}
private static global::MonoJavaBridge.MethodId _m20;
public virtual void setGestureStrokeAngleThreshold(float arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.staticClass, "setGestureStrokeAngleThreshold", "(F)V", ref global::android.gesture.GestureOverlayView._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m21;
public virtual bool isEventsInterceptionEnabled()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.gesture.GestureOverlayView.staticClass, "isEventsInterceptionEnabled", "()Z", ref global::android.gesture.GestureOverlayView._m21);
}
public new bool EventsInterceptionEnabled
{
set
{
setEventsInterceptionEnabled(value);
}
}
private static global::MonoJavaBridge.MethodId _m22;
public virtual void setEventsInterceptionEnabled(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.staticClass, "setEventsInterceptionEnabled", "(Z)V", ref global::android.gesture.GestureOverlayView._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m23;
public virtual bool isFadeEnabled()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.gesture.GestureOverlayView.staticClass, "isFadeEnabled", "()Z", ref global::android.gesture.GestureOverlayView._m23);
}
public new bool FadeEnabled
{
set
{
setFadeEnabled(value);
}
}
private static global::MonoJavaBridge.MethodId _m24;
public virtual void setFadeEnabled(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.staticClass, "setFadeEnabled", "(Z)V", ref global::android.gesture.GestureOverlayView._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new global::android.gesture.Gesture Gesture
{
get
{
return getGesture();
}
set
{
setGesture(value);
}
}
private static global::MonoJavaBridge.MethodId _m25;
public virtual global::android.gesture.Gesture getGesture()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.gesture.GestureOverlayView.staticClass, "getGesture", "()Landroid/gesture/Gesture;", ref global::android.gesture.GestureOverlayView._m25) as android.gesture.Gesture;
}
private static global::MonoJavaBridge.MethodId _m26;
public virtual void setGesture(android.gesture.Gesture arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.staticClass, "setGesture", "(Landroid/gesture/Gesture;)V", ref global::android.gesture.GestureOverlayView._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new global::android.graphics.Path GesturePath
{
get
{
return getGesturePath();
}
}
private static global::MonoJavaBridge.MethodId _m27;
public virtual global::android.graphics.Path getGesturePath()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.gesture.GestureOverlayView.staticClass, "getGesturePath", "()Landroid/graphics/Path;", ref global::android.gesture.GestureOverlayView._m27) as android.graphics.Path;
}
private static global::MonoJavaBridge.MethodId _m28;
public virtual global::android.graphics.Path getGesturePath(android.graphics.Path arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.gesture.GestureOverlayView.staticClass, "getGesturePath", "(Landroid/graphics/Path;)Landroid/graphics/Path;", ref global::android.gesture.GestureOverlayView._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.graphics.Path;
}
private static global::MonoJavaBridge.MethodId _m29;
public virtual bool isGestureVisible()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.gesture.GestureOverlayView.staticClass, "isGestureVisible", "()Z", ref global::android.gesture.GestureOverlayView._m29);
}
public new bool GestureVisible
{
set
{
setGestureVisible(value);
}
}
private static global::MonoJavaBridge.MethodId _m30;
public virtual void setGestureVisible(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.staticClass, "setGestureVisible", "(Z)V", ref global::android.gesture.GestureOverlayView._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new long FadeOffset
{
get
{
return getFadeOffset();
}
set
{
setFadeOffset(value);
}
}
private static global::MonoJavaBridge.MethodId _m31;
public virtual long getFadeOffset()
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::android.gesture.GestureOverlayView.staticClass, "getFadeOffset", "()J", ref global::android.gesture.GestureOverlayView._m31);
}
private static global::MonoJavaBridge.MethodId _m32;
public virtual void setFadeOffset(long arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.staticClass, "setFadeOffset", "(J)V", ref global::android.gesture.GestureOverlayView._m32, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m33;
public virtual void addOnGestureListener(android.gesture.GestureOverlayView.OnGestureListener arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.staticClass, "addOnGestureListener", "(Landroid/gesture/GestureOverlayView$OnGestureListener;)V", ref global::android.gesture.GestureOverlayView._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m34;
public virtual void removeOnGestureListener(android.gesture.GestureOverlayView.OnGestureListener arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.staticClass, "removeOnGestureListener", "(Landroid/gesture/GestureOverlayView$OnGestureListener;)V", ref global::android.gesture.GestureOverlayView._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m35;
public virtual void removeAllOnGestureListeners()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.staticClass, "removeAllOnGestureListeners", "()V", ref global::android.gesture.GestureOverlayView._m35);
}
private static global::MonoJavaBridge.MethodId _m36;
public virtual void addOnGesturePerformedListener(android.gesture.GestureOverlayView.OnGesturePerformedListener arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.staticClass, "addOnGesturePerformedListener", "(Landroid/gesture/GestureOverlayView$OnGesturePerformedListener;)V", ref global::android.gesture.GestureOverlayView._m36, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public void addOnGesturePerformedListener(global::android.gesture.GestureOverlayView.OnGesturePerformedListenerDelegate arg0)
{
addOnGesturePerformedListener((global::android.gesture.GestureOverlayView.OnGesturePerformedListenerDelegateWrapper)arg0);
}
private static global::MonoJavaBridge.MethodId _m37;
public virtual void removeOnGesturePerformedListener(android.gesture.GestureOverlayView.OnGesturePerformedListener arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.staticClass, "removeOnGesturePerformedListener", "(Landroid/gesture/GestureOverlayView$OnGesturePerformedListener;)V", ref global::android.gesture.GestureOverlayView._m37, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public void removeOnGesturePerformedListener(global::android.gesture.GestureOverlayView.OnGesturePerformedListenerDelegate arg0)
{
removeOnGesturePerformedListener((global::android.gesture.GestureOverlayView.OnGesturePerformedListenerDelegateWrapper)arg0);
}
private static global::MonoJavaBridge.MethodId _m38;
public virtual void removeAllOnGesturePerformedListeners()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.staticClass, "removeAllOnGesturePerformedListeners", "()V", ref global::android.gesture.GestureOverlayView._m38);
}
private static global::MonoJavaBridge.MethodId _m39;
public virtual void addOnGesturingListener(android.gesture.GestureOverlayView.OnGesturingListener arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.staticClass, "addOnGesturingListener", "(Landroid/gesture/GestureOverlayView$OnGesturingListener;)V", ref global::android.gesture.GestureOverlayView._m39, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m40;
public virtual void removeOnGesturingListener(android.gesture.GestureOverlayView.OnGesturingListener arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.staticClass, "removeOnGesturingListener", "(Landroid/gesture/GestureOverlayView$OnGesturingListener;)V", ref global::android.gesture.GestureOverlayView._m40, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m41;
public virtual void removeAllOnGesturingListeners()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.staticClass, "removeAllOnGesturingListeners", "()V", ref global::android.gesture.GestureOverlayView._m41);
}
private static global::MonoJavaBridge.MethodId _m42;
public virtual bool isGesturing()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.gesture.GestureOverlayView.staticClass, "isGesturing", "()Z", ref global::android.gesture.GestureOverlayView._m42);
}
private static global::MonoJavaBridge.MethodId _m43;
public virtual void cancelClearAnimation()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.staticClass, "cancelClearAnimation", "()V", ref global::android.gesture.GestureOverlayView._m43);
}
private static global::MonoJavaBridge.MethodId _m44;
public virtual void cancelGesture()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.gesture.GestureOverlayView.staticClass, "cancelGesture", "()V", ref global::android.gesture.GestureOverlayView._m44);
}
private static global::MonoJavaBridge.MethodId _m45;
public GestureOverlayView(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.gesture.GestureOverlayView._m45.native == global::System.IntPtr.Zero)
global::android.gesture.GestureOverlayView._m45 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "<init>", "(Landroid/content/Context;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._m45, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m46;
public GestureOverlayView(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.gesture.GestureOverlayView._m46.native == global::System.IntPtr.Zero)
global::android.gesture.GestureOverlayView._m46 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._m46, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m47;
public GestureOverlayView(android.content.Context arg0, android.util.AttributeSet arg1, int arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.gesture.GestureOverlayView._m47.native == global::System.IntPtr.Zero)
global::android.gesture.GestureOverlayView._m47 = @__env.GetMethodIDNoThrow(global::android.gesture.GestureOverlayView.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;I)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.gesture.GestureOverlayView.staticClass, global::android.gesture.GestureOverlayView._m47, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
Init(@__env, handle);
}
public static int GESTURE_STROKE_TYPE_SINGLE
{
get
{
return 0;
}
}
public static int GESTURE_STROKE_TYPE_MULTIPLE
{
get
{
return 1;
}
}
public static int ORIENTATION_HORIZONTAL
{
get
{
return 0;
}
}
public static int ORIENTATION_VERTICAL
{
get
{
return 1;
}
}
static GestureOverlayView()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.gesture.GestureOverlayView.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/gesture/GestureOverlayView"));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using RestOfUs.Api.WebApi.Areas.HelpPage.Models;
namespace RestOfUs.Api.WebApi.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using AllReady.Areas.Admin.Features.EventManagerInvites;
using AllReady.Areas.Admin.ViewModels.ManagerInvite;
using AllReady.Features.Events;
using AllReady.Models;
using AllReady.Security;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using System.Linq;
using AllReady.Constants;
using AllReady.Areas.Admin.Features.Notifications;
using Microsoft.AspNetCore.Mvc.Routing;
namespace AllReady.Areas.Admin.Controllers
{
[Area(AreaNames.Admin)]
[Authorize]
public class EventManagerInviteController : Controller
{
private readonly IMediator _mediator;
private readonly UserManager<ApplicationUser> _userManager;
public EventManagerInviteController(IMediator mediator, UserManager<ApplicationUser> userManager)
{
_mediator = mediator;
_userManager = userManager;
}
// GET: Admin/Invite/Send/5
[Route("[area]/[controller]/[action]/{eventId:int}")]
[Authorize(nameof(UserType.OrgAdmin))]
public async Task<IActionResult> Send(int eventId)
{
var eventViewModel = await _mediator.SendAsync(new EventManagerInviteQuery { EventId = eventId });
if (eventViewModel == null) return NotFound();
if (!User.IsOrganizationAdmin(eventViewModel.OrganizationId))
{
return Unauthorized();
}
return View(eventViewModel);
}
// POST: Admin/Invite/Send/5
[HttpPost]
[ValidateAntiForgeryToken]
[Route("[area]/[controller]/[action]/{eventId:int}")]
[Authorize(nameof(UserType.OrgAdmin))]
public async Task<IActionResult> Send(int eventId, EventManagerInviteViewModel invite)
{
if (invite == null)
{
return BadRequest();
}
if (ModelState.IsValid)
{
var @event = await _mediator.SendAsync(new EventByEventIdQuery { EventId = eventId });
if (!User.IsOrganizationAdmin(@event.Campaign.ManagingOrganizationId))
{
return Unauthorized();
}
if (await _mediator.SendAsync(new UserHasEventManagerInviteQuery { EventId = invite.EventId, InviteeEmail = invite.InviteeEmailAddress }))
{
ModelState.AddModelError("InviteeEmailAddress", $"An invite already exists for {invite.InviteeEmailAddress}.");
return View("Send", invite);
}
var userToInvite = await _userManager.FindByEmailAsync(invite.InviteeEmailAddress);
if (userToInvite?.ManagedEvents != null && userToInvite.ManagedEvents.Any(m => m.EventId == eventId))
{
ModelState.AddModelError("InviteeEmailAddress", $"{invite.InviteeEmailAddress} is allready a manager for this event");
return View("Send", invite);
}
invite.EventId = eventId;
var user = await _userManager.GetUserAsync(User);
var inviteId = await _mediator.SendAsync(new CreateEventManagerInviteCommand
{
Invite = invite,
UserId = user.Id,
IsInviteeRegistered = userToInvite != null,
RegisterUrl = Url.Action(nameof(AllReady.Controllers.AccountController.Register), "Account", new { area="" }, HttpContext.Request.Scheme),
SenderName = user.Name
});
return RedirectToAction(actionName: "Details", controllerName: "Event", routeValues: new { area = AreaNames.Admin, id = invite.EventId });
}
return View("Send", invite);
}
[Route("[area]/[controller]/[action]/{inviteId:int}")]
public async Task<IActionResult> Details(int inviteId)
{
var viewModel = await _mediator.SendAsync(new EventManagerInviteDetailQuery { EventManagerInviteId = inviteId });
if (viewModel == null)
{
return NotFound();
}
if (!User.IsOrganizationAdmin(viewModel.OrganizationId))
{
return Unauthorized();
}
return View(viewModel);
}
[Route("[area]/[controller]/[action]/{inviteId:int}", Name = "EventManagerInviteAcceptRoute")]
public async Task<IActionResult> Accept(int inviteId)
{
var viewModel = await _mediator.SendAsync(new AcceptDeclineEventManagerInviteDetailQuery { EventManagerInviteId = inviteId });
if (viewModel == null)
{
return NotFound();
}
// User must be the invited user
var user = await _userManager.GetUserAsync(User);
if (user?.Email != viewModel.InviteeEmailAddress)
{
return Unauthorized();
}
return View(viewModel);
}
[Route("[area]/[controller]/[action]")]
public async Task<IActionResult> InviteAccepted(AcceptDeclineEventManagerInviteViewModel viewModel)
{
// User must be the invited user
var user = await _userManager.GetUserAsync(User);
if (user?.Email != viewModel.InviteeEmailAddress)
{
return Unauthorized();
}
await _mediator.SendAsync(new AcceptEventManagerInviteCommand
{
EventManagerInviteId = viewModel.InviteId
});
await _mediator.SendAsync(new CreateEventManagerCommand
{
UserId = user.Id,
EventId = viewModel.EventId
});
return View(viewModel);
}
[Route("[area]/[controller]/[action]/{inviteId:int}", Name = "EventManagerInviteDeclineRoute")]
public async Task<IActionResult> Decline(int inviteId)
{
var viewModel = await _mediator.SendAsync(new AcceptDeclineEventManagerInviteDetailQuery { EventManagerInviteId = inviteId });
if (viewModel == null)
{
return NotFound();
}
// User must be the invited user
var user = await _userManager.GetUserAsync(User);
if (user?.Email != viewModel.InviteeEmailAddress)
{
return Unauthorized();
}
return View(viewModel);
}
[Route("[area]/[controller]/[action]")]
public async Task<IActionResult> InviteDeclined(AcceptDeclineEventManagerInviteViewModel viewModel)
{
// User must be the invited user
var user = await _userManager.GetUserAsync(User);
if (user?.Email != viewModel.InviteeEmailAddress)
{
return Unauthorized();
}
await _mediator.SendAsync(new DeclineEventManagerInviteCommand
{
EventManagerInviteId = viewModel.InviteId
});
return View(viewModel);
}
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
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;
using Vevo;
using Vevo.Domain;
using Vevo.Domain.DataInterfaces;
using Vevo.Domain.Tax;
using Vevo.DataAccessLib.Cart;
using Vevo.Shared.Utilities;
using Vevo.WebAppLib;
using Vevo.WebUI.Ajax;
using Vevo.Base.Domain;
public partial class AdminAdvanced_MainControls_TaxClassRuleList : AdminAdvancedBaseUserControl
{
private bool _emptyRow = false;
private bool IsContainingOnlyEmptyRow
{
get { return _emptyRow; }
set { _emptyRow = value; }
}
private string TaxClassID
{
get
{
return MainContext.QueryString["TaxClassID"];
}
}
private GridViewHelper GridHelper
{
get
{
if (ViewState["GridHelper"] == null)
ViewState["GridHelper"] = new GridViewHelper( uxTaxClassRuleGrid, "" );
return (GridViewHelper) ViewState["GridHelper"];
}
}
private string CurrentTaxClassRuleID
{
get
{
if (ViewState["CurrentTaxClassRuleID"] == null)
return string.Empty;
else
return ViewState["CurrentTaxClassRuleID"].ToString();
}
set
{
ViewState["CurrentTaxClassRuleID"] = value;
}
}
private void SetUpSearchFilter()
{
IList<TableSchemaItem> list = DataAccessContext.TaxClassRepository.GetTaxClassRuleTableSchemas();
uxSearchFilter.SetUpSchema( list, "TaxClassID" );
}
private void SetFooterRowFocus()
{
Control countryList = uxTaxClassRuleGrid.FooterRow.FindControl( "uxCountryList" );
AjaxUtilities.GetScriptManager( this ).SetFocus( countryList );
}
private void CreateDummyRow( IList<TaxClassRule> list )
{
TaxClassRule taxClassRule = new TaxClassRule();
taxClassRule.TaxClassRuleID = "-1";
taxClassRule.TaxClassID = "";
list.Add( taxClassRule );
}
private void DeleteVisible( bool value )
{
uxDeleteButton.Visible = value;
if (value)
{
if (AdminConfig.CurrentTestMode == AdminConfig.TestMode.Normal)
{
uxDeleteConfirmButton.TargetControlID = "uxDeleteButton";
uxConfirmModalPopup.TargetControlID = "uxDeleteButton";
}
else
{
uxDeleteConfirmButton.TargetControlID = "uxDummyButton";
uxConfirmModalPopup.TargetControlID = "uxDummyButton";
}
}
else
{
uxDeleteConfirmButton.TargetControlID = "uxDummyButton";
uxConfirmModalPopup.TargetControlID = "uxDummyButton";
}
}
private void PopulateControls()
{
if (!MainContext.IsPostBack)
{
RefreshGrid();
}
if (uxTaxClassRuleGrid.Rows.Count > 0)
{
DeleteVisible( true );
uxPagingControl.Visible = true;
}
else
{
DeleteVisible( false );
uxPagingControl.Visible = false;
}
if (!IsAdminModifiable())
{
uxAddButton.Visible = false;
DeleteVisible( false );
}
}
private void RefreshGrid()
{
int totalItems;
IList<TaxClassRule> list = DataAccessContext.TaxClassRepository.SearchTaxClassRules(
TaxClassID,
GridHelper.GetFullSortText(),
uxSearchFilter.SearchFilterObj,
(uxPagingControl.CurrentPage - 1) * uxPagingControl.ItemsPerPages,
(uxPagingControl.CurrentPage * uxPagingControl.ItemsPerPages) - 1,
out totalItems );
if (list == null || list.Count == 0)
{
IsContainingOnlyEmptyRow = true;
list = new List<TaxClassRule>();
CreateDummyRow( list );
}
else
{
IsContainingOnlyEmptyRow = false;
}
uxTaxClassRuleGrid.DataSource = list;
uxTaxClassRuleGrid.DataBind();
uxPagingControl.NumberOfPages = (int) Math.Ceiling( (double) totalItems / uxPagingControl.ItemsPerPages );
RefreshDeleteButton();
((AdminAdvanced_Components_CountryList) uxTaxClassRuleGrid.FooterRow.FindControl( "uxCountryList" )).Refresh();
ResetCountryState();
}
private void RefreshDeleteButton()
{
if (IsContainingOnlyEmptyRow)
uxDeleteButton.Visible = false;
else
uxDeleteButton.Visible = true;
}
private void AddDefaultTaxRule( string countryCode, string stateCode, string zipCode )
{
if ((!String.IsNullOrEmpty( stateCode )) && String.IsNullOrEmpty( zipCode ))
{
TaxClass taxClass = DataAccessContext.TaxClassRepository.GetOne( TaxClassID );
TaxClassRule taxClassRule = new TaxClassRule();
for (int i = 0; i < taxClass.TaxClassRule.Count; i++)
{
if (taxClass.TaxClassRule[i].CountryCode == countryCode
&& String.IsNullOrEmpty( taxClass.TaxClassRule[i].StateCode )
&& String.IsNullOrEmpty( taxClass.TaxClassRule[i].ZipCode ))
{
taxClassRule = taxClass.TaxClassRule[i];
break;
}
}
if (taxClassRule.TaxClassRuleID == "0")
{
taxClassRule.CountryCode = countryCode;
taxClassRule.IsDefaultCountry = false;
taxClass.TaxClassRule.Add( taxClassRule );
}
else
{
taxClassRule.IsDefaultState = true;
taxClassRule.IsDefaultZip = true;
}
DataAccessContext.TaxClassRepository.Save( taxClass );
}
else if (!String.IsNullOrEmpty( zipCode ))
{
TaxClass taxClass = DataAccessContext.TaxClassRepository.GetOne( TaxClassID );
TaxClassRule taxClassRule = new TaxClassRule();
for (int i = 0; i < taxClass.TaxClassRule.Count; i++)
{
if (taxClass.TaxClassRule[i].CountryCode == countryCode
&& taxClass.TaxClassRule[i].StateCode == stateCode
&& String.IsNullOrEmpty( taxClass.TaxClassRule[i].ZipCode ))
{
taxClassRule = taxClass.TaxClassRule[i];
break;
}
}
if (taxClassRule.TaxClassRuleID == "0")
{
taxClassRule.CountryCode = countryCode;
taxClassRule.StateCode = stateCode;
taxClassRule.IsDefaultCountry = false;
taxClassRule.IsDefaultState = false;
taxClass.TaxClassRule.Add( taxClassRule );
bool createDefaultState = true;
if (!String.IsNullOrEmpty( stateCode ))
{
for (int i = 0; i < taxClass.TaxClassRule.Count; i++)
{
if (taxClass.TaxClassRule[i].CountryCode == countryCode
&& taxClass.TaxClassRule[i].StateCode == String.Empty)
{
taxClassRule = taxClass.TaxClassRule[i];
createDefaultState = false;
break;
}
}
if (createDefaultState)
{
taxClassRule = new TaxClassRule();
taxClassRule.CountryCode = countryCode;
taxClassRule.IsDefaultCountry = false;
taxClass.TaxClassRule.Add( taxClassRule );
}
else
{
taxClassRule.CountryCode = countryCode;
taxClassRule.IsDefaultState = true;
}
}
}
else
{
taxClassRule.IsDefaultState = false;
taxClassRule.IsDefaultZip = true;
}
DataAccessContext.TaxClassRepository.Save( taxClass );
}
}
private bool IsExistCountry( TaxClassRule taxClassRule )
{
TaxClass taxClass = DataAccessContext.TaxClassRepository.GetOne( TaxClassID );
for (int i = 0; i < taxClass.TaxClassRule.Count; i++)
{
if (taxClass.TaxClassRule[i].CountryCode == taxClassRule.CountryCode
&& String.IsNullOrEmpty( taxClass.TaxClassRule[i].StateCode )
&& String.IsNullOrEmpty( taxClass.TaxClassRule[i].ZipCode )
&& taxClass.TaxClassRule[i].IsDefaultCountry == false
&& taxClass.TaxClassRule[i].TaxClassRuleID != taxClassRule.TaxClassRuleID)
{
return true;
}
}
return false;
}
private bool IsExistState( TaxClassRule taxClassRule )
{
TaxClass taxClass = DataAccessContext.TaxClassRepository.GetOne( TaxClassID );
for (int i = 0; i < taxClass.TaxClassRule.Count; i++)
{
if (taxClass.TaxClassRule[i].CountryCode == taxClassRule.CountryCode
&& taxClass.TaxClassRule[i].StateCode == taxClassRule.StateCode
&& String.IsNullOrEmpty( taxClass.TaxClassRule[i].ZipCode )
&& taxClass.TaxClassRule[i].IsDefaultCountry == false
&& taxClass.TaxClassRule[i].IsDefaultState == false
&& taxClass.TaxClassRule[i].TaxClassRuleID != taxClassRule.TaxClassRuleID)
{
return true;
}
}
return false;
}
private bool IsExistZip( TaxClassRule taxClassRule )
{
TaxClass taxClass = DataAccessContext.TaxClassRepository.GetOne( TaxClassID );
for (int i = 0; i < taxClass.TaxClassRule.Count; i++)
{
if (taxClass.TaxClassRule[i].CountryCode == taxClassRule.CountryCode
&& taxClass.TaxClassRule[i].StateCode == taxClassRule.StateCode
&& taxClass.TaxClassRule[i].ZipCode == taxClassRule.ZipCode
&& taxClass.TaxClassRule[i].IsDefaultCountry == false
&& taxClass.TaxClassRule[i].IsDefaultState == false
&& taxClass.TaxClassRule[i].IsDefaultZip == false
&& taxClass.TaxClassRule[i].TaxClassRuleID != taxClassRule.TaxClassRuleID)
{
return true;
}
}
return false;
}
private bool IsExist( TaxClassRule taxClassRule, out string existMessage )
{
if (taxClassRule.IsDefaultCountry || taxClassRule.IsDefaultState || taxClassRule.IsDefaultZip)
{
existMessage = String.Empty;
return false;
}
else if (String.IsNullOrEmpty( taxClassRule.StateCode ) && String.IsNullOrEmpty( taxClassRule.ZipCode ))
{
existMessage = Resources.TaxClassRuleMessages.AddErrorDuplicatedCountry;
return IsExistCountry( taxClassRule );
}
else if (String.IsNullOrEmpty( taxClassRule.ZipCode ))
{
existMessage = Resources.TaxClassRuleMessages.AddErrorDuplicatedState;
return IsExistState( taxClassRule );
}
else
{
existMessage = Resources.TaxClassRuleMessages.AddErrorDuplicatedZip;
return IsExistZip( taxClassRule );
}
}
private TaxClassRule GetEditDetails( int index )
{
TaxClass taxClass = DataAccessContext.TaxClassRepository.GetOne( TaxClassID );
TaxClassRule taxClassRule = new TaxClassRule();
for (int i = 0; i < taxClass.TaxClassRule.Count; i++)
{
if (taxClass.TaxClassRule[i].TaxClassRuleID ==
((Label) uxTaxClassRuleGrid.Rows[index].FindControl( "uxTaxClassRuleIDLabel" )).Text.Trim())
{
taxClassRule = taxClass.TaxClassRule[i];
}
}
taxClassRule.TaxRate = ConvertUtilities.ToDecimal(
((TextBox) uxTaxClassRuleGrid.Rows[index].FindControl( "uxTaxRateText" )).Text );
return taxClassRule;
}
private TaxClassRule GetAddDetails()
{
TaxClassRule taxClassRule = new TaxClassRule();
taxClassRule.TaxClassRuleID = String.Empty;
taxClassRule.CountryCode =
((AdminAdvanced_Components_CountryList) uxTaxClassRuleGrid.FooterRow.FindControl( "uxCountryList" )).CurrentSelected;
taxClassRule.IsDefaultCountry = false;
taxClassRule.StateCode = ((AdminAdvanced_Components_StateList) uxTaxClassRuleGrid.FooterRow.FindControl( "uxStateList" )).CurrentSelected;
taxClassRule.IsDefaultState = false;
taxClassRule.ZipCode = ((TextBox) uxTaxClassRuleGrid.FooterRow.FindControl( "uxZipCodeText" )).Text.Trim();
taxClassRule.IsDefaultZip = false;
taxClassRule.TaxRate = ConvertUtilities.ToDecimal(
((TextBox) uxTaxClassRuleGrid.FooterRow.FindControl( "uxTaxRateText" )).Text );
return taxClassRule;
}
private void ResetCountryState()
{
if (uxTaxClassRuleGrid.ShowFooter)
{
((AdminAdvanced_Components_StateList) uxTaxClassRuleGrid.FooterRow.FindControl( "uxStateList" )).CountryCode = "";
((AdminAdvanced_Components_CountryList) uxTaxClassRuleGrid.FooterRow.FindControl( "uxCountryList" )).CurrentSelected = "";
((AdminAdvanced_Components_StateList) uxTaxClassRuleGrid.FooterRow.FindControl( "uxStateList" )).CurrentSelected = "";
}
}
protected void uxScarchChange( object sender, EventArgs e )
{
RefreshGrid();
}
protected void uxChangePage( object sender, EventArgs e )
{
RefreshGrid();
}
protected void uxTaxClassRuleGrid_DataBound( object sender, EventArgs e )
{
if (IsContainingOnlyEmptyRow)
{
uxTaxClassRuleGrid.Rows[0].Visible = false;
}
}
private bool HaveChildState( string countryCode )
{
TaxClass taxClass = DataAccessContext.TaxClassRepository.GetOne( TaxClassID );
for (int i = 0; i < taxClass.TaxClassRule.Count; i++)
{
if (taxClass.TaxClassRule[i].CountryCode == countryCode
&& taxClass.TaxClassRule[i].IsDefaultCountry == false
&& taxClass.TaxClassRule[i].IsDefaultState == false
&& taxClass.TaxClassRule[i].IsDefaultZip == false)
{
return true;
}
}
return false;
}
private bool HaveChildZip( string countryCode, string stateCode )
{
TaxClass taxClass = DataAccessContext.TaxClassRepository.GetOne( TaxClassID );
for (int i = 0; i < taxClass.TaxClassRule.Count; i++)
{
if (taxClass.TaxClassRule[i].CountryCode == countryCode
&& taxClass.TaxClassRule[i].StateCode == stateCode
&& taxClass.TaxClassRule[i].IsDefaultCountry == false
&& taxClass.TaxClassRule[i].IsDefaultState == false
&& taxClass.TaxClassRule[i].IsDefaultZip == false)
{
return true;
}
}
return false;
}
private void SetupDefaultTaxRule( string countryCode, string stateCode, string zipCode )
{
if ((!String.IsNullOrEmpty( stateCode )) && String.IsNullOrEmpty( zipCode ))
{
TaxClass taxClass = DataAccessContext.TaxClassRepository.GetOne( TaxClassID );
TaxClassRule taxClassRule = new TaxClassRule();
for (int i = 0; i < taxClass.TaxClassRule.Count; i++)
{
if (taxClass.TaxClassRule[i].CountryCode == countryCode
&& String.IsNullOrEmpty( taxClass.TaxClassRule[i].StateCode )
&& String.IsNullOrEmpty( taxClass.TaxClassRule[i].ZipCode ))
{
taxClassRule = taxClass.TaxClassRule[i];
}
}
if (!HaveChildState( countryCode ))
{
if (!HaveChildZip( countryCode, stateCode ))
{
taxClassRule.IsDefaultState = false;
taxClassRule.IsDefaultZip = false;
}
else
{
taxClassRule.IsDefaultState = false;
taxClassRule.IsDefaultZip = true;
}
DataAccessContext.TaxClassRepository.Save( taxClass );
}
else
{
taxClassRule.IsDefaultState = true;
taxClassRule.IsDefaultZip = true;
DataAccessContext.TaxClassRepository.Save( taxClass );
}
}
else if (!String.IsNullOrEmpty( zipCode ))
{
TaxClass taxClass = DataAccessContext.TaxClassRepository.GetOne( TaxClassID );
TaxClassRule taxClassRule = new TaxClassRule();
for (int i = 0; i < taxClass.TaxClassRule.Count; i++)
{
if (taxClass.TaxClassRule[i].CountryCode == countryCode
&& taxClass.TaxClassRule[i].StateCode == stateCode)
{
taxClassRule = taxClass.TaxClassRule[i];
}
}
if (!HaveChildZip( countryCode, stateCode ))
{
taxClassRule.IsDefaultState = false;
taxClassRule.IsDefaultZip = false;
DataAccessContext.TaxClassRepository.Save( taxClass );
}
}
}
private string DeleteItem( string taxClassRuleID )
{
int deleteIndex = -1;
TaxClass taxClass = DataAccessContext.TaxClassRepository.GetOne( TaxClassID );
TaxClassRule taxClassRule = new TaxClassRule();
for (int i = 0; i < taxClass.TaxClassRule.Count; i++)
{
if (taxClass.TaxClassRule[i].TaxClassRuleID == taxClassRuleID)
{
taxClassRule = taxClass.TaxClassRule[i];
deleteIndex = i;
}
}
string message = String.Empty;
if (taxClassRule.IsDefaultState && taxClassRule.IsDefaultZip)
{
if (HaveChildState( taxClassRule.CountryCode ))
message = Resources.TaxClassRuleMessages.DeleteDefaultStateError;
else
{
if (deleteIndex > -1)
{
taxClass.TaxClassRule.RemoveAt( deleteIndex );
DataAccessContext.TaxClassRepository.Save( taxClass );
}
}
}
else if (taxClassRule.IsDefaultZip)
{
if (HaveChildZip( taxClassRule.CountryCode, taxClassRule.StateCode ))
message = Resources.TaxClassRuleMessages.DeleteDefaultZipError;
else
{
if (deleteIndex > -1)
{
taxClass.TaxClassRule.RemoveAt( deleteIndex );
DataAccessContext.TaxClassRepository.Save( taxClass );
}
}
}
else
{
if (deleteIndex > -1)
{
taxClass.TaxClassRule.RemoveAt( deleteIndex );
DataAccessContext.TaxClassRepository.Save( taxClass );
}
SetupDefaultTaxRule( taxClassRule.CountryCode, taxClassRule.StateCode, taxClassRule.ZipCode );
}
return message;
}
protected void uxDeleteButton_Click( object sender, EventArgs e )
{
string errorMessage = String.Empty;
foreach (GridViewRow row in uxTaxClassRuleGrid.Rows)
{
CheckBox deleteCheck = (CheckBox) row.FindControl( "uxCheck" );
if (deleteCheck != null &&
deleteCheck.Checked)
{
string taxClassRuleID = uxTaxClassRuleGrid.DataKeys[row.RowIndex]["TaxClassRuleID"].ToString();
string message = DeleteItem( taxClassRuleID );
if (!String.IsNullOrEmpty( message ))
{
if (!String.IsNullOrEmpty( errorMessage ))
errorMessage += "<br />";
errorMessage += message;
}
}
}
if (String.IsNullOrEmpty( errorMessage ))
uxMessage.DisplayMessage( Resources.TaxClassRuleMessages.DeleteSuccess );
else
uxMessage.DisplayError( errorMessage );
RefreshGrid();
}
protected void Page_Load( object sender, EventArgs e )
{
if (String.IsNullOrEmpty( TaxClassID ))
MainContext.RedirectMainControl( "TaxClassList.ascx" );
uxSearchFilter.BubbleEvent += new EventHandler( uxScarchChange );
uxPagingControl.BubbleEvent += new EventHandler( uxChangePage );
if (!MainContext.IsPostBack)
SetUpSearchFilter();
}
protected void Page_PreRender( object sender, EventArgs e )
{
PopulateControls();
}
protected void uxAddButton_Click( object sender, EventArgs e )
{
uxTaxClassRuleGrid.EditIndex = -1;
uxTaxClassRuleGrid.ShowFooter = true;
uxTaxClassRuleGrid.ShowHeader = true;
RefreshGrid();
uxAddButton.Visible = false;
AdminAdvanced_Components_CountryList myCountry = ((AdminAdvanced_Components_CountryList) uxTaxClassRuleGrid.FooterRow.FindControl( "uxCountryList" ));
myCountry.CurrentSelected = "";
SetFooterRowFocus();
}
protected void uxTaxClassRuleGrid_Sorting( object sender, GridViewSortEventArgs e )
{
GridHelper.SelectSorting( e.SortExpression );
RefreshGrid();
}
protected void uxTaxClassRuleGrid_RowEditing( object sender, GridViewEditEventArgs e )
{
uxTaxClassRuleGrid.EditIndex = e.NewEditIndex;
RefreshGrid();
}
protected void uxTaxClassRuleGrid_CancelingEdit( object sender, GridViewCancelEditEventArgs e )
{
uxTaxClassRuleGrid.EditIndex = -1;
CurrentTaxClassRuleID = "";
RefreshGrid();
}
protected void uxTaxClassRuleGrid_RowCommand( object sender, GridViewCommandEventArgs e )
{
if (e.CommandName == "Add")
{
try
{
TaxClass taxClass = DataAccessContext.TaxClassRepository.GetOne( TaxClassID );
TaxClassRule taxClassRule = GetAddDetails();
if (String.IsNullOrEmpty( taxClassRule.CountryCode ))
{
uxMessage.DisplayError( Resources.TaxClassRuleMessages.AddErrorSelectCountry );
return;
}
string existMessage;
if (!IsExist( taxClassRule, out existMessage ))
{
taxClass.TaxClassRule.Add( taxClassRule );
DataAccessContext.TaxClassRepository.Save( taxClass );
AddDefaultTaxRule( taxClassRule.CountryCode, taxClassRule.StateCode, taxClassRule.ZipCode );
uxMessage.DisplayMessage( Resources.TaxClassRuleMessages.AddSuccess );
existMessage = String.Empty;
}
else
uxMessage.DisplayError( existMessage );
((TextBox) uxTaxClassRuleGrid.FooterRow.FindControl( "uxZipCodeText" )).Text = "";
((TextBox) uxTaxClassRuleGrid.FooterRow.FindControl( "uxTaxRateText" )).Text = "";
}
catch (Exception)
{
string message = Resources.TaxClassRuleMessages.AddError;
throw new VevoException( message );
}
finally
{
}
RefreshGrid();
}
if (e.CommandName == "Edit")
{
try
{
CurrentTaxClassRuleID = e.CommandArgument.ToString();
uxTaxClassRuleGrid.ShowFooter = false;
uxAddButton.Visible = true;
}
catch (Exception ex)
{
uxMessage.DisplayError( ex.Message );
}
}
}
protected void uxTaxClassRuleGrid_RowUpdating( object sender, GridViewUpdateEventArgs e )
{
try
{
TaxClass taxClass = DataAccessContext.TaxClassRepository.GetOne( TaxClassID );
TaxClassRule taxClassRule = GetEditDetails( e.RowIndex );
string existMessage;
if (!IsExist( taxClassRule, out existMessage ))
{
DataAccessContext.TaxClassRepository.Save( taxClass );
// End editing
uxTaxClassRuleGrid.EditIndex = -1;
CurrentTaxClassRuleID = "";
RefreshGrid();
existMessage = String.Empty;
uxMessage.DisplayMessage( Resources.TaxClassRuleMessages.UpdateSuccess );
}
else
uxMessage.DisplayError( existMessage );
}
catch (Exception)
{
string message = Resources.TaxClassRuleMessages.UpdateError;
throw new ApplicationException( message );
}
finally
{
// Avoid calling Update() automatically by GridView
e.Cancel = true;
}
}
protected void uxState_RefreshHandler( object sender, EventArgs e )
{
int index = uxTaxClassRuleGrid.EditIndex;
AdminAdvanced_Components_StateList stateList =
(AdminAdvanced_Components_StateList) uxTaxClassRuleGrid.Rows[index].FindControl( "uxStateList" );
AdminAdvanced_Components_CountryList countryList =
(AdminAdvanced_Components_CountryList) uxTaxClassRuleGrid.Rows[index].FindControl( "uxCountryList" );
stateList.CountryCode = countryList.CurrentSelected;
stateList.Refresh();
}
protected void uxStateFooter_RefreshHandler( object sender, EventArgs e )
{
AdminAdvanced_Components_StateList stateList = (AdminAdvanced_Components_StateList) uxTaxClassRuleGrid.FooterRow.FindControl( "uxStateList" );
AdminAdvanced_Components_CountryList countryList = (AdminAdvanced_Components_CountryList) uxTaxClassRuleGrid.FooterRow.FindControl( "uxCountryList" );
stateList.CountryCode = countryList.CurrentSelected;
stateList.Refresh();
}
protected string GetCountryText( object countryCode, object isDefaultCountry )
{
if (ConvertUtilities.ToBoolean( isDefaultCountry ))
{
IList<TaxClassRule> list = DataAccessContext.TaxClassRepository.GetTaxClassRulesByTaxClassID( TaxClassID );
if (list.Count == 1)
return "Everywhere in the world";
else
return "The rest of the world";
}
else
return countryCode.ToString();
}
protected string GetStateText( object stateCode, object isDefaultCountry, object isDefaultstate )
{
if (!ConvertUtilities.ToBoolean( isDefaultCountry ) && ConvertUtilities.ToBoolean( isDefaultstate ))
return "All other state";
else
return stateCode.ToString();
}
protected string GetZipText( object zipCode, object isDefaultCountry, object isDefaultstate, object isDefaultZip )
{
if (!ConvertUtilities.ToBoolean( isDefaultCountry ) &&
!ConvertUtilities.ToBoolean( isDefaultstate ) &&
ConvertUtilities.ToBoolean( isDefaultZip ))
return "All other zip";
else
return zipCode.ToString();
}
protected bool IsVisible( object isDefaultCountry, object isDefaultstate, object isDefaultZip )
{
return !(ConvertUtilities.ToBoolean( isDefaultCountry ) &&
ConvertUtilities.ToBoolean( isDefaultstate ) &&
ConvertUtilities.ToBoolean( isDefaultZip ));
}
}
| |
//
// Taken from PodSleuth (http://git.gnome.org/cgit/podsleuth)
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (c) 2007-2009 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.Collections;
using System.Collections.Generic;
namespace CocosSharp
{
public class PlistDictionary : PlistObjectBase, IEnumerable<KeyValuePair<string, PlistObjectBase>>
{
static PlistNull plistNull = new PlistNull();
List<string> keys;
Dictionary<string, PlistObjectBase> dict = new Dictionary<string, PlistObjectBase> ();
#region Properties
public override byte[] AsBinary
{
get { throw new NotImplementedException(); }
}
public override int AsInt
{
get { throw new NotImplementedException(); }
}
public override float AsFloat
{
get { throw new NotImplementedException(); }
}
public override string AsString
{
get { throw new NotImplementedException(); }
}
public override DateTime AsDate
{
get { throw new NotImplementedException(); }
}
public override bool AsBool
{
get { throw new NotImplementedException(); }
}
public override PlistArray AsArray
{
get { return null; }
}
public override PlistDictionary AsDictionary
{
get { return this; }
}
public int Count
{
get { return dict.Count; }
}
public PlistObjectBase this[string key]
{
get
{
PlistObjectBase value;
if (dict.TryGetValue(key, out value))
return value;
return plistNull;
}
set {
if (keys != null) {
if (!dict.ContainsKey (key))
keys.Add (key);
}
dict[key] = value;
}
}
#endregion Properties
#region Constructors
public PlistDictionary() : this(false)
{
}
public PlistDictionary(bool keepOrder)
{
if (keepOrder) {
keys = new List<string> ();
}
}
public PlistDictionary(Dictionary<string, PlistObjectBase> value) : this(value, false)
{
}
public PlistDictionary(Dictionary<string, PlistObjectBase> value, bool keepOrder) : this(keepOrder)
{
foreach (KeyValuePair<string, PlistObjectBase> item in value) {
Add (item.Key, item.Value);
}
}
public PlistDictionary(IDictionary value) : this(value, false)
{
}
public PlistDictionary(IDictionary value, bool keepOrder) : this(keepOrder)
{
foreach (DictionaryEntry item in value) {
Add ((string)item.Key, ObjectToPlistObject (item.Value));
}
}
#endregion Constructors
public override void Write(System.Xml.XmlWriter writer)
{
writer.WriteStartElement ("dict");
foreach (KeyValuePair<string, PlistObjectBase> item in this) {
writer.WriteElementString ("key", item.Key);
item.Value.Write (writer);
}
writer.WriteEndElement ();
}
public void Clear()
{
if (keys != null) {
keys.Clear ();
}
dict.Clear();
}
public void Add(string key, PlistObjectBase value)
{
if (keys != null) {
keys.Add(key);
}
if (dict.ContainsKey (key)) {
CocosSharp.CCLog.Log ("Warning: ignoring duplicate key: {0} (null? {1} empty? {2})", key, key == null, key == "");
} else {
dict.Add (key, value);
}
}
public bool Remove(string key)
{
if (keys != null) {
keys.Remove (key);
}
return dict.Remove(key);
}
public bool ContainsKey(string key)
{
return dict.ContainsKey (key);
}
public PlistObjectBase TryGetValue(string key)
{
PlistObjectBase value;
if (dict.TryGetValue (key, out value))
return value;
return null;
}
IEnumerator<KeyValuePair<string, PlistObjectBase>> GetEnumeratorFromKeys ()
{
foreach (string key in keys) {
yield return new KeyValuePair<string, PlistObjectBase> (key, dict[key]);
}
}
public IEnumerator<KeyValuePair<string, PlistObjectBase>> GetEnumerator ()
{
return keys == null ? dict.GetEnumerator () : GetEnumeratorFromKeys ();
}
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Resources;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
#pragma warning disable CA1054 // Uri parameters should not be strings
namespace Microsoft.NetCore.Analyzers.Security.Helpers
{
internal static class SecurityHelpers
{
/// <summary>
/// Creates a DiagnosticDescriptor with <see cref="LocalizableResourceString"/>s from <see cref="MicrosoftNetCoreAnalyzersResources"/>.
/// </summary>
/// <param name="id">Diagnostic identifier.</param>
/// <param name="titleResourceStringName">Name of the resource string inside <see cref="MicrosoftNetCoreAnalyzersResources"/> for the diagnostic's title.</param>
/// <param name="messageResourceStringName">Name of the resource string inside <see cref="MicrosoftNetCoreAnalyzersResources"/> for the diagnostic's message.</param>
/// <param name="ruleLevel">Indicates the <see cref="RuleLevel"/> for this rule.</param>
/// <param name="descriptionResourceStringName">Name of the resource string inside <see cref="MicrosoftNetCoreAnalyzersResources"/> for the diagnostic's description.</param>
/// <param name="isPortedFxCopRule">Flag indicating if this is a rule ported from legacy FxCop.</param>
/// <param name="isDataflowRule">Flag indicating if this is a dataflow analysis based rule.</param>
/// <returns>new DiagnosticDescriptor</returns>
public static DiagnosticDescriptor CreateDiagnosticDescriptor(
string id,
string titleResourceStringName,
string messageResourceStringName,
RuleLevel ruleLevel,
bool isPortedFxCopRule,
bool isDataflowRule,
bool isReportedAtCompilationEnd,
string? descriptionResourceStringName = null)
{
return CreateDiagnosticDescriptor(
id,
typeof(MicrosoftNetCoreAnalyzersResources),
titleResourceStringName,
messageResourceStringName,
ruleLevel,
isPortedFxCopRule,
isDataflowRule,
isReportedAtCompilationEnd,
descriptionResourceStringName);
}
/// <summary>
/// Creates a DiagnosticDescriptor with <see cref="LocalizableResourceString"/>s from the specified resource source type.
/// </summary>
/// <param name="id">Diagnostic identifier.</param>
/// <param name="resourceSource">Type containing the resource strings.</param>
/// <param name="titleResourceStringName">Name of the resource string inside <paramref name="resourceSource"/> for the diagnostic's title.</param>
/// <param name="messageResourceStringName">Name of the resource string inside <paramref name="resourceSource"/> for the diagnostic's message.</param>
/// <param name="ruleLevel">Indicates the <see cref="RuleLevel"/> for this rule.</param>
/// <param name="descriptionResourceStringName">Name of the resource string inside <paramref name="resourceSource"/> for the diagnostic's description.</param>
/// <param name="isPortedFxCopRule">Flag indicating if this is a rule ported from legacy FxCop.</param>
/// <param name="isDataflowRule">Flag indicating if this is a dataflow analysis based rule.</param>
/// <returns>new DiagnosticDescriptor</returns>
public static DiagnosticDescriptor CreateDiagnosticDescriptor(
string id,
Type resourceSource,
string titleResourceStringName,
string messageResourceStringName,
RuleLevel ruleLevel,
bool isPortedFxCopRule,
bool isDataflowRule,
bool isReportedAtCompilationEnd,
string? descriptionResourceStringName = null)
{
return DiagnosticDescriptorHelper.Create(
id,
GetResourceString(resourceSource, titleResourceStringName),
GetResourceString(resourceSource, messageResourceStringName),
DiagnosticCategory.Security,
ruleLevel,
descriptionResourceStringName != null ? GetResourceString(resourceSource, descriptionResourceStringName) : null,
isPortedFxCopRule,
isDataflowRule,
isReportedAtCompilationEnd: isReportedAtCompilationEnd);
}
/// <summary>
/// Deserialization methods for <see cref="T:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter"/>.
/// </summary>
[SuppressMessage("Documentation", "CA1200:Avoid using cref tags with a prefix", Justification = "The comment references a type that is not referenced by this compilation.")]
public static readonly ImmutableHashSet<string> BinaryFormatterDeserializationMethods =
ImmutableHashSet.Create(
StringComparer.Ordinal,
"Deserialize",
"DeserializeMethodResponse",
"UnsafeDeserialize",
"UnsafeDeserializeMethodResponse");
/// <summary>
/// Deserialization methods for <see cref="T:System.Runtime.Serialization.NetDataContractSerializer"/>.
/// </summary>
[SuppressMessage("Documentation", "CA1200:Avoid using cref tags with a prefix", Justification = "The comment references a type that is not referenced by this compilation.")]
public static readonly ImmutableHashSet<string> NetDataContractSerializerDeserializationMethods =
ImmutableHashSet.Create(
StringComparer.Ordinal,
"Deserialize",
"ReadObject");
/// <summary>
/// Deserialization methods for <see cref="T:System.Web.Script.Serialization.JavaScriptSerializer"/>.
/// </summary>
[SuppressMessage("Documentation", "CA1200:Avoid using cref tags with a prefix", Justification = "The comment references a type that is not referenced by this compilation.")]
public static readonly ImmutableHashSet<string> JavaScriptSerializerDeserializationMethods =
ImmutableHashSet.Create(
StringComparer.Ordinal,
"Deserialize",
"DeserializeObject");
/// <summary>
/// Deserialization methods for <see cref="T:System.Web.UI.ObjectStateFormatter"/>.
/// </summary>
[SuppressMessage("Documentation", "CA1200:Avoid using cref tags with a prefix", Justification = "The comment references a type that is not referenced by this compilation.")]
public static readonly ImmutableHashSet<string> ObjectStateFormatterDeserializationMethods =
ImmutableHashSet.Create(
StringComparer.Ordinal,
"Deserialize");
/// <summary>
/// Deserialization methods for <see cref="T:System.Runtime.Serialization.Formatters.Soap.SoapFormatter"/>.
/// </summary>
[SuppressMessage("Documentation", "CA1200:Avoid using cref tags with a prefix", Justification = "The comment references a type that is not referenced by this compilation.")]
public static readonly ImmutableHashSet<string> SoapFormatterDeserializationMethods =
ImmutableHashSet.Create(
StringComparer.Ordinal,
"Deserialize");
private static readonly ImmutableDictionary<Type, ResourceManager> ResourceManagerMapping =
ImmutableDictionary.CreateRange<Type, ResourceManager>(
new[]
{
(typeof(MicrosoftNetCoreAnalyzersResources), MicrosoftNetCoreAnalyzersResources.ResourceManager),
(typeof(MicrosoftNetCoreAnalyzersResources), MicrosoftNetCoreAnalyzersResources.ResourceManager),
}.Select(o => new KeyValuePair<Type, ResourceManager>(o.Item1, o.ResourceManager)));
/// <summary>
/// Methods using a <see cref="T:Newtonsoft.Json.JsonSerializerSettings"/> parameter for <see cref="T:Newtonsoft.Json.JsonSerializer"/>.
/// </summary>
[SuppressMessage("Documentation", "CA1200:Avoid using cref tags with a prefix", Justification = "The comment references a type that is not referenced by this compilation.")]
public static readonly ImmutableHashSet<string> JsonSerializerInstantiateWithSettingsMethods =
ImmutableHashSet.Create(
StringComparer.Ordinal,
"Create",
"CreateDefault");
/// <summary>
/// Methods using a <see cref="T:Newtonsoft.Json.JsonSerializerSettings"/> parameter for <see cref="T:Newtonsoft.Json.JsonConvert"/>.
/// </summary>
[SuppressMessage("Documentation", "CA1200:Avoid using cref tags with a prefix", Justification = "The comment references a type that is not referenced by this compilation.")]
public static readonly ImmutableHashSet<string> JsonConvertWithSettingsMethods =
ImmutableHashSet.Create(
StringComparer.Ordinal,
"DeserializeObject",
"DeserializeAnonymousType",
"PopulateObject");
/// <summary>
/// Deserialization methods for <see cref="T:Newtonsoft.Json.JsonSerializer"/>.
/// </summary>
[SuppressMessage("Documentation", "CA1200:Avoid using cref tags with a prefix", Justification = "The comment references a type that is not referenced by this compilation.")]
public static readonly ImmutableHashSet<string> JsonSerializerDeserializationMethods =
ImmutableHashSet.Create(
StringComparer.Ordinal,
"Deserialize",
"Populate");
/// <summary>
/// Deserialization methods for <see cref="T:System.Data.DataTable"/>.
/// </summary>
[SuppressMessage("Documentation", "CA1200:Avoid using cref tags with a prefix", Justification = "The comment references a type that is not referenced by this compilation.")]
public static readonly ImmutableHashSet<string> DataTableDeserializationMethods =
ImmutableHashSet.Create(
StringComparer.Ordinal,
"ReadXml");
/// <summary>
/// Deserialization methods for <see cref="T:System.Data.DataSet"/>.
/// </summary>
[SuppressMessage("Documentation", "CA1200:Avoid using cref tags with a prefix", Justification = "The comment references a type that is not referenced by this compilation.")]
public static readonly ImmutableHashSet<string> DataSetDeserializationMethods =
ImmutableHashSet.Create(
StringComparer.Ordinal,
"ReadXml");
/// <summary>
/// Determines if an operation is inside autogenerated code that's probably for a GUI app.
/// </summary>
/// <param name="operationAnalysisContext">Context for the operation in question.</param>
/// <param name="wellKnownTypeProvider"><see cref="WellKnownTypeProvider"/> for the operation's compilation.</param>
/// <returns>True if so, false otherwise.</returns>
/// <remarks>
/// This is useful for analyzers categorizing cases into different rules to represent different risks.
/// </remarks>
public static bool IsOperationInsideAutogeneratedCodeForGuiApp(
OperationAnalysisContext operationAnalysisContext,
WellKnownTypeProvider wellKnownTypeProvider)
{
INamedTypeSymbol? xmlReaderTypeSymbol =
wellKnownTypeProvider.GetOrCreateTypeByMetadataName(
WellKnownTypeNames.SystemXmlXmlReader);
INamedTypeSymbol? designerCategoryAttributeTypeSymbol =
wellKnownTypeProvider.GetOrCreateTypeByMetadataName(
WellKnownTypeNames.SystemComponentModelDesignerCategoryAttribute);
INamedTypeSymbol? debuggerNonUserCodeAttributeTypeSymbol =
wellKnownTypeProvider.GetOrCreateTypeByMetadataName(
WellKnownTypeNames.SystemDiagnosticsDebuggerNonUserCode);
return
operationAnalysisContext.ContainingSymbol is IMethodSymbol methodSymbol
&& methodSymbol.MetadataName == "ReadXmlSerializable"
&& methodSymbol.DeclaredAccessibility == Accessibility.Protected
&& methodSymbol.IsOverride
&& methodSymbol.ReturnsVoid
&& methodSymbol.Parameters.Length == 1
&& methodSymbol.Parameters[0].Type.Equals(xmlReaderTypeSymbol)
&& methodSymbol.ContainingType?.HasAttribute(designerCategoryAttributeTypeSymbol) == true
&& methodSymbol.HasAttribute(debuggerNonUserCodeAttributeTypeSymbol);
}
/// <summary>
/// Gets a <see cref="LocalizableResourceString"/> from <see cref="MicrosoftNetCoreAnalyzersResources"/>.
/// </summary>
/// <param name="resourceSource">Type containing the resource strings.</param>
/// <param name="name">Name of the resource string to retrieve.</param>
/// <returns>The corresponding <see cref="LocalizableResourceString"/>.</returns>
private static LocalizableResourceString GetResourceString(Type resourceSource, string name)
{
if (resourceSource == null)
{
throw new ArgumentNullException(nameof(resourceSource));
}
if (!ResourceManagerMapping.TryGetValue(resourceSource, out ResourceManager resourceManager))
{
throw new ArgumentException($"No mapping found for {resourceSource}", nameof(resourceSource));
}
#if DEBUG
if (resourceManager.GetString(name, System.Globalization.CultureInfo.InvariantCulture) == null)
{
throw new ArgumentException($"Resource string '{name}' not found in {resourceSource}", nameof(name));
}
#endif
LocalizableResourceString localizableResourceString = new LocalizableResourceString(name, resourceManager, resourceSource);
return localizableResourceString;
}
}
}
| |
#if SILVERLIGHT
using Microsoft.VisualStudio.TestTools.UnitTesting;
#elif NETFX_CORE
#else
using NUnit.Framework;
#endif
#if !FREE && !NETFX_CORE
using DevExpress.Xpf.Core.Tests;
#endif
using System;
using System.Linq.Expressions;
using DevExpress.Mvvm.DataAnnotations;
using System.Windows.Input;
using DevExpress.Mvvm.Native;
using System.ComponentModel.DataAnnotations;
#if !NETFX_CORE && !MONO
using System.Windows.Controls;
using System.Windows.Data;
#endif
namespace DevExpress.Mvvm.Tests {
#if !NETFX_CORE
[TestFixture]
public class ViewModelBaseTests {
public interface IService1 { }
public interface IService2 { }
public class TestService1 : IService1 { }
public class TestService2 : IService2 { }
[Test]
public void Interfaces() {
var viewModel = new TestViewModel();
var parentViewModel = new TestViewModel();
Assert.IsNull(viewModel.ParentViewModelChangedValue);
((ISupportParentViewModel)viewModel).ParentViewModel = parentViewModel;
Assert.AreEqual(parentViewModel, viewModel.ParentViewModelChangedValue);
parentViewModel.ServiceContainer.RegisterService(new TestService1());
Assert.IsNotNull(parentViewModel.ServiceContainer.GetService<IService1>());
Assert.IsNotNull(viewModel.ServiceContainer.GetService<IService1>());
Assert.IsNotNull(viewModel.GetService<IService1>());
Assert.IsNull(viewModel.GetService<IService1>(ServiceSearchMode.LocalOnly));
Assert.IsNull(viewModel.NavigatedToParameter);
((ISupportParameter)viewModel).Parameter = "test";
Assert.AreEqual("test", viewModel.NavigatedToParameter);
Assert.AreEqual("test", ((ISupportParameter)viewModel).Parameter);
}
[Test]
public void NullParameterCausesOnParameterChanged() {
var viewModel = new TestViewModel();
Assert.IsNull(((ISupportParameter)viewModel).Parameter);
Assert.AreEqual(0, viewModel.ParameterChangedCount);
((ISupportParameter)viewModel).Parameter = null;
Assert.IsNull(((ISupportParameter)viewModel).Parameter);
Assert.AreEqual(1, viewModel.ParameterChangedCount);
}
[Test]
public void InitializeInDesignMode() {
var viewModel = new TestViewModel();
Assert.IsNull(((ISupportParameter)viewModel).Parameter);
Assert.AreEqual(0, viewModel.ParameterChangedCount);
viewModel.ForceInitializeInDesignMode();
Assert.IsNull(((ISupportParameter)viewModel).Parameter);
Assert.AreEqual(1, viewModel.ParameterChangedCount);
}
[Test]
public void InitializeInRuntime() {
ViewModelDesignHelper.IsInDesignModeOverride = true;
var viewModel = new TestViewModel();
Assert.AreEqual(0, viewModel.InitializeInRuntimeCount);
ViewModelDesignHelper.IsInDesignModeOverride = false;
var viewModel2 = new TestViewModel();
Assert.AreEqual(1, viewModel2.InitializeInRuntimeCount);
}
#region command attrbute
public abstract class CommandAttributeViewModelBaseCounters : ViewModelBase {
public int BaseClassCommandCallCount;
public int SimpleMethodCallCount;
public int MethodWithCommandCallCount;
public int CustomNameCommandCallCount;
public bool MethodWithCanExecuteCanExcute = false;
public int MethodWithReturnTypeCallCount;
public int MethodWithParameterCallCount;
public int MethodWithParameterLastParameter;
public bool MethodWithCustomCanExecuteCanExcute = false;
}
public abstract class CommandAttributeViewModelBase : CommandAttributeViewModelBaseCounters {
[Command]
public void BaseClassCommand() { BaseClassCommandCallCount++; }
}
public class CommandAttributeViewModel : CommandAttributeViewModelBase {
[Command]
public void Simple() { SimpleMethodCallCount++; }
[Command]
public void MethodWithCommand() { MethodWithCommandCallCount++; }
public void NoAttribute() { }
[Command(Name = "MyCommand")]
public void CustomName() { CustomNameCommandCallCount++; }
[Command]
public void MethodWithCanExecute() { }
public bool CanMethodWithCanExecute() { return MethodWithCanExecuteCanExcute; }
[Command]
public int MethodWithReturnType() { MethodWithReturnTypeCallCount++; return 0; }
[Command]
public void MethodWithParameter(int parameter) { MethodWithParameterCallCount++; MethodWithParameterLastParameter = parameter; }
public bool CanMethodWithParameter(int parameter) { return parameter != 13; }
[Command(CanExecuteMethodName = "CanMethodWithCustomCanExecute_"
#if !SILVERLIGHT
, UseCommandManager = false
#endif
)]
public void MethodWithCustomCanExecute() { }
public bool CanMethodWithCustomCanExecute_() { return MethodWithCustomCanExecuteCanExcute; }
}
[MetadataType(typeof(CommandAttributeViewModelMetadata))]
public class CommandAttributeViewModel_FluentAPI : CommandAttributeViewModelBaseCounters {
public void BaseClassCommand() { BaseClassCommandCallCount++; }
public void Simple() { SimpleMethodCallCount++; }
public void MethodWithCommand() { MethodWithCommandCallCount++; }
public void NoAttribute() { }
public void CustomName() { CustomNameCommandCallCount++; }
public void MethodWithCanExecute() { }
public bool CanMethodWithCanExecute() { return MethodWithCanExecuteCanExcute; }
public int MethodWithReturnType() { MethodWithReturnTypeCallCount++; return 0; }
public void MethodWithParameter(int parameter) { MethodWithParameterCallCount++; MethodWithParameterLastParameter = parameter; }
public bool CanMethodWithParameter(int parameter) { return parameter != 13; }
public void MethodWithCustomCanExecute() { }
public bool CanMethodWithCustomCanExecute_(int x) { throw new InvalidOperationException(); }
public bool CanMethodWithCustomCanExecute_() { return MethodWithCustomCanExecuteCanExcute; }
}
public class CommandAttributeViewModelMetadata : IMetadataProvider<CommandAttributeViewModel_FluentAPI> {
void IMetadataProvider<CommandAttributeViewModel_FluentAPI>.BuildMetadata(MetadataBuilder<CommandAttributeViewModel_FluentAPI> builder) {
builder.CommandFromMethod(x => x.BaseClassCommand());
builder.CommandFromMethod(x => x.Simple());
builder.CommandFromMethod(x => x.MethodWithCommand());
builder.CommandFromMethod(x => x.CustomName()).CommandName("MyCommand");
builder.CommandFromMethod(x => x.MethodWithCanExecute());
builder.CommandFromMethod(x => x.MethodWithReturnType());
builder.CommandFromMethod(x => x.MethodWithParameter(default(int)));
builder.CommandFromMethod(x => x.MethodWithCustomCanExecute())
#if !SILVERLIGHT
.DoNotUseCommandManager()
#endif
.CanExecuteMethod(x => x.CanMethodWithCustomCanExecute_())
#if !SILVERLIGHT
.DoNotUseCommandManager()
#endif
;
}
}
#if !MONO
[Test]
public void CommandAttribute_ViewModelTest() {
var viewModel = new CommandAttributeViewModel();
CommandAttribute_ViewModelTestCore(viewModel, () => viewModel.MethodWithCanExecute(), () => viewModel.MethodWithCustomCanExecute());
viewModel = new CommandAttributeViewModel();
CommandAttribute_ViewModelTestCore(viewModel, () => viewModel.MethodWithCanExecute(), () => viewModel.MethodWithCustomCanExecute());
}
[Test]
public void CommandAttribute_ViewModelTest_FluentAPI() {
var viewModel = new CommandAttributeViewModel_FluentAPI();
CommandAttribute_ViewModelTestCore(viewModel, () => viewModel.MethodWithCanExecute(), () => viewModel.MethodWithCustomCanExecute());
}
void CommandAttribute_ViewModelTestCore(CommandAttributeViewModelBaseCounters viewModel, Expression<Action> methodWithCanExecuteExpression, Expression<Action> methodWithCustomCanExecuteExpression) {
var button = new Button() { DataContext = viewModel };
button.SetBinding(Button.CommandProperty, new Binding("SimpleCommand"));
button.Command.Execute(null);
Assert.AreEqual(1, viewModel.SimpleMethodCallCount);
button.SetBinding(Button.CommandProperty, new Binding("NoAttributeCommand"));
Assert.IsNull(button.Command);
button.SetBinding(Button.CommandProperty, new Binding("MethodWithCommand"));
button.Command.Execute(null);
Assert.AreEqual(1, viewModel.MethodWithCommandCallCount);
button.SetBinding(Button.CommandProperty, new Binding("MyCommand"));
button.Command.Execute(null);
Assert.AreEqual(1, viewModel.CustomNameCommandCallCount);
button.SetBinding(Button.CommandProperty, new Binding("BaseClassCommand"));
button.Command.Execute(null);
Assert.AreEqual(1, viewModel.BaseClassCommandCallCount);
Assert.IsTrue(button.IsEnabled);
button.SetBinding(Button.CommandProperty, new Binding("MethodWithCanExecuteCommand"));
Assert.IsFalse(button.IsEnabled);
viewModel.MethodWithCanExecuteCanExcute = true;
#if !SILVERLIGHT
DispatcherHelper.DoEvents();
#endif
Assert.IsFalse(button.IsEnabled);
viewModel.RaiseCanExecuteChanged(methodWithCanExecuteExpression);
#if !SILVERLIGHT
Assert.IsFalse(button.IsEnabled);
DispatcherHelper.DoEvents();
#endif
Assert.IsTrue(button.IsEnabled);
button.SetBinding(Button.CommandProperty, new Binding("MethodWithReturnTypeCommand"));
button.Command.Execute(null);
Assert.AreEqual(1, viewModel.MethodWithReturnTypeCallCount);
button.SetBinding(Button.CommandProperty, new Binding("MethodWithParameterCommand"));
button.Command.Execute(9);
Assert.AreEqual(1, viewModel.MethodWithParameterCallCount);
Assert.AreEqual(9, viewModel.MethodWithParameterLastParameter);
Assert.IsTrue(button.Command.CanExecute(9));
Assert.IsFalse(button.Command.CanExecute(13));
button.Command.Execute("10");
Assert.AreEqual(2, viewModel.MethodWithParameterCallCount);
Assert.AreEqual(10, viewModel.MethodWithParameterLastParameter);
button.SetBinding(Button.CommandProperty, new Binding("MethodWithCustomCanExecuteCommand"));
Assert.IsFalse(button.IsEnabled);
viewModel.MethodWithCustomCanExecuteCanExcute = true;
Assert.IsFalse(button.IsEnabled);
viewModel.RaiseCanExecuteChanged(methodWithCustomCanExecuteExpression);
Assert.IsTrue(button.IsEnabled);
}
#endif
#region exceptions
#pragma warning disable 0618
public class NameConflictViewModel : ViewModelBase {
[Command]
public void Simple() { }
public ICommand SimpleCommand { get; private set; }
}
[Test]
public void CommandAttribute_NameConflictTest() {
AssertHelper.AssertThrows<CommandAttributeException>(() => {
new NameConflictViewModel();
}, x => Assert.AreEqual("Property with the same name already exists: SimpleCommand.", x.Message));
}
public class DuplicateNamesViewModel : ViewModelBase {
[Command(Name = "MyCommand")]
public void Method1() { }
[Command(Name = "MyCommand")]
public void Method2() { }
}
[Test]
public void CommandAttribute_DuplicateNamesTest() {
AssertHelper.AssertThrows<CommandAttributeException>(() => {
new DuplicateNamesViewModel();
}, x => Assert.AreEqual("Property with the same name already exists: MyCommand.", x.Message));
}
public class NotPublicMethodViewModel : ViewModelBase {
[Command]
protected internal void NotPublicMethod() { }
}
[Test]
public void CommandAttribute_NotPublicMethodTest() {
AssertHelper.AssertThrows<CommandAttributeException>(() => {
new NotPublicMethodViewModel();
}, x => Assert.AreEqual("Method should be public: NotPublicMethod.", x.Message));
}
public class TooMuchArgumentsMethodViewModel : ViewModelBase {
[Command]
public void TooMuchArgumentsMethod(int a, int b) { }
}
[Test]
public void CommandAttribute_TooMuchArgumentsMethodTest() {
AssertHelper.AssertThrows<CommandAttributeException>(() => {
new TooMuchArgumentsMethodViewModel();
}, x => Assert.AreEqual("Method cannot have more than one parameter: TooMuchArgumentsMethod.", x.Message));
}
public class OutParameterMethodViewModel : ViewModelBase {
[Command]
public void OutParameterMethod(out int a) { a = 0; }
}
[Test]
public void CommandAttribute_OutParameterMethodTest() {
AssertHelper.AssertThrows<CommandAttributeException>(() => {
new OutParameterMethodViewModel();
}, x => Assert.AreEqual("Method cannot have out or reference parameter: OutParameterMethod.", x.Message));
}
public class RefParameterMethodViewModel : ViewModelBase {
[Command]
public void RefParameterMethod(ref int a) { a = 0; }
}
[Test]
public void CommandAttribute_RefParameterMethodTest() {
AssertHelper.AssertThrows<CommandAttributeException>(() => {
new RefParameterMethodViewModel();
}, x => Assert.AreEqual("Method cannot have out or reference parameter: RefParameterMethod.", x.Message));
}
public class CanExecuteParameterCountMismatchViewModel : ViewModelBase {
[Command]
public void Method() { }
public bool CanMethod(int a) { return true; }
}
[Test]
public void CommandAttribute_CanExecuteParameterCountMismatchTest() {
AssertHelper.AssertThrows<CommandAttributeException>(() => {
new CanExecuteParameterCountMismatchViewModel();
}, x => Assert.AreEqual("Can execute method has incorrect parameters: CanMethod.", x.Message));
}
public class CanExecuteParametersMismatchViewModel : ViewModelBase {
[Command]
public void Method(long a) { }
public bool CanMethod(int a) { return true; }
}
[Test]
public void CommandAttribute_CanExecuteParametersMismatchTest() {
AssertHelper.AssertThrows<CommandAttributeException>(() => {
new CanExecuteParametersMismatchViewModel();
}, x => Assert.AreEqual("Can execute method has incorrect parameters: CanMethod.", x.Message));
}
public class CanExecuteParametersMismatchViewModel2 : ViewModelBase {
[Command]
public void Method(int a) { }
public bool CanMethod(out int a) { a = 0; return true; }
}
[Test]
public void CommandAttribute_CanExecuteParametersMismatchTest2() {
AssertHelper.AssertThrows<CommandAttributeException>(() => {
new CanExecuteParametersMismatchViewModel2();
}, x => Assert.AreEqual("Can execute method has incorrect parameters: CanMethod.", x.Message));
}
public class NotPublicCanExecuteViewModel : ViewModelBase {
[Command]
public void Method() { }
bool CanMethod() { return true; }
}
[Test]
public void CommandAttribute_NotPublicCanExecuteTest() {
AssertHelper.AssertThrows<CommandAttributeException>(() => {
new NotPublicCanExecuteViewModel();
}, x => Assert.AreEqual("Method should be public: CanMethod.", x.Message));
}
public class InvalidCanExecuteMethodNameViewModel : ViewModelBase {
[Command(CanExecuteMethodName = "CanMethod_")]
public void Method() { }
}
[Test]
public void CommandAttribute_InvalidCanExecuteMethodNameTest() {
AssertHelper.AssertThrows<CommandAttributeException>(() => {
new InvalidCanExecuteMethodNameViewModel();
}, x => Assert.AreEqual("Method not found: CanMethod_.", x.Message));
}
#pragma warning restore 0618
#endregion
#endregion
}
#endif
public class TestViewModel : ViewModelBase {
public new IServiceContainer ServiceContainer { get { return base.ServiceContainer; } }
public object ParentViewModelChangedValue { get; private set; }
protected override void OnParentViewModelChanged(object parentViewModel) {
ParentViewModelChangedValue = parentViewModel;
base.OnParentViewModelChanged(parentViewModel);
}
public object NavigatedToParameter { get; private set; }
protected override void OnParameterChanged(object parameter) {
NavigatedToParameter = parameter;
ParameterChangedCount++;
base.OnParameterChanged(parameter);
}
public new T GetService<T>(ServiceSearchMode searchMode = ServiceSearchMode.PreferLocal) where T : class {
return base.GetService<T>(searchMode);
}
public int ParameterChangedCount { get; private set; }
public void ForceInitializeInDesignMode() {
OnInitializeInDesignMode();
}
public int InitializeInRuntimeCount { get; private set; }
protected override void OnInitializeInRuntime() {
base.OnInitializeInRuntime();
InitializeInRuntimeCount++;
}
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading;
namespace Orleans.Runtime
{
/// <summary>
/// The Log Writer base class provides default partial implementation suitable for most specific log writer.
/// </summary>
public abstract class LogWriterBase : ILogConsumer
{
/// <summary>
/// The method to call during logging.
/// This method should be very fast, since it is called synchronously during Orleans logging.
/// </summary>
/// <remarks>
/// To customize functionality in a log writter derived from this base class,
/// you should override the <c>FormatLogMessage</c> and/or <c>WriteLogMessage</c>
/// methods rather than overriding this method directly.
/// </remarks>
/// <seealso cref="FormatLogMessage"/>
/// <seealso cref="WriteLogMessage"/>
/// <param name="severity">The severity of the message being traced.</param>
/// <param name="loggerType">The type of logger the message is being traced through.</param>
/// <param name="caller">The name of the logger tracing the message.</param>
/// <param name="myIPEndPoint">The <see cref="IPEndPoint"/> of the Orleans client/server if known. May be null.</param>
/// <param name="message">The message to log.</param>
/// <param name="exception">The exception to log. May be null.</param>
/// <param name="eventCode">Numeric event code for this log entry. May be zero, meaning 'Unspecified'.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public void Log(
Logger.Severity severity,
TraceLogger.LoggerType loggerType,
string caller,
string message,
IPEndPoint myIPEndPoint,
Exception exception,
int errorCode)
{
var now = DateTime.UtcNow;
var msg = FormatLogMessage(
now,
severity,
loggerType,
caller,
message,
myIPEndPoint,
exception,
errorCode);
try
{
WriteLogMessage(msg, severity);
}
catch (Exception exc)
{
Trace.TraceError("Error writing log message {0} -- Exception={1}", msg, exc);
}
}
/// <summary>
/// The method to call during logging to format the log info into a string ready for output.
/// </summary>
/// <param name="severity">The severity of the message being traced.</param>
/// <param name="loggerType">The type of logger the message is being traced through.</param>
/// <param name="caller">The name of the logger tracing the message.</param>
/// <param name="myIPEndPoint">The <see cref="IPEndPoint"/> of the Orleans client/server if known. May be null.</param>
/// <param name="message">The message to log.</param>
/// <param name="exception">The exception to log. May be null.</param>
/// <param name="eventCode">Numeric event code for this log entry. May be zero, meaning 'Unspecified'.</param>
protected virtual string FormatLogMessage(
DateTime timestamp,
Logger.Severity severity,
TraceLogger.LoggerType loggerType,
string caller,
string message,
IPEndPoint myIPEndPoint,
Exception exception,
int errorCode)
{
return FormatLogMessage_Impl(timestamp, severity, loggerType, caller, message, myIPEndPoint, exception, errorCode, true);
}
protected string FormatLogMessage_Impl(
DateTime timestamp,
Logger.Severity severity,
TraceLogger.LoggerType loggerType,
string caller,
string message,
IPEndPoint myIPEndPoint,
Exception exception,
int errorCode,
bool includeStackTrace)
{
if (severity == Logger.Severity.Error)
message = "!!!!!!!!!! " + message;
string ip = myIPEndPoint == null ? String.Empty : myIPEndPoint.ToString();
if (loggerType.Equals(TraceLogger.LoggerType.Grain))
{
// Grain identifies itself, so I don't want an additional long string in the prefix.
// This is just a temporal solution to ease the dev. process, can remove later.
ip = String.Empty;
}
string exc = includeStackTrace ? TraceLogger.PrintException(exception) : TraceLogger.PrintExceptionWithoutStackTrace(exception);
string msg = String.Format("[{0} {1,5}\t{2}\t{3}\t{4}\t{5}]\t{6}\t{7}",
TraceLogger.ShowDate ? TraceLogger.PrintDate(timestamp) : TraceLogger.PrintTime(timestamp), //0
Thread.CurrentThread.ManagedThreadId, //1
TraceLogger.SeverityTable[(int)severity], //2
errorCode, //3
caller, //4
ip, //5
message, //6
exc); //7
return msg;
}
/// <summary>
/// The method to call during logging to write the log message by this log.
/// </summary>
/// <param name="msg">Message string to be writter</param>
/// <param name="severity">The severity level of this message</param>
protected abstract void WriteLogMessage(string msg, Logger.Severity severity);
}
/// <summary>
/// The Log Writer class is a convenient wrapper around the .Net Trace class.
/// </summary>
public class LogWriterToTrace : LogWriterBase, IFlushableLogConsumer
{
/// <summary>Write the log message for this log.</summary>
protected override void WriteLogMessage(string msg, Logger.Severity severity)
{
switch (severity)
{
case Logger.Severity.Off:
break;
case Logger.Severity.Error:
Trace.TraceError(msg);
break;
case Logger.Severity.Warning:
Trace.TraceWarning(msg);
break;
case Logger.Severity.Info:
Trace.TraceInformation(msg);
break;
case Logger.Severity.Verbose:
case Logger.Severity.Verbose2:
case Logger.Severity.Verbose3:
Trace.WriteLine(msg);
break;
}
Flush();
}
/// <summary>Flush any pending output for this log.</summary>
public void Flush()
{
Trace.Flush();
}
}
/// <summary>
/// The Log Writer class is a wrapper around the .Net Console class.
/// </summary>
public class LogWriterToConsole : LogWriterBase
{
private readonly bool useCompactConsoleOutput;
private readonly string logFormat;
/// <summary>
/// Default constructor
/// </summary>
public LogWriterToConsole()
: this(false, false)
{
}
/// <summary>
/// Constructor which allow some limited overides to the format of log message output,
/// primarily intended for allow simpler Console screen output.
/// </summary>
/// <param name="useCompactConsoleOutput"></param>
/// <param name="showMessageOnly"></param>
internal LogWriterToConsole(bool useCompactConsoleOutput, bool showMessageOnly)
{
this.useCompactConsoleOutput = useCompactConsoleOutput;
if (useCompactConsoleOutput)
{
// Log format items:
// {0} = timestamp
// {1} = severity
// {2} = errorCode
// {3} = caller
// {4} = message
// {5} = exception
this.logFormat = showMessageOnly ? "{4} {5}" : "{0} {1} {2} {3} - {4}\t{5}";
}
}
/// <summary>Format the log message into the format used by this log.</summary>
protected override string FormatLogMessage(
DateTime timestamp,
Logger.Severity severity,
TraceLogger.LoggerType loggerType,
string caller,
string message,
IPEndPoint myIPEndPoint,
Exception exception,
int errorCode)
{
// Don't include stack trace in Warning messages for Console output.
bool includeStackTrace = severity <= Logger.Severity.Error;
if (!useCompactConsoleOutput)
{
return base.FormatLogMessage_Impl(timestamp, severity, loggerType, caller, message, myIPEndPoint, exception, errorCode, includeStackTrace);
}
string msg = String.Format(logFormat,
TraceLogger.PrintTime(timestamp), //0
TraceLogger.SeverityTable[(int)severity], //1
errorCode, //2
caller, //3
message, //4
includeStackTrace ? TraceLogger.PrintException(exception) : TraceLogger.PrintExceptionWithoutStackTrace(exception)); //5
return msg;
}
/// <summary>Write the log message for this log.</summary>
protected override void WriteLogMessage(string msg, Logger.Severity severity)
{
Console.WriteLine(msg);
}
}
/// <summary>
/// This Log Writer class is an Orleans Log Consumer wrapper class which writes to a specified log file.
/// </summary>
public class LogWriterToFile : LogWriterBase, IFlushableLogConsumer, ICloseableLogConsumer
{
private string logFileName;
private readonly bool useFlush;
private StreamWriter logOutput;
private readonly object lockObj = new Object();
/// <summary>
/// Constructor, specifying the file to send output to.
/// </summary>
/// <param name="logFile">The log file to be written to.</param>
public LogWriterToFile(FileInfo logFile)
{
this.logFileName = logFile.FullName;
bool fileExists = File.Exists(logFileName);
this.logOutput = fileExists ? logFile.AppendText() : logFile.CreateText();
this.useFlush = !logOutput.AutoFlush;
logFile.Refresh(); // Refresh the cached view of FileInfo
}
/// <summary>Close this log file, after flushing any pending output.</summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public void Close()
{
if (logOutput == null) return; // was already closed.
try
{
lock (lockObj)
{
if (logOutput == null) // was already closed.
{
return;
}
logOutput.Flush();
logOutput.Dispose();
}
}
catch (Exception exc)
{
string msg = string.Format("Ignoring error closing log file {0} - {1}", logFileName, TraceLogger.PrintException(exc));
Console.WriteLine(msg);
}
this.logOutput = null;
this.logFileName = null;
}
/// <summary>Write the log message for this log.</summary>
protected override void WriteLogMessage(string msg, Logger.Severity severity)
{
lock (lockObj)
{
if (logOutput == null) return;
logOutput.WriteLine(msg);
if (useFlush)
{
logOutput.Flush(); // We need to explicitly flush each log write
}
}
}
/// <summary>Flush any pending output for this log.</summary>
public void Flush()
{
lock (lockObj)
{
if (logOutput == null) return;
logOutput.Flush();
}
}
}
/// <summary>
/// Just a simple log writer wrapper class with public WriteToLog method directly, without formatting.
/// Mainly to be used from tests and external utilities.
/// </summary>
public class SimpleLogWriterToFile : LogWriterToFile
{
/// <summary>
/// Constructor, specifying the file to send output to.
/// </summary>
/// <param name="logFile">The log file to be written to.</param>
public SimpleLogWriterToFile(FileInfo logFile)
: base(logFile)
{
}
/// <summary>
/// Output message directly to log file -- no formatting is performed.
/// </summary>
/// <param name="msg">Message text to be logged.</param>
/// <param name="severity">Severity of this log message -- ignored.</param>
public void WriteToLog(string msg, Logger.Severity severity)
{
WriteLogMessage(msg, severity);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Net.Http
{
public partial class ByteArrayContent : System.Net.Http.HttpContent
{
public ByteArrayContent(byte[] content) { }
public ByteArrayContent(byte[] content, int offset, int count) { }
protected override System.Threading.Tasks.Task<System.IO.Stream> CreateContentReadStreamAsync() { return default(System.Threading.Tasks.Task<System.IO.Stream>); }
protected override System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context) { return default(System.Threading.Tasks.Task); }
protected internal override bool TryComputeLength(out long length) { length = default(long); return default(bool); }
}
public enum ClientCertificateOption
{
Automatic = 1,
Manual = 0,
}
public abstract partial class DelegatingHandler : System.Net.Http.HttpMessageHandler
{
protected DelegatingHandler() { }
protected DelegatingHandler(System.Net.Http.HttpMessageHandler innerHandler) { }
public System.Net.Http.HttpMessageHandler InnerHandler { get { return default(System.Net.Http.HttpMessageHandler); } set { } }
protected override void Dispose(bool disposing) { }
protected internal override System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); }
}
public partial class FormUrlEncodedContent : System.Net.Http.ByteArrayContent
{
public FormUrlEncodedContent(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, string>> nameValueCollection) : base(default(byte[])) { }
}
public partial class HttpClient : System.Net.Http.HttpMessageInvoker
{
public HttpClient() : base(default(System.Net.Http.HttpMessageHandler)) { }
public HttpClient(System.Net.Http.HttpMessageHandler handler) : base(default(System.Net.Http.HttpMessageHandler)) { }
public HttpClient(System.Net.Http.HttpMessageHandler handler, bool disposeHandler) : base(default(System.Net.Http.HttpMessageHandler)) { }
public System.Uri BaseAddress { get { return default(System.Uri); } set { } }
public System.Net.Http.Headers.HttpRequestHeaders DefaultRequestHeaders { get { return default(System.Net.Http.Headers.HttpRequestHeaders); } }
public long MaxResponseContentBufferSize { get { return default(long); } set { } }
public System.TimeSpan Timeout { get { return default(System.TimeSpan); } set { } }
public void CancelPendingRequests() { }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> DeleteAsync(string requestUri) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> DeleteAsync(string requestUri, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> DeleteAsync(System.Uri requestUri) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> DeleteAsync(System.Uri requestUri, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); }
protected override void Dispose(bool disposing) { }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(string requestUri) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(string requestUri, System.Net.Http.HttpCompletionOption completionOption) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(string requestUri, System.Net.Http.HttpCompletionOption completionOption, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(string requestUri, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(System.Uri requestUri) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(System.Uri requestUri, System.Net.Http.HttpCompletionOption completionOption) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(System.Uri requestUri, System.Net.Http.HttpCompletionOption completionOption, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(System.Uri requestUri, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); }
public System.Threading.Tasks.Task<byte[]> GetByteArrayAsync(string requestUri) { return default(System.Threading.Tasks.Task<byte[]>); }
public System.Threading.Tasks.Task<byte[]> GetByteArrayAsync(System.Uri requestUri) { return default(System.Threading.Tasks.Task<byte[]>); }
public System.Threading.Tasks.Task<System.IO.Stream> GetStreamAsync(string requestUri) { return default(System.Threading.Tasks.Task<System.IO.Stream>); }
public System.Threading.Tasks.Task<System.IO.Stream> GetStreamAsync(System.Uri requestUri) { return default(System.Threading.Tasks.Task<System.IO.Stream>); }
public System.Threading.Tasks.Task<string> GetStringAsync(string requestUri) { return default(System.Threading.Tasks.Task<string>); }
public System.Threading.Tasks.Task<string> GetStringAsync(System.Uri requestUri) { return default(System.Threading.Tasks.Task<string>); }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PostAsync(string requestUri, System.Net.Http.HttpContent content) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PostAsync(string requestUri, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PostAsync(System.Uri requestUri, System.Net.Http.HttpContent content) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PostAsync(System.Uri requestUri, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PutAsync(string requestUri, System.Net.Http.HttpContent content) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PutAsync(string requestUri, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PutAsync(System.Uri requestUri, System.Net.Http.HttpContent content) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PutAsync(System.Uri requestUri, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Net.Http.HttpCompletionOption completionOption) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Net.Http.HttpCompletionOption completionOption, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); }
public override System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); }
}
public partial class HttpClientHandler : System.Net.Http.HttpMessageHandler
{
public HttpClientHandler() { }
public bool AllowAutoRedirect { get { return default(bool); } set { } }
public System.Net.DecompressionMethods AutomaticDecompression { get { return default(System.Net.DecompressionMethods); } set { } }
public System.Net.Http.ClientCertificateOption ClientCertificateOptions { get { return default(System.Net.Http.ClientCertificateOption); } set { } }
public System.Net.CookieContainer CookieContainer { get { return default(System.Net.CookieContainer); } set { } }
public System.Net.ICredentials Credentials { get { return default(System.Net.ICredentials); } set { } }
public int MaxAutomaticRedirections { get { return default(int); } set { } }
public long MaxRequestContentBufferSize { get { return default(long); } set { } }
public bool PreAuthenticate { get { return default(bool); } set { } }
public System.Net.IWebProxy Proxy { get { return default(System.Net.IWebProxy); } set { } }
public virtual bool SupportsAutomaticDecompression { get { return default(bool); } }
public virtual bool SupportsProxy { get { return default(bool); } }
public virtual bool SupportsRedirectConfiguration { get { return default(bool); } }
public bool UseCookies { get { return default(bool); } set { } }
public bool UseDefaultCredentials { get { return default(bool); } set { } }
public bool UseProxy { get { return default(bool); } set { } }
protected override void Dispose(bool disposing) { }
protected internal override System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); }
}
public enum HttpCompletionOption
{
ResponseContentRead = 0,
ResponseHeadersRead = 1,
}
public abstract partial class HttpContent : System.IDisposable
{
protected HttpContent() { }
public System.Net.Http.Headers.HttpContentHeaders Headers { get { return default(System.Net.Http.Headers.HttpContentHeaders); } }
public System.Threading.Tasks.Task CopyToAsync(System.IO.Stream stream) { return default(System.Threading.Tasks.Task); }
public System.Threading.Tasks.Task CopyToAsync(System.IO.Stream stream, System.Net.TransportContext context) { return default(System.Threading.Tasks.Task); }
protected virtual System.Threading.Tasks.Task<System.IO.Stream> CreateContentReadStreamAsync() { return default(System.Threading.Tasks.Task<System.IO.Stream>); }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public System.Threading.Tasks.Task LoadIntoBufferAsync() { return default(System.Threading.Tasks.Task); }
public System.Threading.Tasks.Task LoadIntoBufferAsync(long maxBufferSize) { return default(System.Threading.Tasks.Task); }
public System.Threading.Tasks.Task<byte[]> ReadAsByteArrayAsync() { return default(System.Threading.Tasks.Task<byte[]>); }
public System.Threading.Tasks.Task<System.IO.Stream> ReadAsStreamAsync() { return default(System.Threading.Tasks.Task<System.IO.Stream>); }
public System.Threading.Tasks.Task<string> ReadAsStringAsync() { return default(System.Threading.Tasks.Task<string>); }
protected abstract System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context);
protected internal abstract bool TryComputeLength(out long length);
}
public abstract partial class HttpMessageHandler : System.IDisposable
{
protected HttpMessageHandler() { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
protected internal abstract System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken);
}
public partial class HttpMessageInvoker : System.IDisposable
{
public HttpMessageInvoker(System.Net.Http.HttpMessageHandler handler) { }
public HttpMessageInvoker(System.Net.Http.HttpMessageHandler handler, bool disposeHandler) { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public virtual System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); }
}
public partial class HttpMethod : System.IEquatable<System.Net.Http.HttpMethod>
{
public HttpMethod(string method) { }
public static System.Net.Http.HttpMethod Delete { get { return default(System.Net.Http.HttpMethod); } }
public static System.Net.Http.HttpMethod Get { get { return default(System.Net.Http.HttpMethod); } }
public static System.Net.Http.HttpMethod Head { get { return default(System.Net.Http.HttpMethod); } }
public string Method { get { return default(string); } }
public static System.Net.Http.HttpMethod Options { get { return default(System.Net.Http.HttpMethod); } }
public static System.Net.Http.HttpMethod Post { get { return default(System.Net.Http.HttpMethod); } }
public static System.Net.Http.HttpMethod Put { get { return default(System.Net.Http.HttpMethod); } }
public static System.Net.Http.HttpMethod Trace { get { return default(System.Net.Http.HttpMethod); } }
public bool Equals(System.Net.Http.HttpMethod other) { return default(bool); }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static bool operator ==(System.Net.Http.HttpMethod left, System.Net.Http.HttpMethod right) { return default(bool); }
public static bool operator !=(System.Net.Http.HttpMethod left, System.Net.Http.HttpMethod right) { return default(bool); }
public override string ToString() { return default(string); }
}
public partial class HttpRequestException : System.Exception
{
public HttpRequestException() { }
public HttpRequestException(string message) { }
public HttpRequestException(string message, System.Exception inner) { }
}
public partial class HttpRequestMessage : System.IDisposable
{
public HttpRequestMessage() { }
public HttpRequestMessage(System.Net.Http.HttpMethod method, string requestUri) { }
public HttpRequestMessage(System.Net.Http.HttpMethod method, System.Uri requestUri) { }
public System.Net.Http.HttpContent Content { get { return default(System.Net.Http.HttpContent); } set { } }
public System.Net.Http.Headers.HttpRequestHeaders Headers { get { return default(System.Net.Http.Headers.HttpRequestHeaders); } }
public System.Net.Http.HttpMethod Method { get { return default(System.Net.Http.HttpMethod); } set { } }
public System.Collections.Generic.IDictionary<string, object> Properties { get { return default(System.Collections.Generic.IDictionary<string, object>); } }
public System.Uri RequestUri { get { return default(System.Uri); } set { } }
public System.Version Version { get { return default(System.Version); } set { } }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public override string ToString() { return default(string); }
}
public partial class HttpResponseMessage : System.IDisposable
{
public HttpResponseMessage() { }
public HttpResponseMessage(System.Net.HttpStatusCode statusCode) { }
public System.Net.Http.HttpContent Content { get { return default(System.Net.Http.HttpContent); } set { } }
public System.Net.Http.Headers.HttpResponseHeaders Headers { get { return default(System.Net.Http.Headers.HttpResponseHeaders); } }
public bool IsSuccessStatusCode { get { return default(bool); } }
public string ReasonPhrase { get { return default(string); } set { } }
public System.Net.Http.HttpRequestMessage RequestMessage { get { return default(System.Net.Http.HttpRequestMessage); } set { } }
public System.Net.HttpStatusCode StatusCode { get { return default(System.Net.HttpStatusCode); } set { } }
public System.Version Version { get { return default(System.Version); } set { } }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public System.Net.Http.HttpResponseMessage EnsureSuccessStatusCode() { return default(System.Net.Http.HttpResponseMessage); }
public override string ToString() { return default(string); }
}
public abstract partial class MessageProcessingHandler : System.Net.Http.DelegatingHandler
{
protected MessageProcessingHandler() { }
protected MessageProcessingHandler(System.Net.Http.HttpMessageHandler innerHandler) { }
protected abstract System.Net.Http.HttpRequestMessage ProcessRequest(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken);
protected abstract System.Net.Http.HttpResponseMessage ProcessResponse(System.Net.Http.HttpResponseMessage response, System.Threading.CancellationToken cancellationToken);
protected internal sealed override System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>); }
}
public partial class MultipartContent : System.Net.Http.HttpContent, System.Collections.Generic.IEnumerable<System.Net.Http.HttpContent>, System.Collections.IEnumerable
{
public MultipartContent() { }
public MultipartContent(string subtype) { }
public MultipartContent(string subtype, string boundary) { }
public virtual void Add(System.Net.Http.HttpContent content) { }
protected override void Dispose(bool disposing) { }
public System.Collections.Generic.IEnumerator<System.Net.Http.HttpContent> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Net.Http.HttpContent>); }
protected override System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context) { return default(System.Threading.Tasks.Task); }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
protected internal override bool TryComputeLength(out long length) { length = default(long); return default(bool); }
}
public partial class MultipartFormDataContent : System.Net.Http.MultipartContent
{
public MultipartFormDataContent() { }
public MultipartFormDataContent(string boundary) { }
public override void Add(System.Net.Http.HttpContent content) { }
public void Add(System.Net.Http.HttpContent content, string name) { }
public void Add(System.Net.Http.HttpContent content, string name, string fileName) { }
}
public partial class StreamContent : System.Net.Http.HttpContent
{
public StreamContent(System.IO.Stream content) { }
public StreamContent(System.IO.Stream content, int bufferSize) { }
protected override System.Threading.Tasks.Task<System.IO.Stream> CreateContentReadStreamAsync() { return default(System.Threading.Tasks.Task<System.IO.Stream>); }
protected override void Dispose(bool disposing) { }
protected override System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context) { return default(System.Threading.Tasks.Task); }
protected internal override bool TryComputeLength(out long length) { length = default(long); return default(bool); }
}
public partial class StringContent : System.Net.Http.ByteArrayContent
{
public StringContent(string content) : base(default(byte[])) { }
public StringContent(string content, System.Text.Encoding encoding) : base(default(byte[])) { }
public StringContent(string content, System.Text.Encoding encoding, string mediaType) : base(default(byte[])) { }
}
}
namespace System.Net.Http.Headers
{
public partial class AuthenticationHeaderValue
{
public AuthenticationHeaderValue(string scheme) { }
public AuthenticationHeaderValue(string scheme, string parameter) { }
public string Parameter { get { return default(string); } }
public string Scheme { get { return default(string); } }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static System.Net.Http.Headers.AuthenticationHeaderValue Parse(string input) { return default(System.Net.Http.Headers.AuthenticationHeaderValue); }
public override string ToString() { return default(string); }
public static bool TryParse(string input, out System.Net.Http.Headers.AuthenticationHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.AuthenticationHeaderValue); return default(bool); }
}
public partial class CacheControlHeaderValue
{
public CacheControlHeaderValue() { }
public System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue> Extensions { get { return default(System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue>); } }
public System.Nullable<System.TimeSpan> MaxAge { get { return default(System.Nullable<System.TimeSpan>); } set { } }
public bool MaxStale { get { return default(bool); } set { } }
public System.Nullable<System.TimeSpan> MaxStaleLimit { get { return default(System.Nullable<System.TimeSpan>); } set { } }
public System.Nullable<System.TimeSpan> MinFresh { get { return default(System.Nullable<System.TimeSpan>); } set { } }
public bool MustRevalidate { get { return default(bool); } set { } }
public bool NoCache { get { return default(bool); } set { } }
public System.Collections.Generic.ICollection<string> NoCacheHeaders { get { return default(System.Collections.Generic.ICollection<string>); } }
public bool NoStore { get { return default(bool); } set { } }
public bool NoTransform { get { return default(bool); } set { } }
public bool OnlyIfCached { get { return default(bool); } set { } }
public bool Private { get { return default(bool); } set { } }
public System.Collections.Generic.ICollection<string> PrivateHeaders { get { return default(System.Collections.Generic.ICollection<string>); } }
public bool ProxyRevalidate { get { return default(bool); } set { } }
public bool Public { get { return default(bool); } set { } }
public System.Nullable<System.TimeSpan> SharedMaxAge { get { return default(System.Nullable<System.TimeSpan>); } set { } }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static System.Net.Http.Headers.CacheControlHeaderValue Parse(string input) { return default(System.Net.Http.Headers.CacheControlHeaderValue); }
public override string ToString() { return default(string); }
public static bool TryParse(string input, out System.Net.Http.Headers.CacheControlHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.CacheControlHeaderValue); return default(bool); }
}
public partial class ContentDispositionHeaderValue
{
protected ContentDispositionHeaderValue(System.Net.Http.Headers.ContentDispositionHeaderValue source) { }
public ContentDispositionHeaderValue(string dispositionType) { }
public System.Nullable<System.DateTimeOffset> CreationDate { get { return default(System.Nullable<System.DateTimeOffset>); } set { } }
public string DispositionType { get { return default(string); } set { } }
public string FileName { get { return default(string); } set { } }
public string FileNameStar { get { return default(string); } set { } }
public System.Nullable<System.DateTimeOffset> ModificationDate { get { return default(System.Nullable<System.DateTimeOffset>); } set { } }
public string Name { get { return default(string); } set { } }
public System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue> Parameters { get { return default(System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue>); } }
public System.Nullable<System.DateTimeOffset> ReadDate { get { return default(System.Nullable<System.DateTimeOffset>); } set { } }
public System.Nullable<long> Size { get { return default(System.Nullable<long>); } set { } }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static System.Net.Http.Headers.ContentDispositionHeaderValue Parse(string input) { return default(System.Net.Http.Headers.ContentDispositionHeaderValue); }
public override string ToString() { return default(string); }
public static bool TryParse(string input, out System.Net.Http.Headers.ContentDispositionHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.ContentDispositionHeaderValue); return default(bool); }
}
public partial class ContentRangeHeaderValue
{
public ContentRangeHeaderValue(long length) { }
public ContentRangeHeaderValue(long from, long to) { }
public ContentRangeHeaderValue(long from, long to, long length) { }
public System.Nullable<long> From { get { return default(System.Nullable<long>); } }
public bool HasLength { get { return default(bool); } }
public bool HasRange { get { return default(bool); } }
public System.Nullable<long> Length { get { return default(System.Nullable<long>); } }
public System.Nullable<long> To { get { return default(System.Nullable<long>); } }
public string Unit { get { return default(string); } set { } }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static System.Net.Http.Headers.ContentRangeHeaderValue Parse(string input) { return default(System.Net.Http.Headers.ContentRangeHeaderValue); }
public override string ToString() { return default(string); }
public static bool TryParse(string input, out System.Net.Http.Headers.ContentRangeHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.ContentRangeHeaderValue); return default(bool); }
}
public partial class EntityTagHeaderValue
{
public EntityTagHeaderValue(string tag) { }
public EntityTagHeaderValue(string tag, bool isWeak) { }
public static System.Net.Http.Headers.EntityTagHeaderValue Any { get { return default(System.Net.Http.Headers.EntityTagHeaderValue); } }
public bool IsWeak { get { return default(bool); } }
public string Tag { get { return default(string); } }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static System.Net.Http.Headers.EntityTagHeaderValue Parse(string input) { return default(System.Net.Http.Headers.EntityTagHeaderValue); }
public override string ToString() { return default(string); }
public static bool TryParse(string input, out System.Net.Http.Headers.EntityTagHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.EntityTagHeaderValue); return default(bool); }
}
public sealed partial class HttpContentHeaders : System.Net.Http.Headers.HttpHeaders
{
internal HttpContentHeaders() { }
public System.Collections.Generic.ICollection<string> Allow { get { return default(System.Collections.Generic.ICollection<string>); } }
public System.Net.Http.Headers.ContentDispositionHeaderValue ContentDisposition { get { return default(System.Net.Http.Headers.ContentDispositionHeaderValue); } set { } }
public System.Collections.Generic.ICollection<string> ContentEncoding { get { return default(System.Collections.Generic.ICollection<string>); } }
public System.Collections.Generic.ICollection<string> ContentLanguage { get { return default(System.Collections.Generic.ICollection<string>); } }
public System.Nullable<long> ContentLength { get { return default(System.Nullable<long>); } set { } }
public System.Uri ContentLocation { get { return default(System.Uri); } set { } }
public byte[] ContentMD5 { get { return default(byte[]); } set { } }
public System.Net.Http.Headers.ContentRangeHeaderValue ContentRange { get { return default(System.Net.Http.Headers.ContentRangeHeaderValue); } set { } }
public System.Net.Http.Headers.MediaTypeHeaderValue ContentType { get { return default(System.Net.Http.Headers.MediaTypeHeaderValue); } set { } }
public System.Nullable<System.DateTimeOffset> Expires { get { return default(System.Nullable<System.DateTimeOffset>); } set { } }
public System.Nullable<System.DateTimeOffset> LastModified { get { return default(System.Nullable<System.DateTimeOffset>); } set { } }
}
public abstract partial class HttpHeaders : System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Collections.Generic.IEnumerable<string>>>, System.Collections.IEnumerable
{
protected HttpHeaders() { }
public void Add(string name, System.Collections.Generic.IEnumerable<string> values) { }
public void Add(string name, string value) { }
public void Clear() { }
public bool Contains(string name) { return default(bool); }
public System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<string, System.Collections.Generic.IEnumerable<string>>> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<string, System.Collections.Generic.IEnumerable<string>>>); }
public System.Collections.Generic.IEnumerable<string> GetValues(string name) { return default(System.Collections.Generic.IEnumerable<string>); }
public bool Remove(string name) { return default(bool); }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
public override string ToString() { return default(string); }
public bool TryAddWithoutValidation(string name, System.Collections.Generic.IEnumerable<string> values) { return default(bool); }
public bool TryAddWithoutValidation(string name, string value) { return default(bool); }
public bool TryGetValues(string name, out System.Collections.Generic.IEnumerable<string> values) { values = default(System.Collections.Generic.IEnumerable<string>); return default(bool); }
}
public sealed partial class HttpHeaderValueCollection<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.IEnumerable where T : class
{
internal HttpHeaderValueCollection() { }
public int Count { get { return default(int); } }
public bool IsReadOnly { get { return default(bool); } }
public void Add(T item) { }
public void Clear() { }
public bool Contains(T item) { return default(bool); }
public void CopyTo(T[] array, int arrayIndex) { }
public System.Collections.Generic.IEnumerator<T> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<T>); }
public void ParseAdd(string input) { }
public bool Remove(T item) { return default(bool); }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
public override string ToString() { return default(string); }
public bool TryParseAdd(string input) { return default(bool); }
}
public sealed partial class HttpRequestHeaders : System.Net.Http.Headers.HttpHeaders
{
internal HttpRequestHeaders() { }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.MediaTypeWithQualityHeaderValue> Accept { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.MediaTypeWithQualityHeaderValue>); } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.StringWithQualityHeaderValue> AcceptCharset { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.StringWithQualityHeaderValue>); } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.StringWithQualityHeaderValue> AcceptEncoding { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.StringWithQualityHeaderValue>); } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.StringWithQualityHeaderValue> AcceptLanguage { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.StringWithQualityHeaderValue>); } }
public System.Net.Http.Headers.AuthenticationHeaderValue Authorization { get { return default(System.Net.Http.Headers.AuthenticationHeaderValue); } set { } }
public System.Net.Http.Headers.CacheControlHeaderValue CacheControl { get { return default(System.Net.Http.Headers.CacheControlHeaderValue); } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<string> Connection { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<string>); } }
public System.Nullable<bool> ConnectionClose { get { return default(System.Nullable<bool>); } set { } }
public System.Nullable<System.DateTimeOffset> Date { get { return default(System.Nullable<System.DateTimeOffset>); } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.NameValueWithParametersHeaderValue> Expect { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.NameValueWithParametersHeaderValue>); } }
public System.Nullable<bool> ExpectContinue { get { return default(System.Nullable<bool>); } set { } }
public string From { get { return default(string); } set { } }
public string Host { get { return default(string); } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.EntityTagHeaderValue> IfMatch { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.EntityTagHeaderValue>); } }
public System.Nullable<System.DateTimeOffset> IfModifiedSince { get { return default(System.Nullable<System.DateTimeOffset>); } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.EntityTagHeaderValue> IfNoneMatch { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.EntityTagHeaderValue>); } }
public System.Net.Http.Headers.RangeConditionHeaderValue IfRange { get { return default(System.Net.Http.Headers.RangeConditionHeaderValue); } set { } }
public System.Nullable<System.DateTimeOffset> IfUnmodifiedSince { get { return default(System.Nullable<System.DateTimeOffset>); } set { } }
public System.Nullable<int> MaxForwards { get { return default(System.Nullable<int>); } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.NameValueHeaderValue> Pragma { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.NameValueHeaderValue>); } }
public System.Net.Http.Headers.AuthenticationHeaderValue ProxyAuthorization { get { return default(System.Net.Http.Headers.AuthenticationHeaderValue); } set { } }
public System.Net.Http.Headers.RangeHeaderValue Range { get { return default(System.Net.Http.Headers.RangeHeaderValue); } set { } }
public System.Uri Referrer { get { return default(System.Uri); } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.TransferCodingWithQualityHeaderValue> TE { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.TransferCodingWithQualityHeaderValue>); } }
public System.Net.Http.Headers.HttpHeaderValueCollection<string> Trailer { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<string>); } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.TransferCodingHeaderValue> TransferEncoding { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.TransferCodingHeaderValue>); } }
public System.Nullable<bool> TransferEncodingChunked { get { return default(System.Nullable<bool>); } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductHeaderValue> Upgrade { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductHeaderValue>); } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductInfoHeaderValue> UserAgent { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductInfoHeaderValue>); } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ViaHeaderValue> Via { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ViaHeaderValue>); } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.WarningHeaderValue> Warning { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.WarningHeaderValue>); } }
}
public sealed partial class HttpResponseHeaders : System.Net.Http.Headers.HttpHeaders
{
internal HttpResponseHeaders() { }
public System.Net.Http.Headers.HttpHeaderValueCollection<string> AcceptRanges { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<string>); } }
public System.Nullable<System.TimeSpan> Age { get { return default(System.Nullable<System.TimeSpan>); } set { } }
public System.Net.Http.Headers.CacheControlHeaderValue CacheControl { get { return default(System.Net.Http.Headers.CacheControlHeaderValue); } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<string> Connection { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<string>); } }
public System.Nullable<bool> ConnectionClose { get { return default(System.Nullable<bool>); } set { } }
public System.Nullable<System.DateTimeOffset> Date { get { return default(System.Nullable<System.DateTimeOffset>); } set { } }
public System.Net.Http.Headers.EntityTagHeaderValue ETag { get { return default(System.Net.Http.Headers.EntityTagHeaderValue); } set { } }
public System.Uri Location { get { return default(System.Uri); } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.NameValueHeaderValue> Pragma { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.NameValueHeaderValue>); } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.AuthenticationHeaderValue> ProxyAuthenticate { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.AuthenticationHeaderValue>); } }
public System.Net.Http.Headers.RetryConditionHeaderValue RetryAfter { get { return default(System.Net.Http.Headers.RetryConditionHeaderValue); } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductInfoHeaderValue> Server { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductInfoHeaderValue>); } }
public System.Net.Http.Headers.HttpHeaderValueCollection<string> Trailer { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<string>); } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.TransferCodingHeaderValue> TransferEncoding { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.TransferCodingHeaderValue>); } }
public System.Nullable<bool> TransferEncodingChunked { get { return default(System.Nullable<bool>); } set { } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductHeaderValue> Upgrade { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductHeaderValue>); } }
public System.Net.Http.Headers.HttpHeaderValueCollection<string> Vary { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<string>); } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ViaHeaderValue> Via { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ViaHeaderValue>); } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.WarningHeaderValue> Warning { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.WarningHeaderValue>); } }
public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.AuthenticationHeaderValue> WwwAuthenticate { get { return default(System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.AuthenticationHeaderValue>); } }
}
public partial class MediaTypeHeaderValue
{
protected MediaTypeHeaderValue(System.Net.Http.Headers.MediaTypeHeaderValue source) { }
public MediaTypeHeaderValue(string mediaType) { }
public string CharSet { get { return default(string); } set { } }
public string MediaType { get { return default(string); } set { } }
public System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue> Parameters { get { return default(System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue>); } }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static System.Net.Http.Headers.MediaTypeHeaderValue Parse(string input) { return default(System.Net.Http.Headers.MediaTypeHeaderValue); }
public override string ToString() { return default(string); }
public static bool TryParse(string input, out System.Net.Http.Headers.MediaTypeHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.MediaTypeHeaderValue); return default(bool); }
}
public sealed partial class MediaTypeWithQualityHeaderValue : System.Net.Http.Headers.MediaTypeHeaderValue
{
public MediaTypeWithQualityHeaderValue(string mediaType) : base(default(System.Net.Http.Headers.MediaTypeHeaderValue)) { }
public MediaTypeWithQualityHeaderValue(string mediaType, double quality) : base(default(System.Net.Http.Headers.MediaTypeHeaderValue)) { }
public System.Nullable<double> Quality { get { return default(System.Nullable<double>); } set { } }
public static new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue Parse(string input) { return default(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue); }
public static bool TryParse(string input, out System.Net.Http.Headers.MediaTypeWithQualityHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue); return default(bool); }
}
public partial class NameValueHeaderValue
{
protected NameValueHeaderValue(System.Net.Http.Headers.NameValueHeaderValue source) { }
public NameValueHeaderValue(string name) { }
public NameValueHeaderValue(string name, string value) { }
public string Name { get { return default(string); } }
public string Value { get { return default(string); } set { } }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static System.Net.Http.Headers.NameValueHeaderValue Parse(string input) { return default(System.Net.Http.Headers.NameValueHeaderValue); }
public override string ToString() { return default(string); }
public static bool TryParse(string input, out System.Net.Http.Headers.NameValueHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.NameValueHeaderValue); return default(bool); }
}
public partial class NameValueWithParametersHeaderValue : System.Net.Http.Headers.NameValueHeaderValue
{
protected NameValueWithParametersHeaderValue(System.Net.Http.Headers.NameValueWithParametersHeaderValue source) : base(default(string)) { }
public NameValueWithParametersHeaderValue(string name) : base(default(string)) { }
public NameValueWithParametersHeaderValue(string name, string value) : base(default(string)) { }
public System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue> Parameters { get { return default(System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue>); } }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static new System.Net.Http.Headers.NameValueWithParametersHeaderValue Parse(string input) { return default(System.Net.Http.Headers.NameValueWithParametersHeaderValue); }
public override string ToString() { return default(string); }
public static bool TryParse(string input, out System.Net.Http.Headers.NameValueWithParametersHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.NameValueWithParametersHeaderValue); return default(bool); }
}
public partial class ProductHeaderValue
{
public ProductHeaderValue(string name) { }
public ProductHeaderValue(string name, string version) { }
public string Name { get { return default(string); } }
public string Version { get { return default(string); } }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static System.Net.Http.Headers.ProductHeaderValue Parse(string input) { return default(System.Net.Http.Headers.ProductHeaderValue); }
public override string ToString() { return default(string); }
public static bool TryParse(string input, out System.Net.Http.Headers.ProductHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.ProductHeaderValue); return default(bool); }
}
public partial class ProductInfoHeaderValue
{
public ProductInfoHeaderValue(System.Net.Http.Headers.ProductHeaderValue product) { }
public ProductInfoHeaderValue(string comment) { }
public ProductInfoHeaderValue(string productName, string productVersion) { }
public string Comment { get { return default(string); } }
public System.Net.Http.Headers.ProductHeaderValue Product { get { return default(System.Net.Http.Headers.ProductHeaderValue); } }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static System.Net.Http.Headers.ProductInfoHeaderValue Parse(string input) { return default(System.Net.Http.Headers.ProductInfoHeaderValue); }
public override string ToString() { return default(string); }
public static bool TryParse(string input, out System.Net.Http.Headers.ProductInfoHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.ProductInfoHeaderValue); return default(bool); }
}
public partial class RangeConditionHeaderValue
{
public RangeConditionHeaderValue(System.DateTimeOffset date) { }
public RangeConditionHeaderValue(System.Net.Http.Headers.EntityTagHeaderValue entityTag) { }
public RangeConditionHeaderValue(string entityTag) { }
public System.Nullable<System.DateTimeOffset> Date { get { return default(System.Nullable<System.DateTimeOffset>); } }
public System.Net.Http.Headers.EntityTagHeaderValue EntityTag { get { return default(System.Net.Http.Headers.EntityTagHeaderValue); } }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static System.Net.Http.Headers.RangeConditionHeaderValue Parse(string input) { return default(System.Net.Http.Headers.RangeConditionHeaderValue); }
public override string ToString() { return default(string); }
public static bool TryParse(string input, out System.Net.Http.Headers.RangeConditionHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.RangeConditionHeaderValue); return default(bool); }
}
public partial class RangeHeaderValue
{
public RangeHeaderValue() { }
public RangeHeaderValue(System.Nullable<long> from, System.Nullable<long> to) { }
public System.Collections.Generic.ICollection<System.Net.Http.Headers.RangeItemHeaderValue> Ranges { get { return default(System.Collections.Generic.ICollection<System.Net.Http.Headers.RangeItemHeaderValue>); } }
public string Unit { get { return default(string); } set { } }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static System.Net.Http.Headers.RangeHeaderValue Parse(string input) { return default(System.Net.Http.Headers.RangeHeaderValue); }
public override string ToString() { return default(string); }
public static bool TryParse(string input, out System.Net.Http.Headers.RangeHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.RangeHeaderValue); return default(bool); }
}
public partial class RangeItemHeaderValue
{
public RangeItemHeaderValue(System.Nullable<long> from, System.Nullable<long> to) { }
public System.Nullable<long> From { get { return default(System.Nullable<long>); } }
public System.Nullable<long> To { get { return default(System.Nullable<long>); } }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
public override string ToString() { return default(string); }
}
public partial class RetryConditionHeaderValue
{
public RetryConditionHeaderValue(System.DateTimeOffset date) { }
public RetryConditionHeaderValue(System.TimeSpan delta) { }
public System.Nullable<System.DateTimeOffset> Date { get { return default(System.Nullable<System.DateTimeOffset>); } }
public System.Nullable<System.TimeSpan> Delta { get { return default(System.Nullable<System.TimeSpan>); } }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static System.Net.Http.Headers.RetryConditionHeaderValue Parse(string input) { return default(System.Net.Http.Headers.RetryConditionHeaderValue); }
public override string ToString() { return default(string); }
public static bool TryParse(string input, out System.Net.Http.Headers.RetryConditionHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.RetryConditionHeaderValue); return default(bool); }
}
public partial class StringWithQualityHeaderValue
{
public StringWithQualityHeaderValue(string value) { }
public StringWithQualityHeaderValue(string value, double quality) { }
public System.Nullable<double> Quality { get { return default(System.Nullable<double>); } }
public string Value { get { return default(string); } }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static System.Net.Http.Headers.StringWithQualityHeaderValue Parse(string input) { return default(System.Net.Http.Headers.StringWithQualityHeaderValue); }
public override string ToString() { return default(string); }
public static bool TryParse(string input, out System.Net.Http.Headers.StringWithQualityHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.StringWithQualityHeaderValue); return default(bool); }
}
public partial class TransferCodingHeaderValue
{
protected TransferCodingHeaderValue(System.Net.Http.Headers.TransferCodingHeaderValue source) { }
public TransferCodingHeaderValue(string value) { }
public System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue> Parameters { get { return default(System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue>); } }
public string Value { get { return default(string); } }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static System.Net.Http.Headers.TransferCodingHeaderValue Parse(string input) { return default(System.Net.Http.Headers.TransferCodingHeaderValue); }
public override string ToString() { return default(string); }
public static bool TryParse(string input, out System.Net.Http.Headers.TransferCodingHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.TransferCodingHeaderValue); return default(bool); }
}
public sealed partial class TransferCodingWithQualityHeaderValue : System.Net.Http.Headers.TransferCodingHeaderValue
{
public TransferCodingWithQualityHeaderValue(string value) : base(default(System.Net.Http.Headers.TransferCodingHeaderValue)) { }
public TransferCodingWithQualityHeaderValue(string value, double quality) : base(default(System.Net.Http.Headers.TransferCodingHeaderValue)) { }
public System.Nullable<double> Quality { get { return default(System.Nullable<double>); } set { } }
public static new System.Net.Http.Headers.TransferCodingWithQualityHeaderValue Parse(string input) { return default(System.Net.Http.Headers.TransferCodingWithQualityHeaderValue); }
public static bool TryParse(string input, out System.Net.Http.Headers.TransferCodingWithQualityHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.TransferCodingWithQualityHeaderValue); return default(bool); }
}
public partial class ViaHeaderValue
{
public ViaHeaderValue(string protocolVersion, string receivedBy) { }
public ViaHeaderValue(string protocolVersion, string receivedBy, string protocolName) { }
public ViaHeaderValue(string protocolVersion, string receivedBy, string protocolName, string comment) { }
public string Comment { get { return default(string); } }
public string ProtocolName { get { return default(string); } }
public string ProtocolVersion { get { return default(string); } }
public string ReceivedBy { get { return default(string); } }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static System.Net.Http.Headers.ViaHeaderValue Parse(string input) { return default(System.Net.Http.Headers.ViaHeaderValue); }
public override string ToString() { return default(string); }
public static bool TryParse(string input, out System.Net.Http.Headers.ViaHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.ViaHeaderValue); return default(bool); }
}
public partial class WarningHeaderValue
{
public WarningHeaderValue(int code, string agent, string text) { }
public WarningHeaderValue(int code, string agent, string text, System.DateTimeOffset date) { }
public string Agent { get { return default(string); } }
public int Code { get { return default(int); } }
public System.Nullable<System.DateTimeOffset> Date { get { return default(System.Nullable<System.DateTimeOffset>); } }
public string Text { get { return default(string); } }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static System.Net.Http.Headers.WarningHeaderValue Parse(string input) { return default(System.Net.Http.Headers.WarningHeaderValue); }
public override string ToString() { return default(string); }
public static bool TryParse(string input, out System.Net.Http.Headers.WarningHeaderValue parsedValue) { parsedValue = default(System.Net.Http.Headers.WarningHeaderValue); return default(bool); }
}
}
| |
using System;
using System.Collections;
using UnityEngine;
namespace UniRx
{
#if !(UNITY_METRO || UNITY_WP8) && (UNITY_4_4 || UNITY_4_3 || UNITY_4_2 || UNITY_4_1 || UNITY_4_0_1 || UNITY_4_0 || UNITY_3_5 || UNITY_3_4 || UNITY_3_3 || UNITY_3_2 || UNITY_3_1 || UNITY_3_0_0 || UNITY_3_0 || UNITY_2_6_1 || UNITY_2_6)
// Fallback for Unity versions below 4.5
using Hash = System.Collections.Hashtable;
using HashEntry = System.Collections.DictionaryEntry;
#else
// Unity 4.5 release notes:
// WWW: deprecated 'WWW(string url, byte[] postData, Hashtable headers)',
// use 'public WWW(string url, byte[] postData, Dictionary<string, string> headers)' instead.
using Hash = System.Collections.Generic.Dictionary<string, string>;
using HashEntry = System.Collections.Generic.KeyValuePair<string, string>;
#endif
public static partial class ObservableWWW
{
public static IObservable<string> Get(string url, Hash headers = null, IProgress<float> progress = null)
{
return Observable.FromCoroutine<string>((observer, cancellation) => FetchText(new WWW(url, null, (headers ?? new Hash())), observer, progress, cancellation));
}
public static IObservable<byte[]> GetAndGetBytes(string url, Hash headers = null, IProgress<float> progress = null)
{
return Observable.FromCoroutine<byte[]>((observer, cancellation) => FetchBytes(new WWW(url, null, (headers ?? new Hash())), observer, progress, cancellation));
}
public static IObservable<WWW> GetWWW(string url, Hash headers = null, IProgress<float> progress = null)
{
return Observable.FromCoroutine<WWW>((observer, cancellation) => Fetch(new WWW(url, null, (headers ?? new Hash())), observer, progress, cancellation));
}
public static IObservable<string> Post(string url, byte[] postData, IProgress<float> progress = null)
{
return Observable.FromCoroutine<string>((observer, cancellation) => FetchText(new WWW(url, postData), observer, progress, cancellation));
}
public static IObservable<string> Post(string url, byte[] postData, Hash headers, IProgress<float> progress = null)
{
return Observable.FromCoroutine<string>((observer, cancellation) => FetchText(new WWW(url, postData, headers), observer, progress, cancellation));
}
public static IObservable<string> Post(string url, WWWForm content, IProgress<float> progress = null)
{
return Observable.FromCoroutine<string>((observer, cancellation) => FetchText(new WWW(url, content), observer, progress, cancellation));
}
public static IObservable<string> Post(string url, WWWForm content, Hash headers, IProgress<float> progress = null)
{
var contentHeaders = content.headers;
return Observable.FromCoroutine<string>((observer, cancellation) => FetchText(new WWW(url, content.data, MergeHash(contentHeaders, headers)), observer, progress, cancellation));
}
public static IObservable<byte[]> PostAndGetBytes(string url, byte[] postData, IProgress<float> progress = null)
{
return Observable.FromCoroutine<byte[]>((observer, cancellation) => FetchBytes(new WWW(url, postData), observer, progress, cancellation));
}
public static IObservable<byte[]> PostAndGetBytes(string url, byte[] postData, Hash headers, IProgress<float> progress = null)
{
return Observable.FromCoroutine<byte[]>((observer, cancellation) => FetchBytes(new WWW(url, postData, headers), observer, progress, cancellation));
}
public static IObservable<byte[]> PostAndGetBytes(string url, WWWForm content, IProgress<float> progress = null)
{
return Observable.FromCoroutine<byte[]>((observer, cancellation) => FetchBytes(new WWW(url, content), observer, progress, cancellation));
}
public static IObservable<byte[]> PostAndGetBytes(string url, WWWForm content, Hash headers, IProgress<float> progress = null)
{
var contentHeaders = content.headers;
return Observable.FromCoroutine<byte[]>((observer, cancellation) => FetchBytes(new WWW(url, content.data, MergeHash(contentHeaders, headers)), observer, progress, cancellation));
}
public static IObservable<WWW> PostWWW(string url, byte[] postData, IProgress<float> progress = null)
{
return Observable.FromCoroutine<WWW>((observer, cancellation) => Fetch(new WWW(url, postData), observer, progress, cancellation));
}
public static IObservable<WWW> PostWWW(string url, byte[] postData, Hash headers, IProgress<float> progress = null)
{
return Observable.FromCoroutine<WWW>((observer, cancellation) => Fetch(new WWW(url, postData, headers), observer, progress, cancellation));
}
public static IObservable<WWW> PostWWW(string url, WWWForm content, IProgress<float> progress = null)
{
return Observable.FromCoroutine<WWW>((observer, cancellation) => Fetch(new WWW(url, content), observer, progress, cancellation));
}
public static IObservable<WWW> PostWWW(string url, WWWForm content, Hash headers, IProgress<float> progress = null)
{
var contentHeaders = content.headers;
return Observable.FromCoroutine<WWW>((observer, cancellation) => Fetch(new WWW(url, content.data, MergeHash(contentHeaders, headers)), observer, progress, cancellation));
}
public static IObservable<AssetBundle> LoadFromCacheOrDownload(string url, int version, IProgress<float> progress = null)
{
return Observable.FromCoroutine<AssetBundle>((observer, cancellation) => FetchAssetBundle(WWW.LoadFromCacheOrDownload(url, version), observer, progress, cancellation));
}
public static IObservable<AssetBundle> LoadFromCacheOrDownload(string url, int version, uint crc, IProgress<float> progress = null)
{
return Observable.FromCoroutine<AssetBundle>((observer, cancellation) => FetchAssetBundle(WWW.LoadFromCacheOrDownload(url, version, crc), observer, progress, cancellation));
}
// over Unity5 supports Hash128
#if !(UNITY_4_6 || UNITY_4_5 || UNITY_4_4 || UNITY_4_3 || UNITY_4_2 || UNITY_4_1 || UNITY_4_0_1 || UNITY_4_0 || UNITY_3_5 || UNITY_3_4 || UNITY_3_3 || UNITY_3_2 || UNITY_3_1 || UNITY_3_0_0 || UNITY_3_0 || UNITY_2_6_1 || UNITY_2_6)
public static IObservable<AssetBundle> LoadFromCacheOrDownload(string url, Hash128 hash128, IProgress<float> progress = null)
{
return Observable.FromCoroutine<AssetBundle>((observer, cancellation) => FetchAssetBundle(WWW.LoadFromCacheOrDownload(url, hash128), observer, progress, cancellation));
}
public static IObservable<AssetBundle> LoadFromCacheOrDownload(string url, Hash128 hash128, uint crc, IProgress<float> progress = null)
{
return Observable.FromCoroutine<AssetBundle>((observer, cancellation) => FetchAssetBundle(WWW.LoadFromCacheOrDownload(url, hash128, crc), observer, progress, cancellation));
}
#endif
// over 4.5, Hash define is Dictionary.
// below Unity 4.5, WWW only supports Hashtable.
// Unity 4.5, 4.6 WWW supports Dictionary and [Obsolete]Hashtable but WWWForm.content is Hashtable.
// Unity 5.0 WWW only supports Dictionary and WWWForm.content is also Dictionary.
#if !(UNITY_METRO || UNITY_WP8) && (UNITY_4_5 || UNITY_4_6)
static Hash MergeHash(Hashtable wwwFormHeaders, Hash externalHeaders)
{
var newHeaders = new Hash();
foreach (DictionaryEntry item in wwwFormHeaders)
{
newHeaders.Add(item.Key.ToString(), item.Value.ToString());
}
foreach (HashEntry item in externalHeaders)
{
newHeaders.Add(item.Key, item.Value);
}
return newHeaders;
}
#else
static Hash MergeHash(Hash wwwFormHeaders, Hash externalHeaders)
{
foreach (HashEntry item in externalHeaders)
{
wwwFormHeaders[item.Key] = item.Value;
}
return wwwFormHeaders;
}
#endif
static IEnumerator Fetch(WWW www, IObserver<WWW> observer, IProgress<float> reportProgress, CancellationToken cancel)
{
using (www)
{
while (!www.isDone && !cancel.IsCancellationRequested)
{
if (reportProgress != null)
{
try
{
reportProgress.Report(www.progress);
}
catch (Exception ex)
{
observer.OnError(ex);
yield break;
}
}
yield return null;
}
if (cancel.IsCancellationRequested) yield break;
if (reportProgress != null)
{
try
{
reportProgress.Report(www.progress);
}
catch (Exception ex)
{
observer.OnError(ex);
yield break;
}
}
if (!string.IsNullOrEmpty(www.error))
{
observer.OnError(new WWWErrorException(www));
}
else
{
observer.OnNext(www);
observer.OnCompleted();
}
}
}
static IEnumerator FetchText(WWW www, IObserver<string> observer, IProgress<float> reportProgress, CancellationToken cancel)
{
using (www)
{
while (!www.isDone && !cancel.IsCancellationRequested)
{
if (reportProgress != null)
{
try
{
reportProgress.Report(www.progress);
}
catch (Exception ex)
{
observer.OnError(ex);
yield break;
}
}
yield return null;
}
if (cancel.IsCancellationRequested) yield break;
if (reportProgress != null)
{
try
{
reportProgress.Report(www.progress);
}
catch (Exception ex)
{
observer.OnError(ex);
yield break;
}
}
if (!string.IsNullOrEmpty(www.error))
{
observer.OnError(new WWWErrorException(www));
}
else
{
observer.OnNext(www.text);
observer.OnCompleted();
}
}
}
static IEnumerator FetchBytes(WWW www, IObserver<byte[]> observer, IProgress<float> reportProgress, CancellationToken cancel)
{
using (www)
{
while (!www.isDone && !cancel.IsCancellationRequested)
{
if (reportProgress != null)
{
try
{
reportProgress.Report(www.progress);
}
catch (Exception ex)
{
observer.OnError(ex);
yield break;
}
}
yield return null;
}
if (cancel.IsCancellationRequested) yield break;
if (reportProgress != null)
{
try
{
reportProgress.Report(www.progress);
}
catch (Exception ex)
{
observer.OnError(ex);
yield break;
}
}
if (!string.IsNullOrEmpty(www.error))
{
observer.OnError(new WWWErrorException(www));
}
else
{
observer.OnNext(www.bytes);
observer.OnCompleted();
}
}
}
static IEnumerator FetchAssetBundle(WWW www, IObserver<AssetBundle> observer, IProgress<float> reportProgress, CancellationToken cancel)
{
using (www)
{
while (!www.isDone && !cancel.IsCancellationRequested)
{
if (reportProgress != null)
{
try
{
reportProgress.Report(www.progress);
}
catch (Exception ex)
{
observer.OnError(ex);
yield break;
}
}
yield return null;
}
if (cancel.IsCancellationRequested) yield break;
if (reportProgress != null)
{
try
{
reportProgress.Report(www.progress);
}
catch (Exception ex)
{
observer.OnError(ex);
yield break;
}
}
if (!string.IsNullOrEmpty(www.error))
{
observer.OnError(new WWWErrorException(www));
}
else
{
observer.OnNext(www.assetBundle);
observer.OnCompleted();
}
}
}
}
public class WWWErrorException : Exception
{
public string RawErrorMessage { get; private set; }
public bool HasResponse { get; private set; }
public System.Net.HttpStatusCode StatusCode { get; private set; }
public System.Collections.Generic.Dictionary<string, string> ResponseHeaders { get; private set; }
public WWW WWW { get; private set; }
public WWWErrorException(WWW www)
{
this.WWW = www;
this.RawErrorMessage = www.error;
this.ResponseHeaders = www.responseHeaders;
this.HasResponse = false;
var splitted = RawErrorMessage.Split(' ');
if (splitted.Length != 0)
{
int statusCode;
if (int.TryParse(splitted[0], out statusCode))
{
this.HasResponse = true;
this.StatusCode = (System.Net.HttpStatusCode)statusCode;
}
}
}
public override string ToString()
{
return RawErrorMessage;
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Converters;
namespace Twilio.Rest.Api.V2010.Account.IncomingPhoneNumber
{
/// <summary>
/// ReadLocalOptions
/// </summary>
public class ReadLocalOptions : ReadOptions<LocalResource>
{
/// <summary>
/// The SID of the Account that created the resources to read
/// </summary>
public string PathAccountSid { get; set; }
/// <summary>
/// Whether to include new phone numbers
/// </summary>
public bool? Beta { get; set; }
/// <summary>
/// A string that identifies the resources to read
/// </summary>
public string FriendlyName { get; set; }
/// <summary>
/// The phone numbers of the resources to read
/// </summary>
public Types.PhoneNumber PhoneNumber { get; set; }
/// <summary>
/// Include phone numbers based on their origin. By default, phone numbers of all origin are included.
/// </summary>
public string Origin { get; set; }
/// <summary>
/// Generate the necessary parameters
/// </summary>
public override List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Beta != null)
{
p.Add(new KeyValuePair<string, string>("Beta", Beta.Value.ToString().ToLower()));
}
if (FriendlyName != null)
{
p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName));
}
if (PhoneNumber != null)
{
p.Add(new KeyValuePair<string, string>("PhoneNumber", PhoneNumber.ToString()));
}
if (Origin != null)
{
p.Add(new KeyValuePair<string, string>("Origin", Origin));
}
if (PageSize != null)
{
p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
}
return p;
}
}
/// <summary>
/// CreateLocalOptions
/// </summary>
public class CreateLocalOptions : IOptions<LocalResource>
{
/// <summary>
/// The SID of the Account that will create the resource
/// </summary>
public string PathAccountSid { get; set; }
/// <summary>
/// The phone number to purchase in E.164 format
/// </summary>
public Types.PhoneNumber PhoneNumber { get; }
/// <summary>
/// The API version to use for incoming calls made to the new phone number
/// </summary>
public string ApiVersion { get; set; }
/// <summary>
/// A string to describe the new phone number
/// </summary>
public string FriendlyName { get; set; }
/// <summary>
/// The SID of the application to handle SMS messages
/// </summary>
public string SmsApplicationSid { get; set; }
/// <summary>
/// The HTTP method we use to call status_callback
/// </summary>
public Twilio.Http.HttpMethod SmsFallbackMethod { get; set; }
/// <summary>
/// The URL we call when an error occurs while executing TwiML
/// </summary>
public Uri SmsFallbackUrl { get; set; }
/// <summary>
/// The HTTP method to use with sms url
/// </summary>
public Twilio.Http.HttpMethod SmsMethod { get; set; }
/// <summary>
/// The URL we should call when the new phone number receives an incoming SMS message
/// </summary>
public Uri SmsUrl { get; set; }
/// <summary>
/// The URL we should call to send status information to your application
/// </summary>
public Uri StatusCallback { get; set; }
/// <summary>
/// HTTP method we should use to call status_callback
/// </summary>
public Twilio.Http.HttpMethod StatusCallbackMethod { get; set; }
/// <summary>
/// The SID of the application to handle the new phone number
/// </summary>
public string VoiceApplicationSid { get; set; }
/// <summary>
/// Whether to lookup the caller's name
/// </summary>
public bool? VoiceCallerIdLookup { get; set; }
/// <summary>
/// The HTTP method used with voice_fallback_url
/// </summary>
public Twilio.Http.HttpMethod VoiceFallbackMethod { get; set; }
/// <summary>
/// The URL we will call when an error occurs in TwiML
/// </summary>
public Uri VoiceFallbackUrl { get; set; }
/// <summary>
/// The HTTP method used with the voice_url
/// </summary>
public Twilio.Http.HttpMethod VoiceMethod { get; set; }
/// <summary>
/// The URL we should call when the phone number receives a call
/// </summary>
public Uri VoiceUrl { get; set; }
/// <summary>
/// The SID of the Identity resource to associate with the new phone number
/// </summary>
public string IdentitySid { get; set; }
/// <summary>
/// The SID of the Address resource associated with the phone number
/// </summary>
public string AddressSid { get; set; }
/// <summary>
/// Displays if emergency calling is enabled for this number.
/// </summary>
public LocalResource.EmergencyStatusEnum EmergencyStatus { get; set; }
/// <summary>
/// The emergency address configuration to use for emergency calling
/// </summary>
public string EmergencyAddressSid { get; set; }
/// <summary>
/// SID of the trunk to handle calls to the new phone number
/// </summary>
public string TrunkSid { get; set; }
/// <summary>
/// Incoming call type: fax or voice
/// </summary>
public LocalResource.VoiceReceiveModeEnum VoiceReceiveMode { get; set; }
/// <summary>
/// The SID of the Bundle resource associated with number
/// </summary>
public string BundleSid { get; set; }
/// <summary>
/// Construct a new CreateLocalOptions
/// </summary>
/// <param name="phoneNumber"> The phone number to purchase in E.164 format </param>
public CreateLocalOptions(Types.PhoneNumber phoneNumber)
{
PhoneNumber = phoneNumber;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (PhoneNumber != null)
{
p.Add(new KeyValuePair<string, string>("PhoneNumber", PhoneNumber.ToString()));
}
if (ApiVersion != null)
{
p.Add(new KeyValuePair<string, string>("ApiVersion", ApiVersion));
}
if (FriendlyName != null)
{
p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName));
}
if (SmsApplicationSid != null)
{
p.Add(new KeyValuePair<string, string>("SmsApplicationSid", SmsApplicationSid.ToString()));
}
if (SmsFallbackMethod != null)
{
p.Add(new KeyValuePair<string, string>("SmsFallbackMethod", SmsFallbackMethod.ToString()));
}
if (SmsFallbackUrl != null)
{
p.Add(new KeyValuePair<string, string>("SmsFallbackUrl", Serializers.Url(SmsFallbackUrl)));
}
if (SmsMethod != null)
{
p.Add(new KeyValuePair<string, string>("SmsMethod", SmsMethod.ToString()));
}
if (SmsUrl != null)
{
p.Add(new KeyValuePair<string, string>("SmsUrl", Serializers.Url(SmsUrl)));
}
if (StatusCallback != null)
{
p.Add(new KeyValuePair<string, string>("StatusCallback", Serializers.Url(StatusCallback)));
}
if (StatusCallbackMethod != null)
{
p.Add(new KeyValuePair<string, string>("StatusCallbackMethod", StatusCallbackMethod.ToString()));
}
if (VoiceApplicationSid != null)
{
p.Add(new KeyValuePair<string, string>("VoiceApplicationSid", VoiceApplicationSid.ToString()));
}
if (VoiceCallerIdLookup != null)
{
p.Add(new KeyValuePair<string, string>("VoiceCallerIdLookup", VoiceCallerIdLookup.Value.ToString().ToLower()));
}
if (VoiceFallbackMethod != null)
{
p.Add(new KeyValuePair<string, string>("VoiceFallbackMethod", VoiceFallbackMethod.ToString()));
}
if (VoiceFallbackUrl != null)
{
p.Add(new KeyValuePair<string, string>("VoiceFallbackUrl", Serializers.Url(VoiceFallbackUrl)));
}
if (VoiceMethod != null)
{
p.Add(new KeyValuePair<string, string>("VoiceMethod", VoiceMethod.ToString()));
}
if (VoiceUrl != null)
{
p.Add(new KeyValuePair<string, string>("VoiceUrl", Serializers.Url(VoiceUrl)));
}
if (IdentitySid != null)
{
p.Add(new KeyValuePair<string, string>("IdentitySid", IdentitySid.ToString()));
}
if (AddressSid != null)
{
p.Add(new KeyValuePair<string, string>("AddressSid", AddressSid.ToString()));
}
if (EmergencyStatus != null)
{
p.Add(new KeyValuePair<string, string>("EmergencyStatus", EmergencyStatus.ToString()));
}
if (EmergencyAddressSid != null)
{
p.Add(new KeyValuePair<string, string>("EmergencyAddressSid", EmergencyAddressSid.ToString()));
}
if (TrunkSid != null)
{
p.Add(new KeyValuePair<string, string>("TrunkSid", TrunkSid.ToString()));
}
if (VoiceReceiveMode != null)
{
p.Add(new KeyValuePair<string, string>("VoiceReceiveMode", VoiceReceiveMode.ToString()));
}
if (BundleSid != null)
{
p.Add(new KeyValuePair<string, string>("BundleSid", BundleSid.ToString()));
}
return p;
}
}
}
| |
/*
* 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.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using ProtoBuf;
using QuantConnect.Logging;
using QuantConnect.Util;
using static QuantConnect.StringExtensions;
namespace QuantConnect.Data.Market
{
/// <summary>
/// QuoteBar class for second and minute resolution data:
/// An OHLC implementation of the QuantConnect BaseData class with parameters for candles.
/// </summary>
[ProtoContract(SkipConstructor = true)]
public class QuoteBar : BaseData, IBaseDataBar
{
// scale factor used in QC equity/forex data files
private const decimal _scaleFactor = 1 / 10000m;
/// <summary>
/// Average bid size
/// </summary>
[ProtoMember(201)]
public decimal LastBidSize { get; set; }
/// <summary>
/// Average ask size
/// </summary>
[ProtoMember(202)]
public decimal LastAskSize { get; set; }
/// <summary>
/// Bid OHLC
/// </summary>
[ProtoMember(203)]
public Bar Bid { get; set; }
/// <summary>
/// Ask OHLC
/// </summary>
[ProtoMember(204)]
public Bar Ask { get; set; }
/// <summary>
/// Opening price of the bar: Defined as the price at the start of the time period.
/// </summary>
public decimal Open
{
get
{
if (Bid != null && Ask != null)
{
if (Bid.Open != 0m && Ask.Open != 0m)
return (Bid.Open + Ask.Open) / 2m;
if (Bid.Open != 0)
return Bid.Open;
if (Ask.Open != 0)
return Ask.Open;
return 0m;
}
if (Bid != null)
{
return Bid.Open;
}
if (Ask != null)
{
return Ask.Open;
}
return 0m;
}
}
/// <summary>
/// High price of the QuoteBar during the time period.
/// </summary>
public decimal High
{
get
{
if (Bid != null && Ask != null)
{
if (Bid.High != 0m && Ask.High != 0m)
return (Bid.High + Ask.High) / 2m;
if (Bid.High != 0)
return Bid.High;
if (Ask.High != 0)
return Ask.High;
return 0m;
}
if (Bid != null)
{
return Bid.High;
}
if (Ask != null)
{
return Ask.High;
}
return 0m;
}
}
/// <summary>
/// Low price of the QuoteBar during the time period.
/// </summary>
public decimal Low
{
get
{
if (Bid != null && Ask != null)
{
if (Bid.Low != 0m && Ask.Low != 0m)
return (Bid.Low + Ask.Low) / 2m;
if (Bid.Low != 0)
return Bid.Low;
if (Ask.Low != 0)
return Ask.Low;
return 0m;
}
if (Bid != null)
{
return Bid.Low;
}
if (Ask != null)
{
return Ask.Low;
}
return 0m;
}
}
/// <summary>
/// Closing price of the QuoteBar. Defined as the price at Start Time + TimeSpan.
/// </summary>
public decimal Close
{
get
{
if (Bid != null && Ask != null)
{
if (Bid.Close != 0m && Ask.Close != 0m)
return (Bid.Close + Ask.Close) / 2m;
if (Bid.Close != 0)
return Bid.Close;
if (Ask.Close != 0)
return Ask.Close;
return 0m;
}
if (Bid != null)
{
return Bid.Close;
}
if (Ask != null)
{
return Ask.Close;
}
return Value;
}
}
/// <summary>
/// The closing time of this bar, computed via the Time and Period
/// </summary>
public override DateTime EndTime
{
get { return Time + Period; }
set { Period = value - Time; }
}
/// <summary>
/// The period of this quote bar, (second, minute, daily, ect...)
/// </summary>
[ProtoMember(205)]
public TimeSpan Period { get; set; }
/// <summary>
/// Default initializer to setup an empty quotebar.
/// </summary>
public QuoteBar()
{
Symbol = Symbol.Empty;
Time = new DateTime();
Bid = new Bar();
Ask = new Bar();
Value = 0;
Period = TimeSpan.FromMinutes(1);
DataType = MarketDataType.QuoteBar;
}
/// <summary>
/// Initialize Quote Bar with Bid(OHLC) and Ask(OHLC) Values:
/// </summary>
/// <param name="time">DateTime Timestamp of the bar</param>
/// <param name="symbol">Market MarketType Symbol</param>
/// <param name="bid">Bid OLHC bar</param>
/// <param name="lastBidSize">Average bid size over period</param>
/// <param name="ask">Ask OLHC bar</param>
/// <param name="lastAskSize">Average ask size over period</param>
/// <param name="period">The period of this bar, specify null for default of 1 minute</param>
public QuoteBar(DateTime time, Symbol symbol, IBar bid, decimal lastBidSize, IBar ask, decimal lastAskSize, TimeSpan? period = null)
{
Symbol = symbol;
Time = time;
Bid = bid == null ? null : new Bar(bid.Open, bid.High, bid.Low, bid.Close);
Ask = ask == null ? null : new Bar(ask.Open, ask.High, ask.Low, ask.Close);
if (Bid != null) LastBidSize = lastBidSize;
if (Ask != null) LastAskSize = lastAskSize;
Value = Close;
Period = period ?? TimeSpan.FromMinutes(1);
DataType = MarketDataType.QuoteBar;
}
/// <summary>
/// Update the quotebar - build the bar from this pricing information:
/// </summary>
/// <param name="lastTrade">The last trade price</param>
/// <param name="bidPrice">Current bid price</param>
/// <param name="askPrice">Current asking price</param>
/// <param name="volume">Volume of this trade</param>
/// <param name="bidSize">The size of the current bid, if available, if not, pass 0</param>
/// <param name="askSize">The size of the current ask, if available, if not, pass 0</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void Update(decimal lastTrade, decimal bidPrice, decimal askPrice, decimal volume, decimal bidSize, decimal askSize)
{
// update our bid and ask bars - handle null values, this is to give good values for midpoint OHLC
if (Bid == null && bidPrice != 0) Bid = new Bar(bidPrice, bidPrice, bidPrice, bidPrice);
else if (Bid != null) Bid.Update(ref bidPrice);
if (Ask == null && askPrice != 0) Ask = new Bar(askPrice, askPrice, askPrice, askPrice);
else if (Ask != null) Ask.Update(ref askPrice);
if (bidSize > 0)
{
LastBidSize = bidSize;
}
if (askSize > 0)
{
LastAskSize = askSize;
}
// be prepared for updates without trades
if (lastTrade != 0) Value = lastTrade;
else if (askPrice != 0) Value = askPrice;
else if (bidPrice != 0) Value = bidPrice;
}
/// <summary>
/// QuoteBar Reader: Fetch the data from the QC storage and feed it line by line into the engine.
/// </summary>
/// <param name="config">Symbols, Resolution, DataType, </param>
/// <param name="stream">The file data stream</param>
/// <param name="date">Date of this reader request</param>
/// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param>
/// <returns>Enumerable iterator for returning each line of the required data.</returns>
public override BaseData Reader(SubscriptionDataConfig config, StreamReader stream, DateTime date, bool isLiveMode)
{
try
{
switch (config.SecurityType)
{
case SecurityType.Equity:
return ParseEquity(config, stream, date);
case SecurityType.Forex:
case SecurityType.Crypto:
return ParseForex(config, stream, date);
case SecurityType.Cfd:
return ParseCfd(config, stream, date);
case SecurityType.Option:
case SecurityType.FutureOption:
case SecurityType.IndexOption:
return ParseOption(config, stream, date);
case SecurityType.Future:
return ParseFuture(config, stream, date);
}
}
catch (Exception err)
{
Log.Error(Invariant($"QuoteBar.Reader(): Error parsing stream, Symbol: {config.Symbol.Value}, SecurityType: {config.SecurityType}, ") +
Invariant($"Resolution: {config.Resolution}, Date: {date.ToStringInvariant("yyyy-MM-dd")}, Message: {err}")
);
}
// we need to consume a line anyway, to advance the stream
stream.ReadLine();
// if we couldn't parse it above return a default instance
return new QuoteBar { Symbol = config.Symbol, Period = config.Increment };
}
/// <summary>
/// QuoteBar Reader: Fetch the data from the QC storage and feed it line by line into the engine.
/// </summary>
/// <param name="config">Symbols, Resolution, DataType, </param>
/// <param name="line">Line from the data file requested</param>
/// <param name="date">Date of this reader request</param>
/// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param>
/// <returns>Enumerable iterator for returning each line of the required data.</returns>
public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode)
{
try
{
switch (config.SecurityType)
{
case SecurityType.Equity:
return ParseEquity(config, line, date);
case SecurityType.Forex:
case SecurityType.Crypto:
return ParseForex(config, line, date);
case SecurityType.Cfd:
return ParseCfd(config, line, date);
case SecurityType.Option:
case SecurityType.FutureOption:
case SecurityType.IndexOption:
return ParseOption(config, line, date);
case SecurityType.Future:
return ParseFuture(config, line, date);
}
}
catch (Exception err)
{
Log.Error(Invariant($"QuoteBar.Reader(): Error parsing line: '{line}', Symbol: {config.Symbol.Value}, SecurityType: {config.SecurityType}, ") +
Invariant($"Resolution: {config.Resolution}, Date: {date.ToStringInvariant("yyyy-MM-dd")}, Message: {err}")
);
}
// if we couldn't parse it above return a default instance
return new QuoteBar { Symbol = config.Symbol, Period = config.Increment };
}
private static bool HasShownWarning;
/// <summary>
/// "Scaffold" code - If the data being read is formatted as a TradeBar, use this method to deserialize it
/// TODO: Once all Forex data refactored to use QuoteBar formatted data, remove this method
/// </summary>
/// <param name="config">Symbols, Resolution, DataType, </param>
/// <param name="line">Line from the data file requested</param>
/// <param name="date">Date of this reader request</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask prices set to same values</returns>
[Obsolete("All Forex data should use Quotes instead of Trades.")]
private QuoteBar ParseTradeAsQuoteBar(SubscriptionDataConfig config, DateTime date, string line)
{
if (!HasShownWarning)
{
Logging.Log.Error("QuoteBar.ParseTradeAsQuoteBar(): Data formatted as Trade when Quote format was expected. Support for this will disappear June 2017.");
HasShownWarning = true;
}
var quoteBar = new QuoteBar
{
Period = config.Increment,
Symbol = config.Symbol
};
var csv = line.ToCsv(5);
if (config.Resolution == Resolution.Daily || config.Resolution == Resolution.Hour)
{
// hourly and daily have different time format, and can use slow, robust c# parser.
quoteBar.Time = DateTime.ParseExact(csv[0], DateFormat.TwelveCharacter, CultureInfo.InvariantCulture).ConvertTo(config.DataTimeZone, config.ExchangeTimeZone);
}
else
{
//Fast decimal conversion
quoteBar.Time = date.Date.AddMilliseconds(csv[0].ToInt32()).ConvertTo(config.DataTimeZone, config.ExchangeTimeZone);
}
var bid = new Bar
{
Open = csv[1].ToDecimal(),
High = csv[2].ToDecimal(),
Low = csv[3].ToDecimal(),
Close = csv[4].ToDecimal()
};
var ask = new Bar
{
Open = csv[1].ToDecimal(),
High = csv[2].ToDecimal(),
Low = csv[3].ToDecimal(),
Close = csv[4].ToDecimal()
};
quoteBar.Ask = ask;
quoteBar.Bid = bid;
quoteBar.Value = quoteBar.Close;
return quoteBar;
}
/// <summary>
/// Parse a quotebar representing a future with a scaling factor
/// </summary>
/// <param name="config">Symbols, Resolution, DataType</param>
/// <param name="line">Line from the data file requested</param>
/// <param name="date">Date of this reader request</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask set to same values</returns>
public QuoteBar ParseFuture(SubscriptionDataConfig config, string line, DateTime date)
{
return ParseQuote(config, date, line, false);
}
/// <summary>
/// Parse a quotebar representing a future with a scaling factor
/// </summary>
/// <param name="config">Symbols, Resolution, DataType</param>
/// <param name="streamReader">The data stream of the requested file</param>
/// <param name="date">Date of this reader request</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask set to same values</returns>
public QuoteBar ParseFuture(SubscriptionDataConfig config, StreamReader streamReader, DateTime date)
{
return ParseQuote(config, date, streamReader, false);
}
/// <summary>
/// Parse a quotebar representing an option with a scaling factor
/// </summary>
/// <param name="config">Symbols, Resolution, DataType</param>
/// <param name="line">Line from the data file requested</param>
/// <param name="date">Date of this reader request</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask set to same values</returns>
public QuoteBar ParseOption(SubscriptionDataConfig config, string line, DateTime date)
{
return ParseQuote(config, date, line, config.Symbol.SecurityType == SecurityType.Option);
}
/// <summary>
/// Parse a quotebar representing an option with a scaling factor
/// </summary>
/// <param name="config">Symbols, Resolution, DataType</param>
/// <param name="streamReader">The data stream of the requested file</param>
/// <param name="date">Date of this reader request</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask set to same values</returns>
public QuoteBar ParseOption(SubscriptionDataConfig config, StreamReader streamReader, DateTime date)
{
// scale factor only applies for equity and index options
return ParseQuote(config, date, streamReader, useScaleFactor: config.Symbol.SecurityType != SecurityType.FutureOption);
}
/// <summary>
/// Parse a quotebar representing a cfd without a scaling factor
/// </summary>
/// <param name="config">Symbols, Resolution, DataType</param>
/// <param name="line">Line from the data file requested</param>
/// <param name="date">Date of this reader request</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask set to same values</returns>
public QuoteBar ParseCfd(SubscriptionDataConfig config, string line, DateTime date)
{
return ParseQuote(config, date, line, false);
}
/// <summary>
/// Parse a quotebar representing a cfd without a scaling factor
/// </summary>
/// <param name="config">Symbols, Resolution, DataType</param>
/// <param name="streamReader">The data stream of the requested file</param>
/// <param name="date">Date of this reader request</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask set to same values</returns>
public QuoteBar ParseCfd(SubscriptionDataConfig config, StreamReader streamReader, DateTime date)
{
return ParseQuote(config, date, streamReader, false);
}
/// <summary>
/// Parse a quotebar representing a forex without a scaling factor
/// </summary>
/// <param name="config">Symbols, Resolution, DataType</param>
/// <param name="line">Line from the data file requested</param>
/// <param name="date">Date of this reader request</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask set to same values</returns>
public QuoteBar ParseForex(SubscriptionDataConfig config, string line, DateTime date)
{
return ParseQuote(config, date, line, false);
}
/// <summary>
/// Parse a quotebar representing a forex without a scaling factor
/// </summary>
/// <param name="config">Symbols, Resolution, DataType</param>
/// <param name="streamReader">The data stream of the requested file</param>
/// <param name="date">Date of this reader request</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask set to same values</returns>
public QuoteBar ParseForex(SubscriptionDataConfig config, StreamReader streamReader, DateTime date)
{
return ParseQuote(config, date, streamReader, false);
}
/// <summary>
/// Parse a quotebar representing an equity with a scaling factor
/// </summary>
/// <param name="config">Symbols, Resolution, DataType</param>
/// <param name="line">Line from the data file requested</param>
/// <param name="date">Date of this reader request</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask set to same values</returns>
public QuoteBar ParseEquity(SubscriptionDataConfig config, string line, DateTime date)
{
return ParseQuote(config, date, line, true);
}
/// <summary>
/// Parse a quotebar representing an equity with a scaling factor
/// </summary>
/// <param name="config">Symbols, Resolution, DataType</param>
/// <param name="streamReader">The data stream of the requested file</param>
/// <param name="date">Date of this reader request</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask set to same values</returns>
public QuoteBar ParseEquity(SubscriptionDataConfig config, StreamReader streamReader, DateTime date)
{
return ParseQuote(config, date, streamReader, true);
}
/// <summary>
/// "Scaffold" code - If the data being read is formatted as a QuoteBar, use this method to deserialize it
/// </summary>
/// <param name="config">Symbols, Resolution, DataType, </param>
/// <param name="streamReader">The data stream of the requested file</param>
/// <param name="date">Date of this reader request</param>
/// <param name="useScaleFactor">Whether the data has a scaling factor applied</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask prices set appropriately</returns>
private QuoteBar ParseQuote(SubscriptionDataConfig config, DateTime date, StreamReader streamReader, bool useScaleFactor)
{
// Non-equity asset classes will not use scaling, including options that have a non-equity underlying asset class.
var scaleFactor = useScaleFactor
? _scaleFactor
: 1;
var quoteBar = new QuoteBar
{
Period = config.Increment,
Symbol = config.Symbol
};
if (config.Resolution == Resolution.Daily || config.Resolution == Resolution.Hour)
{
// hourly and daily have different time format, and can use slow, robust c# parser.
quoteBar.Time = streamReader.GetDateTime().ConvertTo(config.DataTimeZone, config.ExchangeTimeZone);
}
else
{
// Using custom int conversion for speed on high resolution data.
quoteBar.Time = date.Date.AddMilliseconds(streamReader.GetInt32()).ConvertTo(config.DataTimeZone, config.ExchangeTimeZone);
}
var open = streamReader.GetDecimal();
var high = streamReader.GetDecimal();
var low = streamReader.GetDecimal();
var close = streamReader.GetDecimal();
var lastSize = streamReader.GetDecimal();
// only create the bid if it exists in the file
if (open != 0 || high != 0 || low != 0 || close != 0)
{
quoteBar.Bid = new Bar
{
Open = open * scaleFactor,
High = high * scaleFactor,
Low = low * scaleFactor,
Close = close * scaleFactor
};
quoteBar.LastBidSize = lastSize;
}
else
{
quoteBar.Bid = null;
}
open = streamReader.GetDecimal();
high = streamReader.GetDecimal();
low = streamReader.GetDecimal();
close = streamReader.GetDecimal();
lastSize = streamReader.GetDecimal();
// only create the ask if it exists in the file
if (open != 0 || high != 0 || low != 0 || close != 0)
{
quoteBar.Ask = new Bar
{
Open = open * scaleFactor,
High = high * scaleFactor,
Low = low * scaleFactor,
Close = close * scaleFactor
};
quoteBar.LastAskSize = lastSize;
}
else
{
quoteBar.Ask = null;
}
quoteBar.Value = quoteBar.Close;
return quoteBar;
}
/// <summary>
/// "Scaffold" code - If the data being read is formatted as a QuoteBar, use this method to deserialize it
/// TODO: Once all Forex data refactored to use QuoteBar formatted data, use only this method
/// </summary>
/// <param name="config">Symbols, Resolution, DataType, </param>
/// <param name="line">Line from the data file requested</param>
/// <param name="date">Date of this reader request</param>
/// <param name="useScaleFactor">Whether the data has a scaling factor applied</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask prices set appropriately</returns>
private QuoteBar ParseQuote(SubscriptionDataConfig config, DateTime date, string line, bool useScaleFactor)
{
var scaleFactor = useScaleFactor
? _scaleFactor
: 1;
var quoteBar = new QuoteBar
{
Period = config.Increment,
Symbol = config.Symbol
};
var csv = line.ToCsv(10);
if (config.Resolution == Resolution.Daily || config.Resolution == Resolution.Hour)
{
// hourly and daily have different time format, and can use slow, robust c# parser.
quoteBar.Time = DateTime.ParseExact(csv[0], DateFormat.TwelveCharacter, CultureInfo.InvariantCulture).ConvertTo(config.DataTimeZone, config.ExchangeTimeZone);
}
else
{
// Using custom "ToDecimal" conversion for speed on high resolution data.
quoteBar.Time = date.Date.AddMilliseconds((double)csv[0].ToDecimal()).ConvertTo(config.DataTimeZone, config.ExchangeTimeZone);
}
// only create the bid if it exists in the file
if (csv[1].Length != 0 || csv[2].Length != 0 || csv[3].Length != 0 || csv[4].Length != 0)
{
quoteBar.Bid = new Bar
{
Open = csv[1].ToDecimal() * scaleFactor,
High = csv[2].ToDecimal() * scaleFactor,
Low = csv[3].ToDecimal() * scaleFactor,
Close = csv[4].ToDecimal() * scaleFactor
};
quoteBar.LastBidSize = csv[5].ToDecimal();
}
else
{
quoteBar.Bid = null;
}
// only create the ask if it exists in the file
if (csv[6].Length != 0 || csv[7].Length != 0 || csv[8].Length != 0 || csv[9].Length != 0)
{
quoteBar.Ask = new Bar
{
Open = csv[6].ToDecimal() * scaleFactor,
High = csv[7].ToDecimal() * scaleFactor,
Low = csv[8].ToDecimal() * scaleFactor,
Close = csv[9].ToDecimal() * scaleFactor
};
quoteBar.LastAskSize = csv[10].ToDecimal();
}
else
{
quoteBar.Ask = null;
}
quoteBar.Value = quoteBar.Close;
return quoteBar;
}
/// <summary>
/// Get Source for Custom Data File
/// >> What source file location would you prefer for each type of usage:
/// </summary>
/// <param name="config">Configuration object</param>
/// <param name="date">Date of this source request if source spread across multiple files</param>
/// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param>
/// <returns>String source location of the file</returns>
public override SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode)
{
if (isLiveMode)
{
// this data type is streamed in live mode
return new SubscriptionDataSource(string.Empty, SubscriptionTransportMedium.Streaming);
}
var source = LeanData.GenerateZipFilePath(Globals.DataFolder, config.Symbol, date, config.Resolution, config.TickType);
if (config.SecurityType == SecurityType.Future || config.SecurityType.IsOption())
{
source += "#" + LeanData.GenerateZipEntryName(config.Symbol, date, config.Resolution, config.TickType);
}
return new SubscriptionDataSource(source, SubscriptionTransportMedium.LocalFile, FileFormat.Csv);
}
/// <summary>
/// Return a new instance clone of this quote bar, used in fill forward
/// </summary>
/// <returns>A clone of the current quote bar</returns>
public override BaseData Clone()
{
return new QuoteBar
{
Ask = Ask == null ? null : Ask.Clone(),
Bid = Bid == null ? null : Bid.Clone(),
LastAskSize = LastAskSize,
LastBidSize = LastBidSize,
Symbol = Symbol,
Time = Time,
Period = Period,
Value = Value,
DataType = DataType
};
}
/// <summary>
/// Collapses QuoteBars into TradeBars object when
/// algorithm requires FX data, but calls OnData(<see cref="TradeBars"/>)
/// TODO: (2017) Remove this method in favor of using OnData(<see cref="Slice"/>)
/// </summary>
/// <returns><see cref="TradeBars"/></returns>
public TradeBar Collapse()
{
return new TradeBar(Time, Symbol, Open, High, Low, Close, 0)
{
Period = Period
};
}
/// <summary>
/// Convert this <see cref="QuoteBar"/> to string form.
/// </summary>
/// <returns>String representation of the <see cref="QuoteBar"/></returns>
public override string ToString()
{
return $"{Symbol}: " +
$"Bid: O: {Bid?.Open.SmartRounding()} " +
$"Bid: H: {Bid?.High.SmartRounding()} " +
$"Bid: L: {Bid?.Low.SmartRounding()} " +
$"Bid: C: {Bid?.Close.SmartRounding()} " +
$"Ask: O: {Ask?.Open.SmartRounding()} " +
$"Ask: H: {Ask?.High.SmartRounding()} " +
$"Ask: L: {Ask?.Low.SmartRounding()} " +
$"Ask: C: {Ask?.Close.SmartRounding()} ";
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.