context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
//
// 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.
//
namespace NLog.Internal.FileAppenders
{
using System;
using System.IO;
using System.Threading;
/// <summary>
/// Maintains a collection of file appenders usually associated with file targets.
/// </summary>
internal sealed class FileAppenderCache
{
private BaseFileAppender[] appenders;
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
private string archiveFilePatternToWatch = null;
private readonly MultiFileWatcher externalFileArchivingWatcher = new MultiFileWatcher(NotifyFilters.FileName);
private bool logFileWasArchived = false;
#endif
/// <summary>
/// An "empty" instance of the <see cref="FileAppenderCache"/> class with zero size and empty list of appenders.
/// </summary>
public static readonly FileAppenderCache Empty = new FileAppenderCache();
/// <summary>
/// Initializes a new "empty" instance of the <see cref="FileAppenderCache"/> class with zero size and empty
/// list of appenders.
/// </summary>
private FileAppenderCache() : this(0, null, null) { }
/// <summary>
/// Initializes a new instance of the <see cref="FileAppenderCache"/> class.
/// </summary>
/// <remarks>
/// The size of the list should be positive. No validations are performed during initialisation as it is an
/// intenal class.
/// </remarks>
/// <param name="size">Total number of appenders allowed in list.</param>
/// <param name="appenderFactory">Factory used to create each appender.</param>
/// <param name="createFileParams">Parameters used for creating a file.</param>
public FileAppenderCache(int size, IFileAppenderFactory appenderFactory, ICreateFileParameters createFileParams)
{
Size = size;
Factory = appenderFactory;
CreateFileParameters = createFileParams;
appenders = new BaseFileAppender[Size];
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
externalFileArchivingWatcher.OnChange += ExternalFileArchivingWatcher_OnChange;
#endif
}
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
private void ExternalFileArchivingWatcher_OnChange(object sender, FileSystemEventArgs e)
{
if ((e.ChangeType & WatcherChangeTypes.Created) == WatcherChangeTypes.Created)
logFileWasArchived = true;
}
/// <summary>
/// The archive file path pattern that is used to detect when archiving occurs.
/// </summary>
public string ArchiveFilePatternToWatch
{
get { return archiveFilePatternToWatch; }
set
{
if (archiveFilePatternToWatch != value)
{
archiveFilePatternToWatch = value;
logFileWasArchived = false;
externalFileArchivingWatcher.StopWatching();
}
}
}
/// <summary>
/// Invalidates appenders for all files that were archived.
/// </summary>
public void InvalidateAppendersForInvalidFiles()
{
if (logFileWasArchived)
{
CloseAppenders();
logFileWasArchived = false;
}
}
#endif
/// <summary>
/// Gets the parameters which will be used for creating a file.
/// </summary>
public ICreateFileParameters CreateFileParameters { get; private set; }
/// <summary>
/// Gets the file appender factory used by all the appenders in this list.
/// </summary>
public IFileAppenderFactory Factory { get; private set; }
/// <summary>
/// Gets the number of appenders which the list can hold.
/// </summary>
public int Size { get; private set; }
/// <summary>
/// It allocates the first slot in the list when the file name does not already in the list and clean up any
/// unused slots.
/// </summary>
/// <param name="fileName">File name associated with a single appender.</param>
/// <returns>The allocated appender.</returns>
/// <exception cref="NullReferenceException">
/// Thrown when <see cref="M:AllocateAppender"/> is called on an <c>Empty</c><see cref="FileAppenderCache"/> instance.
/// </exception>
public BaseFileAppender AllocateAppender(string fileName)
{
//
// BaseFileAppender.Write is the most expensive operation here
// so the in-memory data structure doesn't have to be
// very sophisticated. It's a table-based LRU, where we move
// the used element to become the first one.
// The number of items is usually very limited so the
// performance should be equivalent to the one of the hashtable.
//
BaseFileAppender appenderToWrite = null;
int freeSpot = appenders.Length - 1;
for (int i = 0; i < appenders.Length; ++i)
{
// Use empty slot in recent appender list, if there is one.
if (appenders[i] == null)
{
freeSpot = i;
break;
}
if (appenders[i].FileName == fileName)
{
// found it, move it to the first place on the list
// (MRU)
// file open has a chance of failure
// if it fails in the constructor, we won't modify any data structures
BaseFileAppender app = appenders[i];
for (int j = i; j > 0; --j)
{
appenders[j] = appenders[j - 1];
}
appenders[0] = app;
appenderToWrite = app;
break;
}
}
if (appenderToWrite == null)
{
BaseFileAppender newAppender = Factory.Open(fileName, CreateFileParameters);
if (appenders[freeSpot] != null)
{
CloseAppender(appenders[freeSpot]);
appenders[freeSpot] = null;
}
for (int j = freeSpot; j > 0; --j)
{
appenders[j] = appenders[j - 1];
}
appenders[0] = newAppender;
appenderToWrite = newAppender;
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
if (!string.IsNullOrEmpty(archiveFilePatternToWatch))
{
var archiveFilePatternToWatchPath = GetFullPathForPattern(archiveFilePatternToWatch);
string directoryPath = Path.GetDirectoryName(archiveFilePatternToWatchPath);
if (!Directory.Exists(directoryPath))
Directory.CreateDirectory(directoryPath);
externalFileArchivingWatcher.Watch(archiveFilePatternToWatchPath);
}
#endif
}
return appenderToWrite;
}
/// <summary>
/// Get fullpath for a relative file pattern, e.g *.log
/// <see cref="Path.GetFullPath"/> crashes on patterns: ArgumentException: Illegal characters in path.
/// </summary>
/// <param name="pattern"></param>
/// <returns></returns>
private static string GetFullPathForPattern(string pattern)
{
string filePattern = Path.GetFileName(pattern);
string dir = pattern.Substring(0, pattern.Length - filePattern.Length);
// Get absolute path (root+relative)
if (string.IsNullOrEmpty(dir))
{
dir = ".";
}
return Path.Combine(Path.GetFullPath(dir), filePattern);
}
/// <summary>
/// Close all the allocated appenders.
/// </summary>
public void CloseAppenders()
{
if (appenders != null)
{
for (int i = 0; i < appenders.Length; ++i)
{
if (appenders[i] == null)
{
break;
}
CloseAppender(appenders[i]);
appenders[i] = null;
}
}
}
/// <summary>
/// Close the allocated appenders initialised before the supplied time.
/// </summary>
/// <param name="expireTime">The time which prior the appenders considered expired</param>
public void CloseAppenders(DateTime expireTime)
{
for (int i = 0; i < this.appenders.Length; ++i)
{
if (this.appenders[i] == null)
{
break;
}
if (this.appenders[i].OpenTime < expireTime)
{
for (int j = i; j < this.appenders.Length; ++j)
{
if (this.appenders[j] == null)
{
break;
}
CloseAppender(this.appenders[j]);
this.appenders[j] = null;
}
break;
}
}
}
/// <summary>
/// Fluch all the allocated appenders.
/// </summary>
public void FlushAppenders()
{
foreach (BaseFileAppender appender in appenders)
{
if (appender == null)
{
break;
}
appender.Flush();
}
}
/// <summary>
/// Gets the file info for a particular appender.
/// </summary>
/// <param name="fileName">The file name associated with a particular appender.</param>
/// <returns>The file characteristics, if the file information was retrieved successfully, otherwise null.</returns>
public FileCharacteristics GetFileCharacteristics(string fileName)
{
foreach (BaseFileAppender appender in appenders)
{
if (appender == null)
break;
if (appender.FileName == fileName)
return appender.GetFileCharacteristics();
}
return null;
}
/// <summary>
/// Closes the specified appender and removes it from the list.
/// </summary>
/// <param name="fileName">File name of the appender to be closed.</param>
public void InvalidateAppender(string fileName)
{
for (int i = 0; i < appenders.Length; ++i)
{
if (appenders[i] == null)
{
break;
}
if (appenders[i].FileName == fileName)
{
CloseAppender(appenders[i]);
for (int j = i; j < appenders.Length - 1; ++j)
{
appenders[j] = appenders[j + 1];
}
appenders[appenders.Length - 1] = null;
break;
}
}
}
private void CloseAppender(BaseFileAppender appender)
{
appender.Close();
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
externalFileArchivingWatcher.StopWatching();
#endif
}
}
}
| |
namespace XSharp.MacroCompiler
{
internal static class VulcanTypeNames
{
internal const string CodeBlockType = "Codeblock";
internal const string UsualType = "__Usual";
internal const string VOStructAttribute = "VOStructAttribute";
internal const string DefaultParameterAttribute = "DefaultParameterValueAttribute";
internal const string ActualTypeAttribute = "ActualTypeAttribute";
internal const string ClipperCallingConventionAttribute = "ClipperCallingConventionAttribute";
}
internal static class VulcanQualifiedTypeNames
{
internal const string Usual = "global::Vulcan.__Usual";
internal const string Float = "global::Vulcan.__VOFloat";
internal const string Date = "global::Vulcan.__VODate";
internal const string Array = "global::Vulcan.__Array";
internal const string Symbol = "global::Vulcan.__Symbol";
internal const string Psz = "global::Vulcan.__Psz";
internal const string Codeblock = "global::Vulcan.Codeblock";
internal const string WinBool = "global::Vulcan.__WinBool";
internal const string RuntimeState = "global::Vulcan.Runtime.State";
internal const string ClipperCallingConvention = "global::Vulcan.Internal.ClipperCallingConventionAttribute";
internal const string DefaultParameterAttribute = "global::Vulcan.Internal.DefaultParameterValueAttribute";
internal const string WrappedException = "global::Vulcan.Internal.VulcanWrappedException";
internal const string DefaultParameter = "global::Vulcan.Internal.DefaultParameterValueAttribute";
internal const string ActualType = "global::Vulcan.Internal.ActualTypeAttribute";
internal const string Error = "global::Vulcan.Error";
internal const string ClassLibrary = "global::Vulcan.Internal.VulcanClassLibraryAttribute";
internal const string CompilerVersion = "global::Vulcan.Internal.VulcanCompilerVersion";
internal const string VOStructAttribute = "global::Vulcan.Internal.VOStructAttribute";
internal const string CompilerServices = "global::Vulcan.Internal.CompilerServices";
internal const string ImplicitNamespaceAttribute = "global::Vulcan.VulcanImplicitNamespaceAttribute";
internal const string Functions = "global::VulcanRTFuncs.Functions";
}
internal static class XSharpQualifiedTypeNames
{
internal const string Usual = "global::XSharp.__Usual";
internal const string Float = "global::XSharp.__Float";
internal const string Date = "global::XSharp.__Date";
internal const string Array = "global::XSharp.__Array";
internal const string Symbol = "global::XSharp.__Symbol";
internal const string Psz = "global::XSharp.__Psz";
internal const string Codeblock = "global::XSharp.Codeblock";
internal const string WinBool = "global::XSharp.__WinBool";
internal const string RuntimeState = "global::XSharp.RuntimeState";
internal const string ClipperCallingConvention = "global::XSharp.Internal.ClipperCallingConventionAttribute";
internal const string DefaultParameterAttribute = "global::XSharp.Internal.DefaultParameterValueAttribute";
internal const string WrappedException = "global::XSharp.Internal.WrappedException";
internal const string DefaultParameter = "global::XSharp.Internal.DefaultParameterValueAttribute";
internal const string ActualType = "global::XSharp.Internal.ActualTypeAttribute";
internal const string Error = "global::XSharp.Error";
internal const string ClassLibrary = "global::XSharp.Internal.ClassLibraryAttribute";
internal const string CompilerVersion = "global::XSharp.Internal.CompilerVersion";
internal const string VOStructAttribute = "global::XSharp.Internal.VOStructAttribute";
internal const string CompilerServices = "global::XSharp.Internal.CompilerServices";
internal const string ImplicitNamespaceAttribute = "global::XSharp.ImplicitNamespaceAttribute";
internal const string Functions = "global::XSharp.RT.Functions";
internal const string ArrayBase = "global::XSharp.__ArrayBase`1";
}
internal static class XSharpSpecialNames
{
internal const string ImpliedTypeName = "Xs$var";
internal const string ScriptDummy = "XS$dummy";
internal const string StaticLocalFieldNamePrefix = "Xs$StaticLocal$";
internal const string StaticLocalInitFieldNameSuffix = "$init";
internal const string StaticLocalLockFieldNameSuffix = "$lock";
internal const string EventFieldNamePrefix = "Xs$Event$";
internal const string AccessSuffix = "$Access";
internal const string AssignSuffix = "$Assign";
internal const string DelegateNameSpace = "Xs$Delegates";
internal const string PCallPrefix = "$PCall";
internal const string PCallNativePrefix = "$PCallNative";
internal const string AppInit = "$AppInit";
internal const string AppExit = "$AppExit";
internal const string InitProc1 = "$Init1";
internal const string InitProc2 = "$Init2";
internal const string InitProc3 = "$Init3";
internal const string ExitProc = "$Exit";
internal const string PCallProc = "$PCallGetDelegate";
internal const string SymbolTable = "Xs$SymbolTable";
internal const string PSZTable = "Xs$PSZLiteralsTable";
internal const string VoPszList = "Xs$PszList";
internal const string ClipperArgs = "Xs$Args";
internal const string NestedCodeblockArgs = "Xs$NstCbs";
internal const string ClipperPCount = "Xs$PCount";
internal const string ClipperArgCount = "Xs$ArgCount";
internal const string RecoverVarName = "Xs$Obj";
internal const string ExVarName = "Xs$Exception";
internal const string ReturnName = "Xs$Return";
internal const string FunctionsClass = "Functions";
internal const string VOExeFunctionsClass = ".Exe.Functions";
internal const string XSharpCoreFunctionsClass = "XSharp.Core.Functions";
internal const string XSharpRDDFunctionsClass = "XSharp.RDD.Functions";
internal const string XSharpRTFunctionsClass = "XSharp.RT.Functions";
internal const string XSharpVOFunctionsClass = "XSharp.VO.Functions";
internal const string XSharpVFPFunctionsClass = "XSharp.VFP.Functions";
internal const string XSharpXPPFunctionsClass = "XSharp.XPP.Functions";
internal const string XSharpDataFunctionsClass = "XSharp.Data.Functions";
internal const string VODllFunctionsClass = ".Functions";
internal const string ModuleName = "<Module>";
}
internal static class XSharpFunctionNames
{
// these are all expected in the VO Function type
internal const string StringCompare = "__StringCompare";
internal const string StringEquals = "__StringEquals";
internal const string StringSubtract = "StringSubtract";
internal const string InExactEquals = "__InexactEquals";
internal const string InExactNotEquals = "__InexactNotEquals";
internal const string ToObject = "ToObject";
internal const string IVarGet = "IVarGet";
internal const string IVarPut = "IVarPut";
internal const string InternalSend = "__InternalSend";
internal const string ASend = "ASend";
internal const string Eval = "Eval";
internal const string StringAlloc = "StringAlloc";
internal const string GetElement = "__GetElement";
internal const string SetElement = "__SetElement";
internal const string QOut = "QOut";
internal const string QQOut = "QQOut";
// These are in the generated code
internal const string RunInitProcs = "RunInitProcs";
}
internal static class VulcanQualifiedFunctionNames
{
internal const string StringCompare = "global::VulcanRTFuncs.Functions.__StringCompare";
internal const string StringEquals = "global::VulcanRTFuncs.Functions.__StringEquals";
internal const string StringNotEquals = "global::VulcanRTFuncs.Functions.__StringNotEquals";
internal const string VarGet = "global::VulcanRTFuncs.Functions.VarGet";
internal const string VarPut = "global::VulcanRTFuncs.Functions.VarPut";
internal const string FieldGet = "global::VulcanRTFuncs.Functions.__FieldGet";
internal const string FieldGetWa = "global::VulcanRTFuncs.Functions.__FieldGetWa";
internal const string FieldSet = "global::VulcanRTFuncs.Functions.__FieldSet";
internal const string FieldSetWa = "global::VulcanRTFuncs.Functions.__FieldSetWa";
internal const string MemVarGet = "global::VulcanRTFuncs.Functions.__MemVarGet";
internal const string MemVarPut = "global::VulcanRTFuncs.Functions.__MemVarPut";
internal const string IVarGet = "global::VulcanRTFuncs.Functions.IVarGet";
internal const string IVarPut = "global::VulcanRTFuncs.Functions.IVarPut";
internal const string InternalSend = "global::VulcanRTFuncs.Functions.__InternalSend";
internal const string ASend = "global::VulcanRTFuncs.Functions.ASend";
internal const string NullDate = "global::Vulcan.__VODate.NullDate";
internal const string PszRelease = "global::Vulcan.Internal.CompilerServices.String2PszRelease";
internal const string String2Psz = "global::Vulcan.Internal.CompilerServices.String2Psz";
internal const string ArrayNew = "global::Vulcan.__Array.__ArrayNew";
internal const string InStr = "global::VulcanRTFuncs.Functions.Instr";
internal const string EnterSequence = "global::Vulcan.Internal.CompilerServices.EnterBeginSequence";
internal const string ExitSequence = "global::Vulcan.Internal.CompilerServices.ExitBeginSequence";
internal const string WrapException = "global::Vulcan.Error._WrapRawException";
internal const string QQout = "global::VulcanRTFuncs.Functions.QQOut";
internal const string Qout = "global::VulcanRTFuncs.Functions.QOut";
internal const string Chr = "global::VulcanRTFuncs.Functions.Chr";
internal const string PushWorkarea = "global::VulcanRTFuncs.Functions.__pushWorkarea";
internal const string PopWorkarea = "global::VulcanRTFuncs.Functions.__popWorkarea";
internal const string Evaluate = "global::VulcanRTFuncs.Functions.Evaluate$(System.String)";
//internal const string Default = "global::VulcanRTFuncs.Functions.Default";
//internal const string Accept = "global::VulcanRTFuncs.Functions._accept";
//internal const string Wait = "global::VulcanRTFuncs.Functions._wait";
//internal const string Quit = "global::VulcanRTFuncs.Functions._quit";
}
internal static class SystemQualifiedFunctionNames
{
internal const string StringConcat = "global::System.String.Concat";
}
internal static class XSharpQualifiedFunctionNames
{
// In core
internal const string Chr = "global::XSharp.Core.Functions.Chr";
internal const string InStr = "global::XSharp.Core.Functions.Instr";
internal const string WrapException = "global::XSharp.Error.WrapRawException";
// In VO assembly
internal const string StringCompare = "global::XSharp.RT.Functions.__StringCompare";
internal const string StringEquals = "global::XSharp.RT.Functions.__StringEquals";
internal const string StringNotEquals = "global::XSharp.RT.Functions.__StringNotEquals";
internal const string VarGet = "global::XSharp.RT.Functions.__VarGet";
internal const string VarPut = "global::XSharp.RT.Functions.__VarPut";
internal const string FieldGet = "global::XSharp.RT.Functions.__FieldGet";
internal const string FieldGetWa = "global::XSharp.RT.Functions.__FieldGetWa";
internal const string FieldSet = "global::XSharp.RT.Functions.__FieldSet";
internal const string FieldSetWa = "global::XSharp.RT.Functions.__FieldSetWa";
internal const string MemVarGet = "global::XSharp.RT.Functions.__MemVarGet";
internal const string MemVarPut = "global::XSharp.RT.Functions.__MemVarPut";
internal const string IVarGet = "global::XSharp.RT.Functions.IVarGet";
internal const string IVarPut = "global::XSharp.RT.Functions.IVarPut";
internal const string InternalSend = "global::XSharp.RT.Functions.__InternalSend";
internal const string ASend = "global::XSharp.RT.Functions.ASend";
internal const string NullDate = "global::XSharp.__VODate.NullDate";
//internal const string UsualNIL = "global::XSharp.__Usual._NIL";
internal const string PszRelease = "global::XSharp.Internal.CompilerServices.String2PszRelease";
internal const string String2Psz = "global::XSharp.Internal.CompilerServices.String2Psz";
internal const string ArrayNew = "global::XSharp.__Array.__ArrayNew";
internal const string EnterSequence = "global::XSharp.Internal.CompilerServices.EnterBeginSequence";
internal const string ExitSequence = "global::XSharp.Internal.CompilerServices.ExitBeginSequence";
internal const string QQout = "global::XSharp.RT.Functions.QQOut";
internal const string Qout = "global::XSharp.RT.Functions.QOut";
internal const string StringAlloc = "global::XSharp.RT.Functions.StringAlloc";
internal const string PushWorkarea = "global::XSharp.RT.Functions.__pushWorkarea";
internal const string PopWorkarea = "global::XSharp.RT.Functions.__popWorkarea";
internal const string Evaluate = "global::XSharp.RT.Functions.Evaluate$(System.String)";
internal const string VarGetSafe = "global::XSharp.RT.Functions.__VarGetSafe";
internal const string MemVarGetSafe = "global::XSharp.RT.Functions.__MemVarGetSafe";
// In VFP assembly
internal const string FoxArrayAccess_1 = "XSharp.VFP.Functions.__FoxArrayAccess$(System.String,XSharp.__Usual,XSharp.__Usual)";
internal const string FoxArrayAccess_2 = "XSharp.VFP.Functions.__FoxArrayAccess$(System.String,XSharp.__Usual,XSharp.__Usual,XSharp.__Usual)";
}
internal static class OurAssemblyNames
{
// please note that these MUST be lowercase !
internal const string VulcanRT = "vulcanrt";
internal const string VulcanRTFuncs = "vulcanrtfuncs";
internal const string XSharpCore = "xsharp.core";
internal const string XSharpVO = "xsharp.vo";
}
internal static class OurNameSpaces
{
internal const string System = "System";
internal const string Vulcan = "Vulcan";
internal const string XSharp = "XSharp";
}
internal static class SystemNames
{
internal const string IndexerName = "Item";
internal const string DelegateInvokeName = "Invoke";
internal const string CtorName = ".ctor";
internal const string ArrayGetValue = "GetValue";
internal const string ArraySetValue = "SetValue";
internal const string GetEnumerator = "GetEnumerator";
internal const string MoveNext = "MoveNext";
internal const string Current = "Current";
internal const string CurrentGetter = "get_Current";
internal const string Dispose = "Dispose";
internal const string Length = "Length";
}
internal static class SystemQualifiedNames
{
internal const string Cdecl = "global::System.Runtime.InteropServices.CallingConvention.Cdecl";
internal const string ThisCall = "global::System.Runtime.InteropServices.CallingConvention.ThisCall";
internal const string CompilerGenerated = "global::System.Runtime.CompilerServices.CompilerGenerated";
internal const string CompilerGlobalScope = "global::System.Runtime.CompilerServices.CompilerGlobalScope";
internal const string IntPtr = "global::System.IntPtr";
internal const string DllImport = "global::System.Runtime.InteropServices.DllImportAttribute";
internal const string CharSet = "global::System.Runtime.InteropServices.CharSet";
internal const string WriteLine = "global::System.Console.WriteLine";
internal const string Write = "global::System.Console.Write";
internal const string Pow = "global::System.Math.Pow";
internal const string DebuggerBreak = "global::System.Diagnostics.Debugger.Break";
internal const string Debugger = "global::System.Diagnostics.Debugger";
internal const string GetHInstance = "global::System.Runtime.InteropServices.Marshal.GetHINSTANCE";
internal const string Exception = "global::System.Exception";
internal const string StructLayout = "global::System.Runtime.InteropServices.StructLayout";
internal const string LayoutExplicit = "global::System.Runtime.InteropServices.LayoutKind.Explicit";
internal const string LayoutSequential = "global::System.Runtime.InteropServices.LayoutKind.Sequential";
internal const string FieldOffset = "global::System.Runtime.InteropServices.FieldOffset";
internal const string GetDelegate = "global::System.Runtime.InteropServices.Marshal.GetDelegateForFunctionPointer";
internal const string GcCollect = "global::System.Gc.Collect";
internal const string GcWait = "global::System.Gc.WaitForPendingFinalizers";
internal const string Void1 = "System.Void";
internal const string Void2 = "global::System.Void";
internal const string CollectionsGeneric = "global::System.Collections.Generic";
internal const string IEnumerator = "global::System.Collections.IEnumerator";
internal const string IEnumeratorOfT = "global::System.Collections.Generic.IEnumerator`1";
}
internal static class OperatorNames
{
internal const string Implicit = "op_Implicit";
internal const string Explicit = "op_Explicit";
internal const string Addition = "op_Addition";
internal const string BitwiseAnd = "op_BitwiseAnd";
internal const string BitwiseOr = "op_BitwiseOr";
internal const string Decrement = "op_Decrement";
internal const string Division = "op_Division";
internal const string Equality = "op_Equality";
internal const string ExclusiveOr = "op_ExclusiveOr";
internal const string False = "op_False";
internal const string GreaterThan = "op_GreaterThan";
internal const string GreaterThanOrEqual = "op_GreaterThanOrEqual";
internal const string Increment = "op_Increment";
internal const string Inequality = "op_Inequality";
internal const string LeftShift = "op_LeftShift";
internal const string UnsignedLeftShift = "op_UnsignedLeftShift";
internal const string LessThan = "op_LessThan";
internal const string LessThanOrEqual = "op_LessThanOrEqual";
internal const string LogicalNot = "op_LogicalNot";
internal const string LogicalOr = "op_LogicalOr";
internal const string LogicalAnd = "op_LogicalAnd";
internal const string Modulus = "op_Modulus";
internal const string Multiply = "op_Multiply";
internal const string OnesComplement = "op_OnesComplement";
internal const string RightShift = "op_RightShift";
internal const string UnsignedRightShift = "op_UnsignedRightShift";
internal const string Subtraction = "op_Subtraction";
internal const string True = "op_True";
internal const string UnaryNegation = "op_UnaryNegation";
internal const string UnaryPlus = "op_UnaryPlus";
internal const string Concatenate = "op_Concatenate";
internal const string Exponent = "op_Exponent";
internal const string IntegerDivision = "op_IntegerDivision";
internal const string Like = "op_Like";
internal const string __UsualExponent = "__Pow";
internal const string __UsualInExactEquals = "__InexactEquals";
internal const string __UsualInExactNotEquals = "__InexactNotEquals";
}
internal static class VulcanAssemblyNames
{
// please note that these MUST be lowercase !
internal const string VulcanRT = "vulcanrt";
internal const string VulcanRTFuncs = "vulcanrtfuncs";
}
internal static class XSharpAssemblyNames
{
// please note that these MUST be lowercase !
internal const string XSharpCore = "xsharp.core";
internal const string XSharpData = "xsharp.data";
internal const string XSharpRT = "xsharp.rt";
internal const string XSharpVO = "xsharp.vo";
internal const string XSharpXPP = "xsharp.xpp";
internal const string XSharpVFP = "xsharp.vfp";
internal const string SdkDefines = "sdkdefines";
internal const string VoGui = "voguiclasses";
internal const string VoSystem = "vosystemclasses";
internal const string VoRdd = "vorddclasses";
internal const string VoSql = "vosqlclasses";
internal const string VoConsole = "voconsoleclasses";
internal const string VoWin32 = "vowin32apilibrary";
internal const string VoInet = "vointernetclasses";
internal const string VoReport = "voreportclasses";
}
}
| |
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// 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 Newtonsoft.Json;
using Sensus.Anonymization;
using Sensus.Anonymization.Anonymizers;
namespace Sensus
{
/// <summary>
/// A single unit of sensed information returned by a probe.
/// </summary>
public abstract class Datum
{
/// <summary>
/// Settings for serializing Datum objects
/// </summary>
private static readonly JsonSerializerSettings JSON_SERIALIZER_SETTINGS = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
};
public static Datum FromJSON(string json)
{
// null datum properties in the json come from a few places: a reference-type property that is
// null (e.g., a string), a nullable property that has no value, and a property to which a
// value-omitting anonymizer is applied. the first two cases will not cause issues when
// deserializing. the final case will be problematic if the property is a value-type since we
// cannot assign null to a value type. so we're going to ignore null values when deserializing
// data. in the first two cases above, the property will have the appropriate null value. in the
// third case the property will have its default value. be aware that value-type datum type properties
// with value-omitting anonymizers can thus have their values changed when serialized and then
// deserialized (from the original value to their default value). this will usually be okay because
// any subsequent serialization will omit the value again.
JSON_SERIALIZER_SETTINGS.NullValueHandling = NullValueHandling.Ignore;
Datum datum = null;
try
{
datum = JsonConvert.DeserializeObject<Datum>(json, JSON_SERIALIZER_SETTINGS);
}
catch (Exception ex)
{
SensusServiceHelper.Get().Logger.Log("Failed to convert JSON to datum: " + ex.Message, LoggingLevel.Normal, typeof(Datum));
}
return datum;
}
private string _id;
private string _deviceId;
private DateTimeOffset _timestamp;
private string _protocolId;
private int _hashCode;
private bool _anonymized;
private string _buildId;
/// <summary>
/// Unique identifier for the current <see cref="Datum"/>, unique across all data generated by all Sensus apps.
/// </summary>
/// <value>The identifier.</value>
public string Id
{
get { return _id; }
set
{
_id = value;
_hashCode = _id.GetHashCode();
}
}
/// <summary>
/// An identifier that is unique to the particular device running Sensus. Note that this ID will change if the user performs
/// a factory reset on their device.
/// </summary>
/// <value>The device identifier.</value>
[Anonymizable("Device ID:", typeof(StringHashAnonymizer), false)]
public string DeviceId
{
get { return _deviceId; }
set { _deviceId = value; }
}
/// <summary>
/// Date and time at which a data element from the Probe was read.
/// </summary>
/// <value>The timestamp.</value>
[Anonymizable(null, typeof(DateTimeOffsetTimelineAnonymizer), false)]
public DateTimeOffset Timestamp
{
get { return _timestamp; }
set { _timestamp = value; }
}
/// <summary>
/// A unique identifier for the <see cref="Protocol"/> that generated this <see cref="Datum"/>.
/// </summary>
/// <value>The protocol identifier.</value>
public string ProtocolId
{
get
{
return _protocolId;
}
set
{
_protocolId = value;
}
}
/// <summary>
/// Whether or not this <see cref="Datum"/> has been run through an anonymizer.
/// </summary>
/// <value><c>true</c> if anonymized; otherwise, <c>false</c>.</value>
public bool Anonymized
{
get
{
return _anonymized;
}
set
{
_anonymized = value;
}
}
/// <summary>
/// The identifier for the build of Sensus that generated this datum.
/// </summary>
/// <value>The build identifier.</value>
public string BuildId
{
get { return _buildId; }
set { _buildId = value; }
}
[JsonIgnore]
public abstract string DisplayDetail { get; }
/// <summary>
/// Gets the string placeholder value, which is used as a formatting replacement in strings
/// such as <see cref="Probes.User.Scripts.Script.Caption"/> and <see cref="UI.Inputs.Input.LabelText"/>.
/// </summary>
/// <value>The string placeholder value.</value>
[JsonIgnore]
public abstract object StringPlaceholderValue { get; }
/// <summary>
/// Parameterless constructor For JSON.NET deserialization.
/// </summary>
protected Datum()
{
}
protected Datum(DateTimeOffset timestamp)
{
_timestamp = timestamp;
_deviceId = SensusServiceHelper.Get().DeviceId;
_anonymized = false;
_buildId = SensusServiceHelper.BUILD_ID;
Id = Guid.NewGuid().ToString();
}
public string GetJSON(AnonymizedJsonContractResolver anonymizationContractResolver, bool indented)
{
JSON_SERIALIZER_SETTINGS.ContractResolver = anonymizationContractResolver;
// datum objects can be anonymized by omitting values. this is accomplished by setting them to null. also, some fields in datum
// objects might have unreliably obtained values (e.g., GPS location might fail and be null). if we ignore fields with null
// values when serializing, the resulting JSON and other derived structures (e.g., data frames in R) will have differing columns.
// so we should include null values to ensure that all JSON values are always included.
JSON_SERIALIZER_SETTINGS.NullValueHandling = NullValueHandling.Include;
string json = JsonConvert.SerializeObject(this, indented ? Formatting.Indented : Formatting.None, JSON_SERIALIZER_SETTINGS);
// if the json should not be indented, replace all newlines with white space
if (!indented)
{
json = json.Replace('\n', ' ').Replace('\r', ' ');
}
return json.Trim();
}
public override int GetHashCode()
{
return _hashCode;
}
public override bool Equals(object obj)
{
return obj is Datum && (obj as Datum)._id == _id;
}
public override string ToString()
{
return "Type: " + GetType().Name + Environment.NewLine +
"Device ID: " + _deviceId + Environment.NewLine +
"Timestamp: " + _timestamp;
}
}
}
| |
using System;
using NUnit.Framework;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Icao;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Utilities.Test;
namespace Org.BouncyCastle.Asn1.Tests
{
[TestFixture]
public class LDSSecurityObjectUnitTest
: SimpleTest
{
public override string Name
{
get { return "LDSSecurityObject"; }
}
private byte[] GenerateHash()
{
Random rand = new Random();
byte[] bytes = new byte[20];
rand.NextBytes(bytes);
return bytes;
}
public override void PerformTest()
{
AlgorithmIdentifier algoId = new AlgorithmIdentifier("1.3.14.3.2.26");
DataGroupHash[] datas = new DataGroupHash[2];
datas[0] = new DataGroupHash(1, new DerOctetString(GenerateHash()));
datas[1] = new DataGroupHash(2, new DerOctetString(GenerateHash()));
LdsSecurityObject so = new LdsSecurityObject(algoId, datas);
CheckConstruction(so, algoId, datas);
LdsVersionInfo versionInfo = new LdsVersionInfo("Hello", "world");
so = new LdsSecurityObject(algoId, datas, versionInfo);
CheckConstruction(so, algoId, datas, versionInfo);
try
{
LdsSecurityObject.GetInstance(null);
}
catch (Exception)
{
Fail("GetInstance() failed to handle null.");
}
try
{
LdsSecurityObject.GetInstance(new object());
Fail("GetInstance() failed to detect bad object.");
}
catch (ArgumentException)
{
// expected
}
try
{
LdsSecurityObject.GetInstance(DerSequence.Empty);
Fail("constructor failed to detect empty sequence.");
}
catch (ArgumentException)
{
// expected
}
try
{
new LdsSecurityObject(algoId, new DataGroupHash[1]);
Fail("constructor failed to detect small DataGroupHash array.");
}
catch (ArgumentException)
{
// expected
}
try
{
new LdsSecurityObject(algoId, new DataGroupHash[LdsSecurityObject.UBDataGroups + 1]);
Fail("constructor failed to out of bounds DataGroupHash array.");
}
catch (ArgumentException)
{
// expected
}
}
private void CheckConstruction(
LdsSecurityObject so,
AlgorithmIdentifier digestAlgorithmIdentifier,
DataGroupHash[] datagroupHash)
{
CheckStatement(so, digestAlgorithmIdentifier, datagroupHash, null);
so = LdsSecurityObject.GetInstance(so);
CheckStatement(so, digestAlgorithmIdentifier, datagroupHash, null);
Asn1Sequence seq = (Asn1Sequence) Asn1Object.FromByteArray(
so.ToAsn1Object().GetEncoded());
so = LdsSecurityObject.GetInstance(seq);
CheckStatement(so, digestAlgorithmIdentifier, datagroupHash, null);
}
private void CheckConstruction(
LdsSecurityObject so,
AlgorithmIdentifier digestAlgorithmIdentifier,
DataGroupHash[] datagroupHash,
LdsVersionInfo versionInfo)
{
if (!so.Version.Equals(BigInteger.One))
{
Fail("version number not 1");
}
CheckStatement(so, digestAlgorithmIdentifier, datagroupHash, versionInfo);
so = LdsSecurityObject.GetInstance(so);
CheckStatement(so, digestAlgorithmIdentifier, datagroupHash, versionInfo);
Asn1Sequence seq = (Asn1Sequence) Asn1Object.FromByteArray(
so.ToAsn1Object().GetEncoded());
so = LdsSecurityObject.GetInstance(seq);
CheckStatement(so, digestAlgorithmIdentifier, datagroupHash, versionInfo);
}
private void CheckStatement(
LdsSecurityObject so,
AlgorithmIdentifier digestAlgorithmIdentifier,
DataGroupHash[] datagroupHash,
LdsVersionInfo versionInfo)
{
if (digestAlgorithmIdentifier != null)
{
if (!so.DigestAlgorithmIdentifier.Equals(digestAlgorithmIdentifier))
{
Fail("ids don't match.");
}
}
else if (so.DigestAlgorithmIdentifier != null)
{
Fail("digest algorithm Id found when none expected.");
}
if (datagroupHash != null)
{
DataGroupHash[] datas = so.GetDatagroupHash();
for (int i = 0; i != datas.Length; i++)
{
if (!datagroupHash[i].Equals(datas[i]))
{
Fail("name registration authorities don't match.");
}
}
}
else if (so.GetDatagroupHash() != null)
{
Fail("data hash groups found when none expected.");
}
if (versionInfo != null)
{
if (!versionInfo.Equals(so.VersionInfo))
{
Fail("versionInfo doesn't match");
}
}
else if (so.VersionInfo != null)
{
Fail("version info found when none expected.");
}
}
public static void Main(
string[] args)
{
RunTest(new LDSSecurityObjectUnitTest());
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using NUnit.Core;
using NUnit.Core.Filters;
using UnityEditor;
using UnityEngine;
using UnityTest.UnitTestRunner;
namespace UnityTest
{
public class NUnitTestEngine : IUnitTestEngine
{
static readonly string[] k_WhitelistedAssemblies =
{
"Assembly-CSharp-Editor",
"Assembly-Boo-Editor",
"Assembly-UnityScript-Editor"
};
private TestSuite m_TestSuite;
public UnitTestRendererLine GetTests(out UnitTestResult[] results, out string[] categories)
{
if (m_TestSuite == null)
{
var assemblies = GetAssembliesWithTests().Select(a => a.Location).ToList();
TestSuite suite = PrepareTestSuite(assemblies);
m_TestSuite = suite;
}
var resultList = new List<UnitTestResult>();
var categoryList = new HashSet<string>();
UnitTestRendererLine lines = null;
if (m_TestSuite != null)
lines = ParseTestList(m_TestSuite, resultList, categoryList).Single();
results = resultList.ToArray();
categories = categoryList.ToArray();
return lines;
}
private UnitTestRendererLine[] ParseTestList(Test test, List<UnitTestResult> results, HashSet<string> categories)
{
foreach (string category in test.Categories)
categories.Add(category);
if (test is TestMethod)
{
var result = new UnitTestResult
{
Test = new UnitTestInfo(test as TestMethod)
};
results.Add(result);
return new[] { new TestLine(test as TestMethod, result.Id) };
}
GroupLine group = null;
if (test is TestSuite)
group = new GroupLine(test as TestSuite);
var namespaceList = new List<UnitTestRendererLine>(new[] {group});
foreach (Test result in test.Tests)
{
if (result is NamespaceSuite || test is TestAssembly)
namespaceList.AddRange(ParseTestList(result, results, categories));
else
group.AddChildren(ParseTestList(result, results, categories));
}
namespaceList.Sort();
return namespaceList.ToArray();
}
public void RunTests(ITestRunnerCallback testRunnerEventListener)
{
RunTests(TestFilter.Empty, testRunnerEventListener);
}
public void RunTests(TestFilter filter, ITestRunnerCallback testRunnerEventListener)
{
try
{
if (testRunnerEventListener != null)
testRunnerEventListener.RunStarted(m_TestSuite.TestName.FullName, m_TestSuite.TestCount);
ExecuteTestSuite(m_TestSuite, testRunnerEventListener, filter);
if (testRunnerEventListener != null)
testRunnerEventListener.RunFinished();
}
catch (Exception e)
{
Debug.LogException(e);
if (testRunnerEventListener != null)
testRunnerEventListener.RunFinishedException(e);
}
}
public static Assembly[] GetAssembliesWithTests()
{
var libs = new List<Assembly>();
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
if (assembly.GetReferencedAssemblies().All(a => a.Name != "nunit.framework"))
continue;
if (assembly.Location.Replace('\\', '/').StartsWith(Application.dataPath)
|| k_WhitelistedAssemblies.Contains(assembly.GetName().Name))
libs.Add(assembly);
}
return libs.ToArray();
}
private TestSuite PrepareTestSuite(List<String> assemblyList)
{
CoreExtensions.Host.InitializeService();
var testPackage = new TestPackage(PlayerSettings.productName, assemblyList);
var builder = new TestSuiteBuilder();
TestExecutionContext.CurrentContext.TestPackage = testPackage;
TestSuite suite = builder.Build(testPackage);
return suite;
}
private void ExecuteTestSuite(TestSuite suite, ITestRunnerCallback testRunnerEventListener, TestFilter filter)
{
EventListener eventListener;
if (testRunnerEventListener == null)
eventListener = new NullListener();
else
eventListener = new TestRunnerEventListener(testRunnerEventListener);
TestExecutionContext.CurrentContext.Out = new EventListenerTextWriter(eventListener, TestOutputType.Out);
TestExecutionContext.CurrentContext.Error = new EventListenerTextWriter(eventListener, TestOutputType.Error);
suite.Run(eventListener, GetFilter(filter));
}
private ITestFilter GetFilter(TestFilter filter)
{
var nUnitFilter = new AndFilter();
if (filter.names != null && filter.names.Length > 0)
nUnitFilter.Add(new SimpleNameFilter(filter.names));
if (filter.categories != null && filter.categories.Length > 0)
nUnitFilter.Add(new CategoryFilter(filter.categories));
if (filter.objects != null && filter.objects.Length > 0)
nUnitFilter.Add(new OrFilter(filter.objects.Where(o => o is TestName).Select(o => new NameFilter(o as TestName)).ToArray()));
return nUnitFilter;
}
public class TestRunnerEventListener : EventListener
{
private readonly ITestRunnerCallback m_TestRunnerEventListener;
private StringBuilder m_testLog;
public TestRunnerEventListener(ITestRunnerCallback testRunnerEventListener)
{
m_TestRunnerEventListener = testRunnerEventListener;
}
public void RunStarted(string name, int testCount)
{
m_TestRunnerEventListener.RunStarted(name, testCount);
}
public void RunFinished(NUnit.Core.TestResult result)
{
m_TestRunnerEventListener.RunFinished();
}
public void RunFinished(Exception exception)
{
m_TestRunnerEventListener.RunFinishedException(exception);
}
public void TestStarted(TestName testName)
{
m_testLog = new StringBuilder();
m_TestRunnerEventListener.TestStarted(testName.FullName);
}
public void TestFinished(NUnit.Core.TestResult result)
{
m_TestRunnerEventListener.TestFinished(result.UnitTestResult(m_testLog.ToString()));
m_testLog = null;
}
public void SuiteStarted(TestName testName)
{
}
public void SuiteFinished(NUnit.Core.TestResult result)
{
}
public void UnhandledException(Exception exception)
{
}
public void TestOutput(TestOutput testOutput)
{
if (m_testLog != null)
m_testLog.AppendLine(testOutput.Text);
}
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using ASC.Common.Logging;
using Twilio.Clients;
using Twilio.Exceptions;
using Twilio.Jwt;
using Twilio.Jwt.Client;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Rest.Api.V2010.Account.AvailablePhoneNumberCountry;
using Twilio.Types;
using RecordingResource = Twilio.Rest.Api.V2010.Account.Call.RecordingResource;
namespace ASC.VoipService.Twilio
{
public class TwilioProvider : IVoipProvider
{
private readonly string accountSid;
private readonly string authToken;
private readonly TwilioRestClient client;
public TwilioProvider(string accountSid, string authToken)
{
if (string.IsNullOrEmpty(accountSid)) throw new ArgumentNullException("accountSid");
if (string.IsNullOrEmpty(authToken)) throw new ArgumentNullException("authToken");
this.authToken = authToken;
this.accountSid = accountSid;
client = new TwilioRestClient(accountSid, authToken);
}
#region Call
public VoipRecord GetRecord(string callId, string recordSid)
{
var logger = LogManager.GetLogger("ASC");
logger.DebugFormat("recordSid {0}", recordSid);
var result = new VoipRecord { Id = recordSid };
var count = 6;
while (count > 0)
{
try
{
var record = RecordingResource.Fetch(callId, recordSid, client: client);
if (!record.Price.HasValue)
{
count--;
Thread.Sleep(10000);
continue;
}
result.Price = (-1) * record.Price.Value;
logger.DebugFormat("recordSid {0} price {1}", recordSid, result.Price);
result.Duration = Convert.ToInt32(record.Duration);
if (record.Uri != null)
{
result.Uri = record.Uri;
}
break;
}
catch (ApiException)
{
count--;
Thread.Sleep(10000);
}
}
return result;
}
public void CreateQueue(VoipPhone newPhone)
{
newPhone.Settings.Queue = ((TwilioPhone)newPhone).CreateQueue(newPhone.Number, 5, string.Empty, 5);
}
#endregion
#region Numbers
public VoipPhone BuyNumber(string phoneNumber)
{
var newNumber = IncomingPhoneNumberResource.Create(
new CreateIncomingPhoneNumberOptions
{
PathAccountSid = accountSid,
PhoneNumber = new PhoneNumber(phoneNumber)
}, client);
return new TwilioPhone(client) { Id = newNumber.Sid, Number = phoneNumber.Substring(1) };
}
public VoipPhone DeleteNumber(VoipPhone phone)
{
IncomingPhoneNumberResource.Delete(phone.Id, client: client);
return phone;
}
public IEnumerable<VoipPhone> GetExistingPhoneNumbers()
{
var result = IncomingPhoneNumberResource.Read(client: client);
return result.Select(r => new TwilioPhone(client) { Id = r.Sid, Number = r.PhoneNumber.ToString() });
}
public IEnumerable<VoipPhone> GetAvailablePhoneNumbers(PhoneNumberType phoneNumberType, string isoCountryCode)
{
switch (phoneNumberType)
{
case PhoneNumberType.Local:
return LocalResource.Read(isoCountryCode, voiceEnabled: true, client: client).Select(r => new TwilioPhone(client) { Number = r.PhoneNumber.ToString() });
case PhoneNumberType.TollFree:
return TollFreeResource.Read(isoCountryCode, voiceEnabled: true, client: client).Select(r => new TwilioPhone(client) { Number = r.PhoneNumber.ToString() });
}
return new List<VoipPhone>();
}
public VoipPhone GetPhone(string phoneSid)
{
var phone = IncomingPhoneNumberResource.Fetch(phoneSid, client: client);
var result = new TwilioPhone(client) { Id = phone.Sid, Number = phone.PhoneNumber.ToString(), Settings = new TwilioVoipSettings() };
if (phone.VoiceUrl == null)
{
result.Settings.VoiceUrl = result.Settings.Connect(false);
}
return result;
}
public VoipPhone GetPhone(object[] data)
{
return new TwilioPhone(client)
{
Id = (string)data[0],
Number = (string)data[1],
Alias = (string)data[2],
Settings = new TwilioVoipSettings((string)data[3])
};
}
public VoipCall GetCall(string callId)
{
var result = new VoipCall { Id = callId };
var count = 6;
while (count > 0)
{
try
{
var call = CallResource.Fetch(result.Id, client: client);
if (!call.Price.HasValue || string.IsNullOrEmpty(call.Duration))
{
count--;
Thread.Sleep(10000);
continue;
}
result.Price = (-1) * call.Price.Value;
result.DialDuration = Convert.ToInt32(call.Duration);
break;
}
catch (ApiException)
{
count--;
Thread.Sleep(10000);
}
}
return result;
}
public string GetToken(Agent agent, int seconds = 60 * 60 * 24)
{
var scopes = new HashSet<IScope>
{
new IncomingClientScope(agent.ClientID)
};
var capability = new ClientCapability(accountSid, authToken, scopes: scopes);
return capability.ToJwt();
}
public void UpdateSettings(VoipPhone phone)
{
IncomingPhoneNumberResource.Update(phone.Id, voiceUrl: new Uri(phone.Settings.Connect(false)), client: client);
}
public void DisablePhone(VoipPhone phone)
{
IncomingPhoneNumberResource.Update(phone.Id, voiceUrl: new Uri("https://demo.twilio.com/welcome/voice/"), client: client);
}
#endregion
}
public enum PhoneNumberType
{
Local,
/* Mobile,*/
TollFree
}
}
| |
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Worker;
using Moq;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Xunit;
using Microsoft.TeamFoundation.DistributedTask.Orchestration.Server.Expressions;
namespace Microsoft.VisualStudio.Services.Agent.Tests.Worker
{
public sealed class StepsRunnerL0
{
private Mock<IExecutionContext> _ec;
private StepsRunner _stepsRunner;
private Variables _variables;
private TestHostContext CreateTestContext([CallerMemberName] String testName = "")
{
var hc = new TestHostContext(this, testName);
var expressionManager = new ExpressionManager();
expressionManager.Initialize(hc);
hc.SetSingleton<IExpressionManager>(expressionManager);
List<string> warnings;
_variables = new Variables(
hostContext: hc,
copy: new Dictionary<string, string>(),
maskHints: new List<MaskHint>(),
warnings: out warnings);
_ec = new Mock<IExecutionContext>();
_ec.SetupAllProperties();
_ec.Setup(x => x.Variables).Returns(_variables);
_stepsRunner = new StepsRunner();
_stepsRunner.Initialize(hc);
return hc;
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async Task RunCritialStepsAllStepPass()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var variableSets = new[]
{
new[] { CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded) },
new[] { CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.SucceededOrFailed) },
new[] { CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Always) }
};
foreach (var variableSet in variableSets)
{
_ec.Object.Result = null;
// Act.
await _stepsRunner.RunAsync(
jobContext: _ec.Object,
steps: variableSet.Select(x => x.Object).ToList(),
stage: JobRunStage.PreJob);
// Assert.
Assert.Equal(TaskResult.Succeeded, _ec.Object.Result ?? TaskResult.Succeeded);
Assert.Equal(2, variableSet.Length);
variableSet[0].Verify(x => x.RunAsync());
variableSet[1].Verify(x => x.RunAsync());
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async Task RunCritialStepsStopOnStepFailure()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var variableSets = new[]
{
new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded) },
new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.SucceededOrFailed) },
new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Always) },
};
foreach (var variableSet in variableSets)
{
_ec.Object.Result = null;
// Act.
await _stepsRunner.RunAsync(
jobContext: _ec.Object,
steps: variableSet.Select(x => x.Object).ToList(),
stage: JobRunStage.PreJob);
// Assert.
Assert.Equal(TaskResult.Failed, _ec.Object.Result);
Assert.Equal(2, variableSet.Length);
variableSet[0].Verify(x => x.RunAsync());
variableSet[1].Verify(x => x.RunAsync(), Times.Never);
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async Task RunCritialStepsContinueOnError()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var variableSets = new[]
{
new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded, true), CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded) },
new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded, true), CreateStep(TaskResult.Succeeded, ExpressionManager.SucceededOrFailed) },
new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded, true), CreateStep(TaskResult.Succeeded, ExpressionManager.Always) },
new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded, true), CreateStep(TaskResult.Failed, ExpressionManager.Succeeded, true) },
new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded, true), CreateStep(TaskResult.Failed, ExpressionManager.SucceededOrFailed, true) },
new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded, true), CreateStep(TaskResult.Failed, ExpressionManager.Always, true) }
};
foreach (var variableSet in variableSets)
{
_ec.Object.Result = null;
// Act.
await _stepsRunner.RunAsync(
jobContext: _ec.Object,
steps: variableSet.Select(x => x.Object).ToList(),
stage: JobRunStage.PreJob);
// Assert.
Assert.Equal(TaskResult.SucceededWithIssues, _ec.Object.Result);
Assert.Equal(2, variableSet.Length);
variableSet[0].Verify(x => x.RunAsync());
variableSet[1].Verify(x => x.RunAsync());
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async Task RunPostJobStepsIgnoreCondition()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var variableSets = new[]
{
new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded) },
new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.SucceededOrFailed) },
new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Always) },
};
foreach (var variableSet in variableSets)
{
_ec.Object.Result = null;
// Act.
await _stepsRunner.RunAsync(
jobContext: _ec.Object,
steps: variableSet.Select(x => x.Object).ToList(),
stage: JobRunStage.PostJob);
// Assert.
Assert.Equal(TaskResult.Failed, _ec.Object.Result);
Assert.Equal(2, variableSet.Length);
variableSet[0].Verify(x => x.RunAsync());
variableSet[1].Verify(x => x.RunAsync());
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async Task RunNormalStepsAllStepPass()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var variableSets = new[]
{
new[] { CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded) },
new[] { CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.SucceededOrFailed) },
new[] { CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Always) }
};
foreach (var variableSet in variableSets)
{
_ec.Object.Result = null;
// Act.
await _stepsRunner.RunAsync(
jobContext: _ec.Object,
steps: variableSet.Select(x => x.Object).ToList(),
stage: JobRunStage.Main);
// Assert.
Assert.Equal(TaskResult.Succeeded, _ec.Object.Result ?? TaskResult.Succeeded);
Assert.Equal(2, variableSet.Length);
variableSet[0].Verify(x => x.RunAsync());
variableSet[1].Verify(x => x.RunAsync());
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async Task RunNormalStepsContinueOnError()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var variableSets = new[]
{
new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded, true), CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded) },
new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded, true), CreateStep(TaskResult.Succeeded, ExpressionManager.SucceededOrFailed) },
new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded, true), CreateStep(TaskResult.Succeeded, ExpressionManager.Always) },
new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded, true), CreateStep(TaskResult.Failed, ExpressionManager.Succeeded, true) },
new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded, true), CreateStep(TaskResult.Failed, ExpressionManager.SucceededOrFailed, true) },
new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded, true), CreateStep(TaskResult.Failed, ExpressionManager.Always, true) }
};
foreach (var variableSet in variableSets)
{
_ec.Object.Result = null;
// Act.
await _stepsRunner.RunAsync(
jobContext: _ec.Object,
steps: variableSet.Select(x => x.Object).ToList(),
stage: JobRunStage.Main);
// Assert.
Assert.Equal(TaskResult.SucceededWithIssues, _ec.Object.Result);
Assert.Equal(2, variableSet.Length);
variableSet[0].Verify(x => x.RunAsync());
variableSet[1].Verify(x => x.RunAsync());
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async Task RunsAfterFailureBasedOnCondition()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var variableSets = new[]
{
new
{
Steps = new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded) },
Expected = false,
},
new
{
Steps = new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.SucceededOrFailed) },
Expected = true,
},
};
foreach (var variableSet in variableSets)
{
_ec.Object.Result = null;
// Act.
await _stepsRunner.RunAsync(
jobContext: _ec.Object,
steps: variableSet.Steps.Select(x => x.Object).ToList(),
stage: JobRunStage.Main);
// Assert.
Assert.Equal(TaskResult.Failed, _ec.Object.Result ?? TaskResult.Succeeded);
Assert.Equal(2, variableSet.Steps.Length);
variableSet.Steps[0].Verify(x => x.RunAsync());
variableSet.Steps[1].Verify(x => x.RunAsync(), variableSet.Expected ? Times.Once() : Times.Never());
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async Task RunsAlwaysSteps()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var variableSets = new[]
{
new
{
Steps = new[] { CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Always) },
Expected = TaskResult.Succeeded,
},
new
{
Steps = new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Always) },
Expected = TaskResult.Failed,
},
new
{
Steps = new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Always) },
Expected = TaskResult.Failed,
},
new
{
Steps = new[] { CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded), CreateStep(TaskResult.Failed, ExpressionManager.Always) },
Expected = TaskResult.Failed,
},
new
{
Steps = new[] { CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded), CreateStep(TaskResult.Failed, ExpressionManager.Always, true) },
Expected = TaskResult.SucceededWithIssues,
},
};
foreach (var variableSet in variableSets)
{
_ec.Object.Result = null;
// Act.
await _stepsRunner.RunAsync(
jobContext: _ec.Object,
steps: variableSet.Steps.Select(x => x.Object).ToList(),
stage: JobRunStage.Main);
// Assert.
Assert.Equal(variableSet.Expected, _ec.Object.Result ?? TaskResult.Succeeded);
Assert.Equal(2, variableSet.Steps.Length);
variableSet.Steps[0].Verify(x => x.RunAsync());
variableSet.Steps[1].Verify(x => x.RunAsync());
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async Task SetsJobResultCorrectly()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var variableSets = new[]
{
new
{
Steps = new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded) },
Expected = TaskResult.Failed
},
new
{
Steps = new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.SucceededOrFailed) },
Expected = TaskResult.Failed
},
new
{
Steps = new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Always) },
Expected = TaskResult.Failed
},
new
{
Steps = new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded, continueOnError: true), CreateStep(TaskResult.Failed, ExpressionManager.Succeeded) },
Expected = TaskResult.Failed
},
new
{
Steps = new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded, continueOnError: true), CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded) },
Expected = TaskResult.SucceededWithIssues
},
new
{
Steps = new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded, continueOnError: true), CreateStep(TaskResult.Failed, ExpressionManager.Succeeded, continueOnError: true) },
Expected = TaskResult.SucceededWithIssues
},
new
{
Steps = new[] { CreateStep(TaskResult.Succeeded, ExpressionManager.SucceededOrFailed) },
Expected = TaskResult.Succeeded
},
new
{
Steps = new[] { CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded), CreateStep(TaskResult.Failed, ExpressionManager.Succeeded) },
Expected = TaskResult.Failed
},
new
{
Steps = new[] { CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded), CreateStep(TaskResult.SucceededWithIssues, ExpressionManager.Succeeded) },
Expected = TaskResult.SucceededWithIssues
},
new
{
Steps = new[] { CreateStep(TaskResult.SucceededWithIssues, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded) },
Expected = TaskResult.SucceededWithIssues
},
new
{
Steps = new[] { CreateStep(TaskResult.SucceededWithIssues, ExpressionManager.Succeeded), CreateStep(TaskResult.Failed, ExpressionManager.Succeeded) },
Expected = TaskResult.Failed
},
// Abandoned
// Canceled
// Failed
// Skipped
// Succeeded
// SucceededWithIssues
};
foreach (var variableSet in variableSets)
{
_ec.Object.Result = null;
// Act.
await _stepsRunner.RunAsync(
jobContext: _ec.Object,
steps: variableSet.Steps.Select(x => x.Object).ToList(),
stage: JobRunStage.Main);
// Assert.
Assert.True(
variableSet.Expected == (_ec.Object.Result ?? TaskResult.Succeeded),
$"Expected '{variableSet.Expected}'. Actual '{_ec.Object.Result}'. Steps: {FormatSteps(variableSet.Steps)}");
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async Task SkipsAfterFailureOnlyBaseOnCondition()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var variableSets = new[]
{
new
{
Step = new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded) },
Expected = false
},
new
{
Step = new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.SucceededOrFailed) },
Expected = true
},
new
{
Step = new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Always) },
Expected = true
}
};
foreach (var variableSet in variableSets)
{
_ec.Object.Result = null;
// Act.
await _stepsRunner.RunAsync(
jobContext: _ec.Object,
steps: variableSet.Step.Select(x => x.Object).ToList(),
stage: JobRunStage.Main);
// Assert.
Assert.Equal(2, variableSet.Step.Length);
variableSet.Step[0].Verify(x => x.RunAsync());
variableSet.Step[1].Verify(x => x.RunAsync(), variableSet.Expected ? Times.Once() : Times.Never());
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async Task AlwaysMeansAlways()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var variableSets = new[]
{
new[] { CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Always) },
new[] { CreateStep(TaskResult.SucceededWithIssues, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Always) },
new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Always) },
new[] { CreateStep(TaskResult.Canceled, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Always) }
};
foreach (var variableSet in variableSets)
{
_ec.Object.Result = null;
// Act.
await _stepsRunner.RunAsync(
jobContext: _ec.Object,
steps: variableSet.Select(x => x.Object).ToList(),
stage: JobRunStage.Main);
// Assert.
Assert.Equal(2, variableSet.Length);
variableSet[0].Verify(x => x.RunAsync());
variableSet[1].Verify(x => x.RunAsync(), Times.Once());
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async Task TreatsConditionErrorAsFailure()
{
using (TestHostContext hc = CreateTestContext())
{
var expressionManager = new Mock<IExpressionManager>();
expressionManager.Object.Initialize(hc);
hc.SetSingleton<IExpressionManager>(expressionManager.Object);
expressionManager.Setup(x => x.Evaluate(It.IsAny<IExecutionContext>(), It.IsAny<INode>(), It.IsAny<bool>())).Throws(new Exception());
// Arrange.
var variableSets = new[]
{
new[] { CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded) },
new[] { CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded) },
};
foreach (var variableSet in variableSets)
{
_ec.Object.Result = null;
// Act.
await _stepsRunner.RunAsync(
jobContext: _ec.Object,
steps: variableSet.Select(x => x.Object).ToList(),
stage: JobRunStage.Main);
// Assert.
Assert.Equal(TaskResult.Failed, _ec.Object.Result ?? TaskResult.Succeeded);
}
}
}
private Mock<IStep> CreateStep(TaskResult result, INode condition, Boolean continueOnError = false)
{
// Setup the step.
var step = new Mock<IStep>();
step.Setup(x => x.Condition).Returns(condition);
step.Setup(x => x.ContinueOnError).Returns(continueOnError);
step.Setup(x => x.Enabled).Returns(true);
step.Setup(x => x.RunAsync()).Returns(Task.CompletedTask);
// Setup the step execution context.
var stepContext = new Mock<IExecutionContext>();
stepContext.SetupAllProperties();
stepContext.Setup(x => x.Variables).Returns(_variables);
stepContext.Setup(x => x.Complete(It.IsAny<TaskResult?>(), It.IsAny<string>()))
.Callback((TaskResult? r, string currentOperation) =>
{
if (r != null)
{
stepContext.Object.Result = r;
}
});
stepContext.Object.Result = result;
step.Setup(x => x.ExecutionContext).Returns(stepContext.Object);
return step;
}
private string FormatSteps(IEnumerable<Mock<IStep>> steps)
{
return String.Join(
" ; ",
steps.Select(x => String.Format(
CultureInfo.InvariantCulture,
"Returns={0},Condition=[{1}],ContinueOnError={2},Enabled={3}",
x.Object.ExecutionContext.Result,
x.Object.Condition,
x.Object.ContinueOnError,
x.Object.Enabled)));
}
}
}
| |
#region license
// Copyright (c) 2009 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
//
// DO NOT EDIT THIS FILE!
//
// This file was generated automatically by astgen.boo.
//
namespace Boo.Lang.Compiler.Ast
{
using System.Collections;
using System.Runtime.Serialization;
[System.Serializable]
public partial class Destructor : Method
{
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public Destructor CloneNode()
{
return (Destructor)Clone();
}
/// <summary>
/// <see cref="Node.CleanClone"/>
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public Destructor CleanClone()
{
return (Destructor)base.CleanClone();
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public NodeType NodeType
{
get { return NodeType.Destructor; }
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public void Accept(IAstVisitor visitor)
{
visitor.OnDestructor(this);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Matches(Node node)
{
if (node == null) return false;
if (NodeType != node.NodeType) return false;
var other = ( Destructor)node;
if (_modifiers != other._modifiers) return NoMatch("Destructor._modifiers");
if (_name != other._name) return NoMatch("Destructor._name");
if (!Node.AllMatch(_attributes, other._attributes)) return NoMatch("Destructor._attributes");
if (!Node.AllMatch(_parameters, other._parameters)) return NoMatch("Destructor._parameters");
if (!Node.AllMatch(_genericParameters, other._genericParameters)) return NoMatch("Destructor._genericParameters");
if (!Node.Matches(_returnType, other._returnType)) return NoMatch("Destructor._returnType");
if (!Node.AllMatch(_returnTypeAttributes, other._returnTypeAttributes)) return NoMatch("Destructor._returnTypeAttributes");
if (!Node.Matches(_body, other._body)) return NoMatch("Destructor._body");
if (!Node.AllMatch(_locals, other._locals)) return NoMatch("Destructor._locals");
if (_implementationFlags != other._implementationFlags) return NoMatch("Destructor._implementationFlags");
if (!Node.Matches(_explicitInfo, other._explicitInfo)) return NoMatch("Destructor._explicitInfo");
return true;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Replace(Node existing, Node newNode)
{
if (base.Replace(existing, newNode))
{
return true;
}
if (_attributes != null)
{
Attribute item = existing as Attribute;
if (null != item)
{
Attribute newItem = (Attribute)newNode;
if (_attributes.Replace(item, newItem))
{
return true;
}
}
}
if (_parameters != null)
{
ParameterDeclaration item = existing as ParameterDeclaration;
if (null != item)
{
ParameterDeclaration newItem = (ParameterDeclaration)newNode;
if (_parameters.Replace(item, newItem))
{
return true;
}
}
}
if (_genericParameters != null)
{
GenericParameterDeclaration item = existing as GenericParameterDeclaration;
if (null != item)
{
GenericParameterDeclaration newItem = (GenericParameterDeclaration)newNode;
if (_genericParameters.Replace(item, newItem))
{
return true;
}
}
}
if (_returnType == existing)
{
this.ReturnType = (TypeReference)newNode;
return true;
}
if (_returnTypeAttributes != null)
{
Attribute item = existing as Attribute;
if (null != item)
{
Attribute newItem = (Attribute)newNode;
if (_returnTypeAttributes.Replace(item, newItem))
{
return true;
}
}
}
if (_body == existing)
{
this.Body = (Block)newNode;
return true;
}
if (_locals != null)
{
Local item = existing as Local;
if (null != item)
{
Local newItem = (Local)newNode;
if (_locals.Replace(item, newItem))
{
return true;
}
}
}
if (_explicitInfo == existing)
{
this.ExplicitInfo = (ExplicitMemberInfo)newNode;
return true;
}
return false;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public object Clone()
{
Destructor clone = (Destructor)FormatterServices.GetUninitializedObject(typeof(Destructor));
clone._lexicalInfo = _lexicalInfo;
clone._endSourceLocation = _endSourceLocation;
clone._documentation = _documentation;
clone._isSynthetic = _isSynthetic;
clone._entity = _entity;
if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone();
clone._modifiers = _modifiers;
clone._name = _name;
if (null != _attributes)
{
clone._attributes = _attributes.Clone() as AttributeCollection;
clone._attributes.InitializeParent(clone);
}
if (null != _parameters)
{
clone._parameters = _parameters.Clone() as ParameterDeclarationCollection;
clone._parameters.InitializeParent(clone);
}
if (null != _genericParameters)
{
clone._genericParameters = _genericParameters.Clone() as GenericParameterDeclarationCollection;
clone._genericParameters.InitializeParent(clone);
}
if (null != _returnType)
{
clone._returnType = _returnType.Clone() as TypeReference;
clone._returnType.InitializeParent(clone);
}
if (null != _returnTypeAttributes)
{
clone._returnTypeAttributes = _returnTypeAttributes.Clone() as AttributeCollection;
clone._returnTypeAttributes.InitializeParent(clone);
}
if (null != _body)
{
clone._body = _body.Clone() as Block;
clone._body.InitializeParent(clone);
}
if (null != _locals)
{
clone._locals = _locals.Clone() as LocalCollection;
clone._locals.InitializeParent(clone);
}
clone._implementationFlags = _implementationFlags;
if (null != _explicitInfo)
{
clone._explicitInfo = _explicitInfo.Clone() as ExplicitMemberInfo;
clone._explicitInfo.InitializeParent(clone);
}
return clone;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override internal void ClearTypeSystemBindings()
{
_annotations = null;
_entity = null;
if (null != _attributes)
{
_attributes.ClearTypeSystemBindings();
}
if (null != _parameters)
{
_parameters.ClearTypeSystemBindings();
}
if (null != _genericParameters)
{
_genericParameters.ClearTypeSystemBindings();
}
if (null != _returnType)
{
_returnType.ClearTypeSystemBindings();
}
if (null != _returnTypeAttributes)
{
_returnTypeAttributes.ClearTypeSystemBindings();
}
if (null != _body)
{
_body.ClearTypeSystemBindings();
}
if (null != _locals)
{
_locals.ClearTypeSystemBindings();
}
if (null != _explicitInfo)
{
_explicitInfo.ClearTypeSystemBindings();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
////////////////////////////////////////////////////////////////////////////
//
//
//
// Purpose: This class implements a set of methods for comparing
// strings.
//
//
////////////////////////////////////////////////////////////////////////////
using System.Reflection;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
namespace System.Globalization
{
[Flags]
public enum CompareOptions
{
None = 0x00000000,
IgnoreCase = 0x00000001,
IgnoreNonSpace = 0x00000002,
IgnoreSymbols = 0x00000004,
IgnoreKanaType = 0x00000008, // ignore kanatype
IgnoreWidth = 0x00000010, // ignore width
OrdinalIgnoreCase = 0x10000000, // This flag can not be used with other flags.
StringSort = 0x20000000, // use string sort method
Ordinal = 0x40000000, // This flag can not be used with other flags.
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public partial class CompareInfo : IDeserializationCallback
{
// Mask used to check if IndexOf()/LastIndexOf()/IsPrefix()/IsPostfix() has the right flags.
private const CompareOptions ValidIndexMaskOffFlags =
~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType);
// Mask used to check if Compare() has the right flags.
private const CompareOptions ValidCompareMaskOffFlags =
~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType | CompareOptions.StringSort);
// Mask used to check if GetHashCodeOfString() has the right flags.
private const CompareOptions ValidHashCodeOfStringMaskOffFlags =
~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType);
// Mask used to check if we have the right flags.
private const CompareOptions ValidSortkeyCtorMaskOffFlags =
~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType | CompareOptions.StringSort);
// Cache the invariant CompareInfo
internal static readonly CompareInfo Invariant = CultureInfo.InvariantCulture.CompareInfo;
//
// CompareInfos have an interesting identity. They are attached to the locale that created them,
// ie: en-US would have an en-US sort. For haw-US (custom), then we serialize it as haw-US.
// The interesting part is that since haw-US doesn't have its own sort, it has to point at another
// locale, which is what SCOMPAREINFO does.
[OptionalField(VersionAdded = 2)]
private string m_name; // The name used to construct this CompareInfo. Do not rename (binary serialization)
[NonSerialized]
private string _sortName; // The name that defines our behavior
[OptionalField(VersionAdded = 3)]
private SortVersion m_SortVersion; // Do not rename (binary serialization)
// _invariantMode is defined for the perf reason as accessing the instance field is faster than access the static property GlobalizationMode.Invariant
[NonSerialized]
private readonly bool _invariantMode = GlobalizationMode.Invariant;
private int culture; // Do not rename (binary serialization). The fields sole purpose is to support Desktop serialization.
internal CompareInfo(CultureInfo culture)
{
m_name = culture._name;
InitSort(culture);
}
/*=================================GetCompareInfo==========================
**Action: Get the CompareInfo constructed from the data table in the specified assembly for the specified culture.
** Warning: The assembly versioning mechanism is dead!
**Returns: The CompareInfo for the specified culture.
**Arguments:
** culture the ID of the culture
** assembly the assembly which contains the sorting table.
**Exceptions:
** ArgumentNullException when the assembly is null
** ArgumentException if culture is invalid.
============================================================================*/
// Assembly constructor should be deprecated, we don't act on the assembly information any more
public static CompareInfo GetCompareInfo(int culture, Assembly assembly)
{
// Parameter checking.
if (assembly == null)
{
throw new ArgumentNullException(nameof(assembly));
}
if (assembly != typeof(Object).Module.Assembly)
{
throw new ArgumentException(SR.Argument_OnlyMscorlib);
}
return GetCompareInfo(culture);
}
/*=================================GetCompareInfo==========================
**Action: Get the CompareInfo constructed from the data table in the specified assembly for the specified culture.
** The purpose of this method is to provide version for CompareInfo tables.
**Returns: The CompareInfo for the specified culture.
**Arguments:
** name the name of the culture
** assembly the assembly which contains the sorting table.
**Exceptions:
** ArgumentNullException when the assembly is null
** ArgumentException if name is invalid.
============================================================================*/
// Assembly constructor should be deprecated, we don't act on the assembly information any more
public static CompareInfo GetCompareInfo(string name, Assembly assembly)
{
if (name == null || assembly == null)
{
throw new ArgumentNullException(name == null ? nameof(name) : nameof(assembly));
}
if (assembly != typeof(Object).Module.Assembly)
{
throw new ArgumentException(SR.Argument_OnlyMscorlib);
}
return GetCompareInfo(name);
}
/*=================================GetCompareInfo==========================
**Action: Get the CompareInfo for the specified culture.
** This method is provided for ease of integration with NLS-based software.
**Returns: The CompareInfo for the specified culture.
**Arguments:
** culture the ID of the culture.
**Exceptions:
** ArgumentException if culture is invalid.
============================================================================*/
// People really shouldn't be calling LCID versions, no custom support
public static CompareInfo GetCompareInfo(int culture)
{
if (CultureData.IsCustomCultureId(culture))
{
// Customized culture cannot be created by the LCID.
throw new ArgumentException(SR.Argument_CustomCultureCannotBePassedByNumber, nameof(culture));
}
return CultureInfo.GetCultureInfo(culture).CompareInfo;
}
/*=================================GetCompareInfo==========================
**Action: Get the CompareInfo for the specified culture.
**Returns: The CompareInfo for the specified culture.
**Arguments:
** name the name of the culture.
**Exceptions:
** ArgumentException if name is invalid.
============================================================================*/
public static CompareInfo GetCompareInfo(string name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
return CultureInfo.GetCultureInfo(name).CompareInfo;
}
public static unsafe bool IsSortable(char ch)
{
if (GlobalizationMode.Invariant)
{
return true;
}
char *pChar = &ch;
return IsSortable(pChar, 1);
}
public static unsafe bool IsSortable(string text)
{
if (text == null)
{
// A null param is invalid here.
throw new ArgumentNullException(nameof(text));
}
if (text.Length == 0)
{
// A zero length string is not invalid, but it is also not sortable.
return (false);
}
if (GlobalizationMode.Invariant)
{
return true;
}
fixed (char *pChar = text)
{
return IsSortable(pChar, text.Length);
}
}
[OnDeserializing]
private void OnDeserializing(StreamingContext ctx)
{
m_name = null;
}
void IDeserializationCallback.OnDeserialization(object sender)
{
OnDeserialized();
}
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
{
OnDeserialized();
}
private void OnDeserialized()
{
// If we didn't have a name, use the LCID
if (m_name == null)
{
// From whidbey, didn't have a name
CultureInfo ci = CultureInfo.GetCultureInfo(this.culture);
m_name = ci._name;
}
else
{
InitSort(CultureInfo.GetCultureInfo(m_name));
}
}
[OnSerializing]
private void OnSerializing(StreamingContext ctx)
{
// This is merely for serialization compatibility with Whidbey/Orcas, it can go away when we don't want that compat any more.
culture = CultureInfo.GetCultureInfo(this.Name).LCID; // This is the lcid of the constructing culture (still have to dereference to get target sort)
Debug.Assert(m_name != null, "CompareInfo.OnSerializing - expected m_name to be set already");
}
///////////////////////////----- Name -----/////////////////////////////////
//
// Returns the name of the culture (well actually, of the sort).
// Very important for providing a non-LCID way of identifying
// what the sort is.
//
// Note that this name isn't dereferenced in case the CompareInfo is a different locale
// which is consistent with the behaviors of earlier versions. (so if you ask for a sort
// and the locale's changed behavior, then you'll get changed behavior, which is like
// what happens for a version update)
//
////////////////////////////////////////////////////////////////////////
public virtual string Name
{
get
{
Debug.Assert(m_name != null, "CompareInfo.Name Expected _name to be set");
if (m_name == "zh-CHT" || m_name == "zh-CHS")
{
return m_name;
}
return _sortName;
}
}
////////////////////////////////////////////////////////////////////////
//
// Compare
//
// Compares the two strings with the given options. Returns 0 if the
// two strings are equal, a number less than 0 if string1 is less
// than string2, and a number greater than 0 if string1 is greater
// than string2.
//
////////////////////////////////////////////////////////////////////////
public virtual int Compare(string string1, string string2)
{
return (Compare(string1, string2, CompareOptions.None));
}
public virtual int Compare(string string1, string string2, CompareOptions options)
{
if (options == CompareOptions.OrdinalIgnoreCase)
{
return String.Compare(string1, string2, StringComparison.OrdinalIgnoreCase);
}
// Verify the options before we do any real comparison.
if ((options & CompareOptions.Ordinal) != 0)
{
if (options != CompareOptions.Ordinal)
{
throw new ArgumentException(SR.Argument_CompareOptionOrdinal, nameof(options));
}
return String.CompareOrdinal(string1, string2);
}
if ((options & ValidCompareMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
//Our paradigm is that null sorts less than any other string and
//that two nulls sort as equal.
if (string1 == null)
{
if (string2 == null)
{
return (0); // Equal
}
return (-1); // null < non-null
}
if (string2 == null)
{
return (1); // non-null > null
}
if (_invariantMode)
{
if ((options & CompareOptions.IgnoreCase) != 0)
return CompareOrdinalIgnoreCase(string1, 0, string1.Length, string2, 0, string2.Length);
return String.CompareOrdinal(string1, string2);
}
return CompareString(string1.AsSpan(), string2.AsSpan(), options);
}
// TODO https://github.com/dotnet/coreclr/issues/13827:
// This method shouldn't be necessary, as we should be able to just use the overload
// that takes two spans. But due to this issue, that's adding significant overhead.
internal int Compare(ReadOnlySpan<char> string1, string string2, CompareOptions options)
{
if (options == CompareOptions.OrdinalIgnoreCase)
{
return CompareOrdinalIgnoreCase(string1, string2.AsSpan());
}
// Verify the options before we do any real comparison.
if ((options & CompareOptions.Ordinal) != 0)
{
if (options != CompareOptions.Ordinal)
{
throw new ArgumentException(SR.Argument_CompareOptionOrdinal, nameof(options));
}
return string.CompareOrdinal(string1, string2.AsSpan());
}
if ((options & ValidCompareMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
// null sorts less than any other string.
if (string2 == null)
{
return 1;
}
if (_invariantMode)
{
return (options & CompareOptions.IgnoreCase) != 0 ?
CompareOrdinalIgnoreCase(string1, string2.AsSpan()) :
string.CompareOrdinal(string1, string2.AsSpan());
}
return CompareString(string1, string2, options);
}
// TODO https://github.com/dotnet/corefx/issues/21395: Expose this publicly?
internal virtual int Compare(ReadOnlySpan<char> string1, ReadOnlySpan<char> string2, CompareOptions options)
{
if (options == CompareOptions.OrdinalIgnoreCase)
{
return CompareOrdinalIgnoreCase(string1, string2);
}
// Verify the options before we do any real comparison.
if ((options & CompareOptions.Ordinal) != 0)
{
if (options != CompareOptions.Ordinal)
{
throw new ArgumentException(SR.Argument_CompareOptionOrdinal, nameof(options));
}
return string.CompareOrdinal(string1, string2);
}
if ((options & ValidCompareMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
if (_invariantMode)
{
return (options & CompareOptions.IgnoreCase) != 0 ?
CompareOrdinalIgnoreCase(string1, string2) :
string.CompareOrdinal(string1, string2);
}
return CompareString(string1, string2, options);
}
////////////////////////////////////////////////////////////////////////
//
// Compare
//
// Compares the specified regions of the two strings with the given
// options.
// Returns 0 if the two strings are equal, a number less than 0 if
// string1 is less than string2, and a number greater than 0 if
// string1 is greater than string2.
//
////////////////////////////////////////////////////////////////////////
public virtual int Compare(string string1, int offset1, int length1, string string2, int offset2, int length2)
{
return Compare(string1, offset1, length1, string2, offset2, length2, 0);
}
public virtual int Compare(string string1, int offset1, string string2, int offset2, CompareOptions options)
{
return Compare(string1, offset1, string1 == null ? 0 : string1.Length - offset1,
string2, offset2, string2 == null ? 0 : string2.Length - offset2, options);
}
public virtual int Compare(string string1, int offset1, string string2, int offset2)
{
return Compare(string1, offset1, string2, offset2, 0);
}
public virtual int Compare(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options)
{
if (options == CompareOptions.OrdinalIgnoreCase)
{
int result = String.Compare(string1, offset1, string2, offset2, length1 < length2 ? length1 : length2, StringComparison.OrdinalIgnoreCase);
if ((length1 != length2) && result == 0)
return (length1 > length2 ? 1 : -1);
return (result);
}
// Verify inputs
if (length1 < 0 || length2 < 0)
{
throw new ArgumentOutOfRangeException((length1 < 0) ? nameof(length1) : nameof(length2), SR.ArgumentOutOfRange_NeedPosNum);
}
if (offset1 < 0 || offset2 < 0)
{
throw new ArgumentOutOfRangeException((offset1 < 0) ? nameof(offset1) : nameof(offset2), SR.ArgumentOutOfRange_NeedPosNum);
}
if (offset1 > (string1 == null ? 0 : string1.Length) - length1)
{
throw new ArgumentOutOfRangeException(nameof(string1), SR.ArgumentOutOfRange_OffsetLength);
}
if (offset2 > (string2 == null ? 0 : string2.Length) - length2)
{
throw new ArgumentOutOfRangeException(nameof(string2), SR.ArgumentOutOfRange_OffsetLength);
}
if ((options & CompareOptions.Ordinal) != 0)
{
if (options != CompareOptions.Ordinal)
{
throw new ArgumentException(SR.Argument_CompareOptionOrdinal,
nameof(options));
}
}
else if ((options & ValidCompareMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
//
// Check for the null case.
//
if (string1 == null)
{
if (string2 == null)
{
return (0);
}
return (-1);
}
if (string2 == null)
{
return (1);
}
if (options == CompareOptions.Ordinal)
{
return CompareOrdinal(string1, offset1, length1,
string2, offset2, length2);
}
if (_invariantMode)
{
if ((options & CompareOptions.IgnoreCase) != 0)
return CompareOrdinalIgnoreCase(string1, offset1, length1, string2, offset2, length2);
return CompareOrdinal(string1, offset1, length1, string2, offset2, length2);
}
return CompareString(
string1.AsSpan().Slice(offset1, length1),
string2.AsSpan().Slice(offset2, length2),
options);
}
private static int CompareOrdinal(string string1, int offset1, int length1, string string2, int offset2, int length2)
{
int result = String.CompareOrdinal(string1, offset1, string2, offset2,
(length1 < length2 ? length1 : length2));
if ((length1 != length2) && result == 0)
{
return (length1 > length2 ? 1 : -1);
}
return (result);
}
//
// CompareOrdinalIgnoreCase compare two string ordinally with ignoring the case.
// it assumes the strings are Ascii string till we hit non Ascii character in strA or strB and then we continue the comparison by
// calling the OS.
//
internal static int CompareOrdinalIgnoreCase(string strA, int indexA, int lengthA, string strB, int indexB, int lengthB)
{
Debug.Assert(indexA + lengthA <= strA.Length);
Debug.Assert(indexB + lengthB <= strB.Length);
return CompareOrdinalIgnoreCase(strA.AsSpan().Slice(indexA, lengthA), strB.AsSpan().Slice(indexB, lengthB));
}
internal static unsafe int CompareOrdinalIgnoreCase(ReadOnlySpan<char> strA, ReadOnlySpan<char> strB)
{
int length = Math.Min(strA.Length, strB.Length);
int range = length;
fixed (char* ap = &MemoryMarshal.GetReference(strA))
fixed (char* bp = &MemoryMarshal.GetReference(strB))
{
char* a = ap;
char* b = bp;
// in InvariantMode we support all range and not only the ascii characters.
char maxChar = (char) (GlobalizationMode.Invariant ? 0xFFFF : 0x7F);
while (length != 0 && (*a <= maxChar) && (*b <= maxChar))
{
int charA = *a;
int charB = *b;
if (charA == charB)
{
a++; b++;
length--;
continue;
}
// uppercase both chars - notice that we need just one compare per char
if ((uint)(charA - 'a') <= 'z' - 'a') charA -= 0x20;
if ((uint)(charB - 'a') <= 'z' - 'a') charB -= 0x20;
// Return the (case-insensitive) difference between them.
if (charA != charB)
return charA - charB;
// Next char
a++; b++;
length--;
}
if (length == 0)
return strA.Length - strB.Length;
Debug.Assert(!GlobalizationMode.Invariant);
range -= length;
return CompareStringOrdinalIgnoreCase(a, strA.Length - range, b, strB.Length - range);
}
}
////////////////////////////////////////////////////////////////////////
//
// IsPrefix
//
// Determines whether prefix is a prefix of string. If prefix equals
// String.Empty, true is returned.
//
////////////////////////////////////////////////////////////////////////
public virtual bool IsPrefix(string source, string prefix, CompareOptions options)
{
if (source == null || prefix == null)
{
throw new ArgumentNullException((source == null ? nameof(source) : nameof(prefix)),
SR.ArgumentNull_String);
}
if (prefix.Length == 0)
{
return (true);
}
if (source.Length == 0)
{
return false;
}
if (options == CompareOptions.OrdinalIgnoreCase)
{
return source.StartsWith(prefix, StringComparison.OrdinalIgnoreCase);
}
if (options == CompareOptions.Ordinal)
{
return source.StartsWith(prefix, StringComparison.Ordinal);
}
if ((options & ValidIndexMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
if (_invariantMode)
{
return source.StartsWith(prefix, (options & CompareOptions.IgnoreCase) != 0 ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
return StartsWith(source, prefix, options);
}
internal bool IsPrefix(ReadOnlySpan<char> source, ReadOnlySpan<char> prefix, CompareOptions options)
{
Debug.Assert(prefix.Length != 0);
Debug.Assert(source.Length != 0);
Debug.Assert((options & ValidIndexMaskOffFlags) == 0);
Debug.Assert(!_invariantMode);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return StartsWith(source, prefix, options);
}
public virtual bool IsPrefix(string source, string prefix)
{
return (IsPrefix(source, prefix, 0));
}
////////////////////////////////////////////////////////////////////////
//
// IsSuffix
//
// Determines whether suffix is a suffix of string. If suffix equals
// String.Empty, true is returned.
//
////////////////////////////////////////////////////////////////////////
public virtual bool IsSuffix(string source, string suffix, CompareOptions options)
{
if (source == null || suffix == null)
{
throw new ArgumentNullException((source == null ? nameof(source) : nameof(suffix)),
SR.ArgumentNull_String);
}
if (suffix.Length == 0)
{
return (true);
}
if (source.Length == 0)
{
return false;
}
if (options == CompareOptions.OrdinalIgnoreCase)
{
return source.EndsWith(suffix, StringComparison.OrdinalIgnoreCase);
}
if (options == CompareOptions.Ordinal)
{
return source.EndsWith(suffix, StringComparison.Ordinal);
}
if ((options & ValidIndexMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
if (_invariantMode)
{
return source.EndsWith(suffix, (options & CompareOptions.IgnoreCase) != 0 ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
return EndsWith(source, suffix, options);
}
internal bool IsSuffix(ReadOnlySpan<char> source, ReadOnlySpan<char> suffix, CompareOptions options)
{
Debug.Assert(suffix.Length != 0);
Debug.Assert(source.Length != 0);
Debug.Assert((options & ValidIndexMaskOffFlags) == 0);
Debug.Assert(!_invariantMode);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return EndsWith(source, suffix, options);
}
public virtual bool IsSuffix(string source, string suffix)
{
return (IsSuffix(source, suffix, 0));
}
////////////////////////////////////////////////////////////////////////
//
// IndexOf
//
// Returns the first index where value is found in string. The
// search starts from startIndex and ends at endIndex. Returns -1 if
// the specified value is not found. If value equals String.Empty,
// startIndex is returned. Throws IndexOutOfRange if startIndex or
// endIndex is less than zero or greater than the length of string.
// Throws ArgumentException if value is null.
//
////////////////////////////////////////////////////////////////////////
public virtual int IndexOf(string source, char value)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, 0, source.Length, CompareOptions.None);
}
public virtual int IndexOf(string source, string value)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, 0, source.Length, CompareOptions.None);
}
public virtual int IndexOf(string source, char value, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, 0, source.Length, options);
}
public virtual int IndexOf(string source, string value, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, 0, source.Length, options);
}
public virtual int IndexOf(string source, char value, int startIndex)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None);
}
public virtual int IndexOf(string source, string value, int startIndex)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None);
}
public virtual int IndexOf(string source, char value, int startIndex, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, startIndex, source.Length - startIndex, options);
}
public virtual int IndexOf(string source, string value, int startIndex, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, startIndex, source.Length - startIndex, options);
}
public virtual int IndexOf(string source, char value, int startIndex, int count)
{
return IndexOf(source, value, startIndex, count, CompareOptions.None);
}
public virtual int IndexOf(string source, string value, int startIndex, int count)
{
return IndexOf(source, value, startIndex, count, CompareOptions.None);
}
public unsafe virtual int IndexOf(string source, char value, int startIndex, int count, CompareOptions options)
{
// Validate inputs
if (source == null)
throw new ArgumentNullException(nameof(source));
if (startIndex < 0 || startIndex > source.Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
if (count < 0 || startIndex > source.Length - count)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
if (source.Length == 0)
{
return -1;
}
if (options == CompareOptions.OrdinalIgnoreCase)
{
return source.IndexOf(value.ToString(), startIndex, count, StringComparison.OrdinalIgnoreCase);
}
// Validate CompareOptions
// Ordinal can't be selected with other flags
if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal))
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
if (_invariantMode)
return IndexOfOrdinal(source, new string(value, 1), startIndex, count, ignoreCase: (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
return IndexOfCore(source, new string(value, 1), startIndex, count, options, null);
}
public unsafe virtual int IndexOf(string source, string value, int startIndex, int count, CompareOptions options)
{
// Validate inputs
if (source == null)
throw new ArgumentNullException(nameof(source));
if (value == null)
throw new ArgumentNullException(nameof(value));
if (startIndex > source.Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
}
// In Everett we used to return -1 for empty string even if startIndex is negative number so we keeping same behavior here.
// We return 0 if both source and value are empty strings for Everett compatibility too.
if (source.Length == 0)
{
if (value.Length == 0)
{
return 0;
}
return -1;
}
if (startIndex < 0)
{
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
}
if (count < 0 || startIndex > source.Length - count)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
if (options == CompareOptions.OrdinalIgnoreCase)
{
return IndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
}
// Validate CompareOptions
// Ordinal can't be selected with other flags
if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal))
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
if (_invariantMode)
return IndexOfOrdinal(source, value, startIndex, count, ignoreCase: (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
return IndexOfCore(source, value, startIndex, count, options, null);
}
internal virtual int IndexOfOrdinal(ReadOnlySpan<char> source, ReadOnlySpan<char> value, bool ignoreCase)
{
Debug.Assert(!_invariantMode);
return IndexOfOrdinalCore(source, value, ignoreCase);
}
internal unsafe virtual int IndexOf(ReadOnlySpan<char> source, ReadOnlySpan<char> value, CompareOptions options)
{
Debug.Assert(!_invariantMode);
return IndexOfCore(source, value, options, null);
}
// The following IndexOf overload is mainly used by String.Replace. This overload assumes the parameters are already validated
// and the caller is passing a valid matchLengthPtr pointer.
internal unsafe int IndexOf(string source, string value, int startIndex, int count, CompareOptions options, int* matchLengthPtr)
{
Debug.Assert(source != null);
Debug.Assert(value != null);
Debug.Assert(startIndex >= 0);
Debug.Assert(matchLengthPtr != null);
*matchLengthPtr = 0;
if (source.Length == 0)
{
if (value.Length == 0)
{
return 0;
}
return -1;
}
if (startIndex >= source.Length)
{
return -1;
}
if (options == CompareOptions.OrdinalIgnoreCase)
{
int res = IndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
if (res >= 0)
{
*matchLengthPtr = value.Length;
}
return res;
}
if (_invariantMode)
{
int res = IndexOfOrdinal(source, value, startIndex, count, ignoreCase: (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
if (res >= 0)
{
*matchLengthPtr = value.Length;
}
return res;
}
return IndexOfCore(source, value, startIndex, count, options, matchLengthPtr);
}
internal int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
if (_invariantMode)
{
return InvariantIndexOf(source, value, startIndex, count, ignoreCase);
}
return IndexOfOrdinalCore(source, value, startIndex, count, ignoreCase);
}
////////////////////////////////////////////////////////////////////////
//
// LastIndexOf
//
// Returns the last index where value is found in string. The
// search starts from startIndex and ends at endIndex. Returns -1 if
// the specified value is not found. If value equals String.Empty,
// endIndex is returned. Throws IndexOutOfRange if startIndex or
// endIndex is less than zero or greater than the length of string.
// Throws ArgumentException if value is null.
//
////////////////////////////////////////////////////////////////////////
public virtual int LastIndexOf(String source, char value)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
// Can't start at negative index, so make sure we check for the length == 0 case.
return LastIndexOf(source, value, source.Length - 1, source.Length, CompareOptions.None);
}
public virtual int LastIndexOf(string source, string value)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
// Can't start at negative index, so make sure we check for the length == 0 case.
return LastIndexOf(source, value, source.Length - 1,
source.Length, CompareOptions.None);
}
public virtual int LastIndexOf(string source, char value, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
// Can't start at negative index, so make sure we check for the length == 0 case.
return LastIndexOf(source, value, source.Length - 1,
source.Length, options);
}
public virtual int LastIndexOf(string source, string value, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
// Can't start at negative index, so make sure we check for the length == 0 case.
return LastIndexOf(source, value, source.Length - 1, source.Length, options);
}
public virtual int LastIndexOf(string source, char value, int startIndex)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, CompareOptions.None);
}
public virtual int LastIndexOf(string source, string value, int startIndex)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, CompareOptions.None);
}
public virtual int LastIndexOf(string source, char value, int startIndex, CompareOptions options)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, options);
}
public virtual int LastIndexOf(string source, string value, int startIndex, CompareOptions options)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, options);
}
public virtual int LastIndexOf(string source, char value, int startIndex, int count)
{
return LastIndexOf(source, value, startIndex, count, CompareOptions.None);
}
public virtual int LastIndexOf(string source, string value, int startIndex, int count)
{
return LastIndexOf(source, value, startIndex, count, CompareOptions.None);
}
public virtual int LastIndexOf(string source, char value, int startIndex, int count, CompareOptions options)
{
// Verify Arguments
if (source == null)
throw new ArgumentNullException(nameof(source));
// Validate CompareOptions
// Ordinal can't be selected with other flags
if ((options & ValidIndexMaskOffFlags) != 0 &&
(options != CompareOptions.Ordinal) &&
(options != CompareOptions.OrdinalIgnoreCase))
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
// Special case for 0 length input strings
if (source.Length == 0 && (startIndex == -1 || startIndex == 0))
return -1;
// Make sure we're not out of range
if (startIndex < 0 || startIndex > source.Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
// Make sure that we allow startIndex == source.Length
if (startIndex == source.Length)
{
startIndex--;
if (count > 0)
count--;
}
// 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
if (options == CompareOptions.OrdinalIgnoreCase)
{
return source.LastIndexOf(value.ToString(), startIndex, count, StringComparison.OrdinalIgnoreCase);
}
if (_invariantMode)
return InvariantLastIndexOf(source, new string(value, 1), startIndex, count, (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
return LastIndexOfCore(source, value.ToString(), startIndex, count, options);
}
public virtual int LastIndexOf(string source, string value, int startIndex, int count, CompareOptions options)
{
// Verify Arguments
if (source == null)
throw new ArgumentNullException(nameof(source));
if (value == null)
throw new ArgumentNullException(nameof(value));
// Validate CompareOptions
// Ordinal can't be selected with other flags
if ((options & ValidIndexMaskOffFlags) != 0 &&
(options != CompareOptions.Ordinal) &&
(options != CompareOptions.OrdinalIgnoreCase))
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
// Special case for 0 length input strings
if (source.Length == 0 && (startIndex == -1 || startIndex == 0))
return (value.Length == 0) ? 0 : -1;
// Make sure we're not out of range
if (startIndex < 0 || startIndex > source.Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
// Make sure that we allow startIndex == source.Length
if (startIndex == source.Length)
{
startIndex--;
if (count > 0)
count--;
// If we are looking for nothing, just return 0
if (value.Length == 0 && count >= 0 && startIndex - count + 1 >= 0)
return startIndex;
}
// 2nd half of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
if (options == CompareOptions.OrdinalIgnoreCase)
{
return LastIndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
}
if (_invariantMode)
return InvariantLastIndexOf(source, value, startIndex, count, (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
return LastIndexOfCore(source, value, startIndex, count, options);
}
internal int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
if (_invariantMode)
{
return InvariantLastIndexOf(source, value, startIndex, count, ignoreCase);
}
return LastIndexOfOrdinalCore(source, value, startIndex, count, ignoreCase);
}
////////////////////////////////////////////////////////////////////////
//
// GetSortKey
//
// Gets the SortKey for the given string with the given options.
//
////////////////////////////////////////////////////////////////////////
public virtual SortKey GetSortKey(string source, CompareOptions options)
{
if (_invariantMode)
return InvariantCreateSortKey(source, options);
return CreateSortKey(source, options);
}
public virtual SortKey GetSortKey(string source)
{
if (_invariantMode)
return InvariantCreateSortKey(source, CompareOptions.None);
return CreateSortKey(source, CompareOptions.None);
}
////////////////////////////////////////////////////////////////////////
//
// Equals
//
// Implements Object.Equals(). Returns a boolean indicating whether
// or not object refers to the same CompareInfo as the current
// instance.
//
////////////////////////////////////////////////////////////////////////
public override bool Equals(Object value)
{
CompareInfo that = value as CompareInfo;
if (that != null)
{
return this.Name == that.Name;
}
return (false);
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCode
//
// Implements Object.GetHashCode(). Returns the hash code for the
// CompareInfo. The hash code is guaranteed to be the same for
// CompareInfo A and B where A.Equals(B) is true.
//
////////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
return (this.Name.GetHashCode());
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCodeOfString
//
// This internal method allows a method that allows the equivalent of creating a Sortkey for a
// string from CompareInfo, and generate a hashcode value from it. It is not very convenient
// to use this method as is and it creates an unnecessary Sortkey object that will be GC'ed.
//
// The hash code is guaranteed to be the same for string A and B where A.Equals(B) is true and both
// the CompareInfo and the CompareOptions are the same. If two different CompareInfo objects
// treat the string the same way, this implementation will treat them differently (the same way that
// Sortkey does at the moment).
//
// This method will never be made public itself, but public consumers of it could be created, e.g.:
//
// string.GetHashCode(CultureInfo)
// string.GetHashCode(CompareInfo)
// string.GetHashCode(CultureInfo, CompareOptions)
// string.GetHashCode(CompareInfo, CompareOptions)
// etc.
//
// (the methods above that take a CultureInfo would use CultureInfo.CompareInfo)
//
////////////////////////////////////////////////////////////////////////
internal int GetHashCodeOfString(string source, CompareOptions options)
{
//
// Parameter validation
//
if (null == source)
{
throw new ArgumentNullException(nameof(source));
}
if ((options & ValidHashCodeOfStringMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
return GetHashCodeOfStringCore(source, options);
}
public virtual int GetHashCode(string source, CompareOptions options)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (options == CompareOptions.Ordinal)
{
return source.GetHashCode();
}
if (options == CompareOptions.OrdinalIgnoreCase)
{
return TextInfo.GetHashCodeOrdinalIgnoreCase(source);
}
//
// GetHashCodeOfString does more parameters validation. basically will throw when
// having Ordinal, OrdinalIgnoreCase and StringSort
//
return GetHashCodeOfString(source, options);
}
////////////////////////////////////////////////////////////////////////
//
// ToString
//
// Implements Object.ToString(). Returns a string describing the
// CompareInfo.
//
////////////////////////////////////////////////////////////////////////
public override string ToString()
{
return ("CompareInfo - " + this.Name);
}
public SortVersion Version
{
get
{
if (m_SortVersion == null)
{
if (_invariantMode)
{
m_SortVersion = new SortVersion(0, CultureInfo.LOCALE_INVARIANT, new Guid(0, 0, 0, 0, 0, 0, 0,
(byte) (CultureInfo.LOCALE_INVARIANT >> 24),
(byte) ((CultureInfo.LOCALE_INVARIANT & 0x00FF0000) >> 16),
(byte) ((CultureInfo.LOCALE_INVARIANT & 0x0000FF00) >> 8),
(byte) (CultureInfo.LOCALE_INVARIANT & 0xFF)));
}
else
{
m_SortVersion = GetSortVersion();
}
}
return m_SortVersion;
}
}
public int LCID
{
get
{
return CultureInfo.GetCultureInfo(Name).LCID;
}
}
}
}
| |
using System;
using UnityEngine;
namespace InControl
{
public class InputControl
{
public static readonly InputControl Null = new InputControl( "NullInputControl" );
public string Handle { get; protected set; }
public InputControlType Target { get; protected set; }
public ulong UpdateTick { get; protected set; }
public float Sensitivity = 1.0f;
public float LowerDeadZone = 0.0f;
public float UpperDeadZone = 1.0f;
public bool IsButton { get; protected set; }
InputControlState thisState;
InputControlState lastState;
InputControlState tempState;
private InputControl( string handle )
{
Handle = handle;
}
public InputControl( string handle, InputControlType target )
{
Handle = handle;
Target = target;
IsButton = (target >= InputControlType.Action1 && target <= InputControlType.Action4) ||
(target >= InputControlType.Button0 && target <= InputControlType.Button19);
}
public void UpdateWithState( bool state, ulong updateTick )
{
if (IsNull)
{
throw new InvalidOperationException( "A null control cannot be updated." );
}
if (UpdateTick > updateTick)
{
throw new InvalidOperationException( "A control cannot be updated with an earlier tick." );
}
tempState.Set( state || tempState.State );
}
public void UpdateWithValue( float value, ulong updateTick )
{
if (IsNull)
{
throw new InvalidOperationException( "A null control cannot be updated." );
}
if (UpdateTick > updateTick)
{
throw new InvalidOperationException( "A control cannot be updated with an earlier tick." );
}
if (Mathf.Abs( value ) > Mathf.Abs( tempState.Value ))
{
tempState.Set( value );
}
}
internal void PreUpdate( ulong updateTick )
{
RawValue = null;
PreValue = null;
lastState = thisState;
tempState.Reset();
}
internal void PostUpdate( ulong updateTick )
{
thisState = tempState;
if (thisState != lastState)
{
UpdateTick = updateTick;
}
}
public bool State
{
get { return thisState.State; }
}
public bool LastState
{
get { return lastState.State; }
}
public float Value
{
get { return thisState.Value; }
}
public float LastValue
{
get { return lastState.Value; }
}
public bool HasChanged
{
get { return thisState != lastState; }
}
public bool IsPressed
{
get { return thisState.State; }
}
public bool WasPressed
{
get { return thisState && !lastState; }
}
public bool WasReleased
{
get { return !thisState && lastState; }
}
public bool IsNull
{
get { return this == Null; }
}
public bool IsNotNull
{
get { return this != Null; }
}
public override string ToString()
{
return string.Format( "[InputControl: Handle={0}, Value={1}]", Handle, Value );
}
public static implicit operator bool( InputControl control )
{
return control.State;
}
public static implicit operator float( InputControl control )
{
return control.Value;
}
public InputControlType? Obverse
{
get
{
switch (Target)
{
case InputControlType.LeftStickX:
return InputControlType.LeftStickY;
case InputControlType.LeftStickY:
return InputControlType.LeftStickX;
case InputControlType.RightStickX:
return InputControlType.RightStickY;
case InputControlType.RightStickY:
return InputControlType.RightStickX;
default:
return null;
}
}
}
// This is for internal use only and is not always set.
internal float? RawValue;
internal float? PreValue;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclassregprop.genclassregprop
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclassregprop.genclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass001.genclass001;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Reflection;
public class MyClass
{
public int Field = 0;
}
public struct MyStruct
{
public int Number;
}
public enum MyEnum
{
First = 1,
Second = 2,
Third = 3
}
public class MemberClass<T>
{
/// <summary>
/// We use this to get the values we cannot get directly
/// </summary>
/// <param name = "target"></param>
/// <param name = "name"></param>
/// <returns></returns>
public object GetPrivateValue(object target, string name)
{
var tip = target.GetType();
var prop = tip.GetTypeInfo().GetDeclaredField(name);
return prop.GetValue(target);
}
/// <summary>
/// We use this to set the value we cannot set directly
/// </summary>
/// <param name = "target"></param>
/// <param name = "name"></param>
/// <param name = "value"></param>
public void SetPrivateValue(object target, string name, object value)
{
var tip = target.GetType();
var prop = tip.GetTypeInfo().GetDeclaredField(name);
prop.SetValue(target, value);
}
public decimal[] myDecimalArr = new decimal[2];
public dynamic myDynamic = new object();
public T myT;
public T Property_T
{
set
{
myT = value;
}
get
{
return myT;
}
}
public decimal[] Property_decimalArr
{
protected internal set
{
myDecimalArr = value;
}
get
{
return myDecimalArr;
}
}
public dynamic Property_dynamic
{
get
{
return myDynamic;
}
set
{
myDynamic = value;
}
}
public static float myFloatStatic;
public static T myTStatic;
public static T Property_TStatic
{
set
{
myTStatic = value;
}
get
{
return myTStatic;
}
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass001.genclass001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclassregprop.genclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass001.genclass001;
// <Title> Tests generic class regular property used in regular method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t1 = new Test();
return t1.TestGetMethod(new MemberClass<bool>()) + t1.TestSetMethod(new MemberClass<bool>()) == 0 ? 0 : 1;
}
public int TestGetMethod(MemberClass<bool> mc)
{
mc.Property_T = true;
dynamic dy = mc;
if (!(bool)dy.Property_T)
return 1;
else
return 0;
}
public int TestSetMethod(MemberClass<bool> mc)
{
dynamic dy = mc;
dy.Property_T = true;
mc = dy; //mc might be a boxed struct
if (!mc.Property_T)
return 1;
else
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass002.genclass002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclassregprop.genclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass002.genclass002;
// <Title> Tests generic class regular property used in regular method body with conditional attribute.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
private static int s_count = 0;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t1 = new Test();
t1.TestGetMethod(new MemberClass<bool>());
t1.TestSetMethod(new MemberClass<bool>());
return s_count;
}
[System.Diagnostics.Conditional("c1")]
public void TestGetMethod(MemberClass<bool> mc)
{
dynamic dy = mc;
mc.Property_decimalArr = new decimal[1];
if ((int)dy.Property_decimalArr.Length != 1)
s_count++;
}
[System.Diagnostics.Conditional("c2")]
public void TestSetMethod(MemberClass<bool> mc)
{
dynamic dy = mc;
dy.Property_decimalArr = new decimal[]
{
0M, 1M
}
;
if (!((int)mc.Property_decimalArr.Length != 2))
s_count++;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass003.genclass003
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclassregprop.genclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass003.genclass003;
// <Title> Tests generic class regular property used in member initializer of anonymous type.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass<string> mc = new MemberClass<string>();
mc.myT = "Test";
mc.myDecimalArr = new decimal[]
{
0M, 1M
}
;
dynamic dy = mc;
var tc = new
{
A1 = (string)dy.Property_T,
A2 = (decimal[])dy.Property_decimalArr,
A3 = (object)dy.Property_dynamic
}
;
if (tc != null && mc.myT == tc.A1 && tc.A2[0] == 0M && tc.A2[1] == 1M && tc.A3 == mc.myDynamic)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass005.genclass005
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclassregprop.genclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass005.genclass005;
// <Title> Tests generic class regular property used in query expression.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
var list = new List<string>()
{
null, "b", null, "a"
}
;
MemberClass<string> mc = new MemberClass<string>();
mc.myT = "a";
dynamic dy = mc;
var result = list.Where(p => p == (string)dy.Property_T).ToList();
if (result.Count == 1 && result[0] == "a")
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass006.genclass006
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclassregprop.genclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass006.genclass006;
// <Title> Tests generic class regular property used in member initializer of object initializer.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
private int _field1;
private string _field2 = string.Empty;
private MyEnum _field3;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass<string> mc1 = new MemberClass<string>();
MemberClass<Test> mc2 = new MemberClass<Test>();
MemberClass<MyStruct> mc3 = new MemberClass<MyStruct>();
mc1.Property_dynamic = 10;
mc3.Property_dynamic = MyEnum.Second;
dynamic dy1 = mc1;
dynamic dy2 = mc2;
dynamic dy3 = mc3;
var test = new Test()
{
_field1 = dy1.Property_dynamic,
_field2 = dy2.Property_dynamic == null ? string.Empty : dy2.Property_dynamic.ToString(),
_field3 = dy3.Property_dynamic
}
;
if (test._field1 == 10 && test._field2 != null && test._field3 == MyEnum.Second)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass007.genclass007
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclassregprop.genclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass007.genclass007;
// <Title> Tests generic class regular property used in explicit operator.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public class InnerTest1
{
public int field;
public static explicit operator InnerTest2(InnerTest1 t1)
{
var dy = new MemberClass<InnerTest2>();
dy.Property_T = new InnerTest2()
{
field = t1.field + 1
}
;
return dy.Property_T;
}
}
public class InnerTest2
{
public int field;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
InnerTest1 t = new InnerTest1()
{
field = 20
}
;
InnerTest2 result = (InnerTest2)t; //explicit
return (result.field == 21) ? 0 : 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass008.genclass008
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclassregprop.genclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass008.genclass008;
// <Title> Tests generic class regular property used in implicit operator.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public class InnerTest1
{
public int field;
public static implicit operator InnerTest2(InnerTest1 t1)
{
var dy = new MemberClass<InnerTest2>();
dy.Property_T = new InnerTest2()
{
field = t1.field + 1
}
;
return dy.Property_T;
}
}
public class InnerTest2
{
public int field;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
InnerTest1 t = new InnerTest1()
{
field = 20
}
;
InnerTest2 result1 = (InnerTest2)t; //explicit
InnerTest2 result2 = t; //implicit
return (result1.field == 21 && result2.field == 21) ? 0 : 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass011.genclass011
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclassregprop.genclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass011.genclass011;
// <Title> Tests generic class regular property used in volatile field initializer.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
private static MemberClass<MyClass> s_mc;
private static dynamic s_dy;
static Test()
{
s_mc = new MemberClass<MyClass>();
s_mc.Property_dynamic = new MyClass()
{
Field = 10
}
;
s_dy = s_mc;
}
private volatile object _o = s_dy.Property_dynamic;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t = new Test();
if (t._o.GetType() == typeof(MyClass) && ((MyClass)t._o).Field == 10)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass012.genclass012
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclassregprop.genclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass012.genclass012;
// <Title> Tests generic class regular property used in volatile field initializer.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//<Expects Status=warning>\(17,16\).*CS0219</Expects>
using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
List<int> list = new List<int>()
{
0, 4, 1, 6, 4, 4, 5
}
;
string s = "test";
var mc = new MemberClass<int>();
mc.Property_T = 4;
mc.Property_dynamic = "Test";
dynamic dy = mc;
var result = list.Where(p => p == (int)dy.Property_T).Select(p => new
{
A = dy.Property_T,
B = dy.Property_dynamic
}
).ToList();
if (result.Count == 3)
{
foreach (var m in result)
{
if ((int)m.A != 4 || m.A.GetType() != typeof(int) || (string)m.B != "Test" || m.B.GetType() != typeof(string))
return 1;
}
return 0;
}
return 1;
}
}
//</Code>
}
| |
namespace Mallos.Input
{
using Veldrid;
internal static class VeldridHelpers
{
public static MouseButtons ConvertMouseButtons(this MouseButton button)
{
switch (button)
{
case MouseButton.Left:
return MouseButtons.Left;
case MouseButton.Middle:
return MouseButtons.Middle;
case MouseButton.Right:
return MouseButtons.Right;
case MouseButton.Button1:
return MouseButtons.XButton1;
case MouseButton.Button2:
return MouseButtons.XButton2;
case MouseButton.Button3:
case MouseButton.Button4:
case MouseButton.Button5:
case MouseButton.Button6:
case MouseButton.Button7:
case MouseButton.Button8:
case MouseButton.Button9:
case MouseButton.LastButton:
default:
return MouseButtons.Empty;
}
}
public static Keys ConvertKey(this Key key)
{
switch (key)
{
default:
case Key.Unknown:
return Keys.Unknown;
case Key.ShiftLeft:
return Keys.LeftShift;
case Key.ShiftRight:
return Keys.RightShift;
case Key.ControlLeft:
return Keys.LeftControl;
case Key.ControlRight:
return Keys.RightControl;
case Key.AltLeft:
return Keys.LeftAlt;
case Key.AltRight:
return Keys.RightAlt;
case Key.WinLeft:
return Keys.LWin;
case Key.WinRight:
return Keys.RWin;
case Key.Menu:
return Keys.Menu;
case Key.F1:
return Keys.F1;
case Key.F2:
return Keys.F2;
case Key.F3:
return Keys.F3;
case Key.F4:
return Keys.F4;
case Key.F5:
return Keys.F5;
case Key.F6:
return Keys.F6;
case Key.F7:
return Keys.F7;
case Key.F8:
return Keys.F8;
case Key.F9:
return Keys.F9;
case Key.F10:
return Keys.F10;
case Key.F11:
return Keys.F11;
case Key.F12:
return Keys.F12;
case Key.F13:
return Keys.Unknown;
case Key.F14:
return Keys.Unknown;
case Key.F15:
return Keys.Unknown;
case Key.F16:
return Keys.Unknown;
case Key.F17:
return Keys.Unknown;
case Key.F18:
return Keys.Unknown;
case Key.F19:
return Keys.Unknown;
case Key.F20:
return Keys.Unknown;
case Key.F21:
return Keys.Unknown;
case Key.F22:
return Keys.Unknown;
case Key.F23:
return Keys.Unknown;
case Key.F24:
return Keys.Unknown;
case Key.F25:
return Keys.Unknown;
case Key.F26:
return Keys.Unknown;
case Key.F27:
return Keys.Unknown;
case Key.F28:
return Keys.Unknown;
case Key.F29:
return Keys.Unknown;
case Key.F30:
return Keys.Unknown;
case Key.F31:
return Keys.Unknown;
case Key.F32:
return Keys.Unknown;
case Key.F33:
return Keys.Unknown;
case Key.F34:
return Keys.Unknown;
case Key.F35:
return Keys.Unknown;
case Key.Up:
return Keys.Up;
case Key.Down:
return Keys.Down;
case Key.Left:
return Keys.Left;
case Key.Right:
return Keys.Right;
case Key.Enter:
return Keys.Enter;
case Key.Escape:
return Keys.Escape;
case Key.Space:
return Keys.Space;
case Key.Tab:
return Keys.Tab;
case Key.BackSpace:
return Keys.BackSpace;
case Key.Insert:
return Keys.Insert;
case Key.Delete:
return Keys.Delete;
case Key.PageUp:
return Keys.PageUp;
case Key.PageDown:
return Keys.PageDown;
case Key.Home:
return Keys.Home;
case Key.End:
return Keys.End;
case Key.CapsLock:
return Keys.CapsLock;
case Key.ScrollLock:
return Keys.ScrollLock;
case Key.PrintScreen:
return Keys.PrintScreen;
case Key.Pause:
return Keys.Pause;
case Key.NumLock:
return Keys.NumLock;
case Key.Clear:
return Keys.OemClear;
case Key.Sleep:
return Keys.Sleep;
case Key.Keypad0:
return Keys.NumPad0;
case Key.Keypad1:
return Keys.NumPad1;
case Key.Keypad2:
return Keys.NumPad2;
case Key.Keypad3:
return Keys.NumPad3;
case Key.Keypad4:
return Keys.NumPad4;
case Key.Keypad5:
return Keys.NumPad5;
case Key.Keypad6:
return Keys.NumPad6;
case Key.Keypad7:
return Keys.NumPad7;
case Key.Keypad8:
return Keys.NumPad8;
case Key.Keypad9:
return Keys.NumPad9;
case Key.KeypadDivide:
return Keys.Divide;
case Key.KeypadMultiply:
return Keys.Multiply;
case Key.KeypadSubtract:
return Keys.Subtract;
case Key.KeypadAdd:
return Keys.Add;
case Key.KeypadDecimal:
return Keys.Decimal;
case Key.KeypadEnter:
return Keys.Enter;
case Key.A:
return Keys.A;
case Key.B:
return Keys.B;
case Key.C:
return Keys.C;
case Key.D:
return Keys.D;
case Key.E:
return Keys.E;
case Key.F:
return Keys.F;
case Key.G:
return Keys.G;
case Key.H:
return Keys.H;
case Key.I:
return Keys.I;
case Key.J:
return Keys.J;
case Key.K:
return Keys.K;
case Key.L:
return Keys.L;
case Key.M:
return Keys.M;
case Key.N:
return Keys.N;
case Key.O:
return Keys.O;
case Key.P:
return Keys.P;
case Key.Q:
return Keys.Q;
case Key.R:
return Keys.R;
case Key.S:
return Keys.S;
case Key.T:
return Keys.T;
case Key.U:
return Keys.U;
case Key.W:
return Keys.W;
case Key.X:
return Keys.X;
case Key.Y:
return Keys.Y;
case Key.Z:
return Keys.Z;
case Key.Number0:
return Keys.D0;
case Key.Number1:
return Keys.D1;
case Key.Number2:
return Keys.D2;
case Key.Number3:
return Keys.D3;
case Key.Number4:
return Keys.D4;
case Key.Number5:
return Keys.D5;
case Key.Number6:
return Keys.D6;
case Key.Number7:
return Keys.D7;
case Key.Number8:
return Keys.D8;
case Key.Number9:
return Keys.D9;
case Key.Tilde:
return Keys.Unknown;
case Key.Minus:
return Keys.OemMinus;
case Key.Plus:
return Keys.OemPlus;
case Key.BracketLeft:
return Keys.OemOpenBrackets;
case Key.BracketRight:
return Keys.OemCloseBrackets;
case Key.Semicolon:
return Keys.OemSemicolon;
case Key.Quote:
return Keys.OemQuotes;
case Key.Comma:
return Keys.OemComma;
case Key.Period:
return Keys.OemPeriod;
case Key.Slash:
return Keys.Unknown;
case Key.BackSlash:
return Keys.OemBackslash;
case Key.NonUSBackSlash:
return Keys.OemBackslash;
case Key.LastKey:
return Keys.Unknown;
}
}
}
}
| |
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.CodeFixes.FullyQualify;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.FullyQualify
{
public class FullyQualifyTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace)
{
return Tuple.Create<DiagnosticAnalyzer, CodeFixProvider>(null, new CSharpFullyQualifyCodeFixProvider());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestTypeFromMultipleNamespaces1()
{
await TestAsync(
@"class Class { [|IDictionary|] Method() { Foo(); } }",
@"class Class { System.Collections.IDictionary Method() { Foo(); } }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestTypeFromMultipleNamespaces2()
{
await TestAsync(
@"class Class { [|IDictionary|] Method() { Foo(); } }",
@"class Class { System.Collections.Generic.IDictionary Method() { Foo(); } }",
index: 1);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericWithNoArgs()
{
await TestAsync(
@"class Class { [|List|] Method() { Foo(); } }",
@"class Class { System.Collections.Generic.List Method() { Foo(); } }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericWithCorrectArgs()
{
await TestAsync(
@"class Class { [|List<int>|] Method() { Foo(); } }",
@"class Class { System.Collections.Generic.List<int> Method() { Foo(); } }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestSmartTagDisplayText()
{
await TestSmartTagTextAsync(
@"class Class { [|List<int>|] Method() { Foo(); } }",
"System.Collections.Generic.List");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericWithWrongArgs()
{
await TestMissingAsync(
@"class Class { [|List<int,string>|] Method() { Foo(); } }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericInLocalDeclaration()
{
await TestAsync(
@"class Class { void Foo() { [|List<int>|] a = new List<int>(); } }",
@"class Class { void Foo() { System.Collections.Generic.List<int> a = new List<int>(); } }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericItemType()
{
await TestAsync(
@"using System.Collections.Generic; class Class { List<[|Int32|]> l; }",
@"using System.Collections.Generic; class Class { List<System.Int32> l; }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenerateWithExistingUsings()
{
await TestAsync(
@"using System; class Class { [|List<int>|] Method() { Foo(); } }",
@"using System; class Class { System.Collections.Generic.List<int> Method() { Foo(); } }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenerateInNamespace()
{
await TestAsync(
@"namespace N { class Class { [|List<int>|] Method() { Foo(); } } }",
@"namespace N { class Class { System.Collections.Generic.List<int> Method() { Foo(); } } }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenerateInNamespaceWithUsings()
{
await TestAsync(
@"namespace N { using System; class Class { [|List<int>|] Method() { Foo(); } } }",
@"namespace N { using System; class Class { System.Collections.Generic.List<int> Method() { Foo(); } } }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestExistingUsing()
{
await TestActionCountAsync(
@"using System.Collections.Generic; class Class { [|IDictionary|] Method() { Foo(); } }",
count: 2);
await TestAsync(
@"using System.Collections.Generic; class Class { [|IDictionary|] Method() { Foo(); } }",
@"using System.Collections.Generic; class Class { System.Collections.IDictionary Method() { Foo(); } }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingIfUniquelyBound()
{
await TestMissingAsync(
@"using System; class Class { [|String|] Method() { Foo(); } }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingIfUniquelyBoundGeneric()
{
await TestMissingAsync(
@"using System.Collections.Generic; class Class { [|List<int>|] Method() { Foo(); } }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestOnEnum()
{
await TestAsync(
@"class Class { void Foo() { var a = [|Colors|].Red; } } namespace A { enum Colors {Red, Green, Blue} }",
@"class Class { void Foo() { var a = A.Colors.Red; } } namespace A { enum Colors {Red, Green, Blue} }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestOnClassInheritance()
{
await TestAsync(
@"class Class : [|Class2|] { } namespace A { class Class2 { } }",
@"class Class : A.Class2 { } namespace A { class Class2 { } }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestOnImplementedInterface()
{
await TestAsync(
@"class Class : [|IFoo|] { } namespace A { interface IFoo { } }",
@"class Class : A.IFoo { } namespace A { interface IFoo { } }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAllInBaseList()
{
await TestAsync(
@"class Class : [|IFoo|], Class2 { } namespace A { class Class2 { } } namespace B { interface IFoo { } } ",
@"class Class : B.IFoo, Class2 { } namespace A { class Class2 { } } namespace B { interface IFoo { } }");
await TestAsync(
@"class Class : B.IFoo, [|Class2|] { } namespace A { class Class2 { } } namespace B { interface IFoo { } } ",
@"class Class : B.IFoo, A.Class2 { } namespace A { class Class2 { } } namespace B { interface IFoo { } }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAttributeUnexpanded()
{
await TestAsync(
@"[[|Obsolete|]]class Class { }",
@"[System.Obsolete]class Class { }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAttributeExpanded()
{
await TestAsync(
@"[[|ObsoleteAttribute|]]class Class { }",
@"[System.ObsoleteAttribute]class Class { }");
}
[WorkItem(527360)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestExtensionMethods()
{
await TestMissingAsync(
@"using System.Collections.Generic; class Foo { void Bar() { var values = new List<int>() { 1, 2, 3 }; values.[|Where|](i => i > 1); } }");
}
[WorkItem(538018)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAfterNew()
{
await TestAsync(
@"class Class { void Foo() { List<int> l; l = new [|List<int>|](); } }",
@"class Class { void Foo() { List<int> l; l = new System.Collections.Generic.List<int>(); } }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestArgumentsInMethodCall()
{
await TestAsync(
@"class Class { void Test() { Console.WriteLine([|DateTime|].Today); } }",
@"class Class { void Test() { Console.WriteLine(System.DateTime.Today); } }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestCallSiteArgs()
{
await TestAsync(
@"class Class { void Test([|DateTime|] dt) { } }",
@"class Class { void Test(System.DateTime dt) { } }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestUsePartialClass()
{
await TestAsync(
@"namespace A { public class Class { [|PClass|] c; } } namespace B{ public partial class PClass { } }",
@"namespace A { public class Class { B.PClass c; } } namespace B{ public partial class PClass { } }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericClassInNestedNamespace()
{
await TestAsync(
@"namespace A { namespace B { class GenericClass<T> { } } } namespace C { class Class { [|GenericClass<int>|] c; } }",
@"namespace A { namespace B { class GenericClass<T> { } } } namespace C { class Class { A.B.GenericClass<int> c; } }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestBeforeStaticMethod()
{
await TestAsync(
@"class Class { void Test() { [|Math|].Sqrt(); }",
@"class Class { void Test() { System.Math.Sqrt(); }");
}
[WorkItem(538136)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestBeforeNamespace()
{
await TestAsync(
@"namespace A { class Class { [|C|].Test t; } } namespace B { namespace C { class Test { } } }",
@"namespace A { class Class { B.C.Test t; } } namespace B { namespace C { class Test { } } }");
}
[WorkItem(527395)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestSimpleNameWithLeadingTrivia()
{
await TestAsync(
@"class Class { void Test() { /*foo*/[|Int32|] i; } }",
@"class Class { void Test() { /*foo*/System.Int32 i; } }",
compareTokens: false);
}
[WorkItem(527395)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericNameWithLeadingTrivia()
{
await TestAsync(
@"class Class { void Test() { /*foo*/[|List<int>|] l; } }",
@"class Class { void Test() { /*foo*/System.Collections.Generic.List<int> l; } }",
compareTokens: false);
}
[WorkItem(538740)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyTypeName()
{
await TestAsync(
@"public class Program { public class Inner { } } class Test { [|Inner|] i; }",
@"public class Program { public class Inner { } } class Test { Program.Inner i; }");
}
[WorkItem(538740)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyTypeName_NotForGenericType()
{
await TestMissingAsync(
@"class Program<T> { public class Inner { } } class Test { [|Inner|] i; }");
}
[WorkItem(538764)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyThroughAlias()
{
await TestAsync(
@"using Alias = System; class C { [|Int32|] i; }",
@"using Alias = System; class C { Alias.Int32 i; }");
}
[WorkItem(538763)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyPrioritizeTypesOverNamespaces1()
{
await TestAsync(
@"namespace Outer { namespace C { class C { } } } class Test { [|C|] c; }",
@"namespace Outer { namespace C { class C { } } } class Test { Outer.C.C c; }");
}
[WorkItem(538763)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyPrioritizeTypesOverNamespaces2()
{
await TestAsync(
@"namespace Outer { namespace C { class C { } } } class Test { [|C|] c; }",
@"namespace Outer { namespace C { class C { } } } class Test { Outer.C c; }",
index: 1);
}
[WorkItem(539853)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task BugFix5950()
{
await TestAsync(
@"using System.Console; WriteLine([|Expression|].Constant(123));",
@"using System.Console; WriteLine(System.Linq.Expressions.Expression.Constant(123));",
parseOptions: GetScriptOptions());
}
[WorkItem(540318)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAfterAlias()
{
await TestMissingAsync(
@"using System ; using System . Collections . Generic ; using System . Linq ; class Program { static void Main ( string [ ] args ) { System :: [|Console|] :: WriteLine ( ""TEST"" ) ; } } ");
}
[WorkItem(540942)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingOnIncompleteStatement()
{
await TestMissingAsync(
@"using System ; using System . IO ; class C { static void Main ( string [ ] args ) { [|Path|] } } ");
}
[WorkItem(542643)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAssemblyAttribute()
{
await TestAsync(
@"[ assembly : [|InternalsVisibleTo|] ( ""Project"" ) ] ",
@"[ assembly : System . Runtime . CompilerServices . InternalsVisibleTo ( ""Project"" ) ] ");
}
[WorkItem(543388)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingOnAliasName()
{
await TestMissingAsync(
@"using [|GIBBERISH|] = Foo . GIBBERISH ; class Program { static void Main ( string [ ] args ) { GIBBERISH x ; } } namespace Foo { public class GIBBERISH { } } ");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingOnAttributeOverloadResolutionError()
{
await TestMissingAsync(
@"using System . Runtime . InteropServices ; class M { [ [|DllImport|] ( ) ] static extern int ? My ( ) ; } ");
}
[WorkItem(544950)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestNotOnAbstractConstructor()
{
await TestMissingAsync(
@"using System . IO ; class Program { static void Main ( string [ ] args ) { var s = new [|Stream|] ( ) ; } } ");
}
[WorkItem(545774)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAttribute()
{
var input = @"[ assembly : [|Guid|] ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ";
await TestActionCountAsync(input, 1);
await TestAsync(
input,
@"[ assembly : System . Runtime . InteropServices . Guid ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ");
}
[WorkItem(546027)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGeneratePropertyFromAttribute()
{
await TestMissingAsync(
@"using System ; [ AttributeUsage ( AttributeTargets . Class ) ] class MyAttrAttribute : Attribute { } [ MyAttr ( 123 , [|Version|] = 1 ) ] class D { } ");
}
[WorkItem(775448)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task ShouldTriggerOnCS0308()
{
// CS0308: The non-generic type 'A' cannot be used with type arguments
await TestAsync(
@"using System.Collections;
class Test
{
static void Main(string[] args)
{
[|IEnumerable<int>|] f;
}
}",
@"using System.Collections;
class Test
{
static void Main(string[] args)
{
System.Collections.Generic.IEnumerable<int> f;
}
}");
}
[WorkItem(947579)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task AmbiguousTypeFix()
{
await TestAsync(
@"using n1;
using n2;
class B { void M1() { [|var a = new A();|] }}
namespace n1 { class A { }}
namespace n2 { class A { }}",
@"using n1;
using n2;
class B { void M1() { var a = new n1.A(); }}
namespace n1 { class A { }}
namespace n2 { class A { }}");
}
[WorkItem(995857)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task NonPublicNamespaces()
{
await TestAsync(
@"namespace MS.Internal.Xaml { private class A { } }
namespace System.Xaml { public class A { } }
public class Program { static void M() { [|Xaml|] } }",
@"namespace MS.Internal.Xaml { private class A { } }
namespace System.Xaml { public class A { } }
public class Program { static void M() { System.Xaml } }");
await TestAsync(
@"namespace MS.Internal.Xaml { public class A { } }
namespace System.Xaml { public class A { } }
public class Program { static void M() { [|Xaml|] } }",
@"namespace MS.Internal.Xaml { public class A { } }
namespace System.Xaml { public class A { } }
public class Program { static void M() { MS.Internal.Xaml } }");
}
}
}
| |
// Graph Engine
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security;
using System.Runtime.Serialization;
namespace Trinity.Core.Lib
{
internal enum ExceptionArgument
{
obj,
dictionary,
dictionaryCreationThreshold,
array,
info,
key,
collection,
list,
match,
converter,
queue,
stack,
capacity,
index,
startIndex,
value,
count,
arrayIndex,
name,
mode,
item,
options,
view
}
internal enum ExceptionResource
{
Argument_ImplementIComparable,
Argument_InvalidType,
Argument_InvalidArgumentForComparison,
Argument_InvalidRegistryKeyPermissionCheck,
ArgumentOutOfRange_NeedNonNegNum,
Arg_ArrayPlusOffTooSmall,
Arg_NonZeroLowerBound,
Arg_RankMultiDimNotSupported,
Arg_RegKeyDelHive,
Arg_RegKeyStrLenBug,
Arg_RegSetStrArrNull,
Arg_RegSetMismatchedKind,
Arg_RegSubKeyAbsent,
Arg_RegSubKeyValueAbsent,
Argument_AddingDuplicate,
Serialization_InvalidOnDeser,
Serialization_MissingKeys,
Serialization_NullKey,
Argument_InvalidArrayType,
NotSupported_KeyCollectionSet,
NotSupported_ValueCollectionSet,
ArgumentOutOfRange_SmallCapacity,
ArgumentOutOfRange_Index,
Argument_InvalidOffLen,
Argument_ItemNotExist,
ArgumentOutOfRange_Count,
ArgumentOutOfRange_InvalidThreshold,
ArgumentOutOfRange_ListInsert,
NotSupported_ReadOnlyCollection,
InvalidOperation_CannotRemoveFromStackOrQueue,
InvalidOperation_EmptyQueue,
InvalidOperation_EnumOpCantHappen,
InvalidOperation_EnumFailedVersion,
InvalidOperation_EmptyStack,
ArgumentOutOfRange_BiggerThanCollection,
InvalidOperation_EnumNotStarted,
InvalidOperation_EnumEnded,
NotSupported_SortedListNestedWrite,
InvalidOperation_NoValue,
InvalidOperation_RegRemoveSubKey,
Security_RegistryPermission,
UnauthorizedAccess_RegistryNoWrite,
ObjectDisposed_RegKeyClosed,
NotSupported_InComparableType,
Argument_InvalidRegistryOptionsCheck,
Argument_InvalidRegistryViewCheck
}
internal static class ThrowHelper
{
// Methods
internal static string GetArgumentName(ExceptionArgument argument)
{
switch (argument)
{
case ExceptionArgument.obj:
return "obj";
case ExceptionArgument.dictionary:
return "dictionary";
case ExceptionArgument.dictionaryCreationThreshold:
return "dictionaryCreationThreshold";
case ExceptionArgument.array:
return "array";
case ExceptionArgument.info:
return "info";
case ExceptionArgument.key:
return "key";
case ExceptionArgument.collection:
return "collection";
case ExceptionArgument.list:
return "list";
case ExceptionArgument.match:
return "match";
case ExceptionArgument.converter:
return "converter";
case ExceptionArgument.queue:
return "queue";
case ExceptionArgument.stack:
return "stack";
case ExceptionArgument.capacity:
return "capacity";
case ExceptionArgument.index:
return "index";
case ExceptionArgument.startIndex:
return "startIndex";
case ExceptionArgument.value:
return "value";
case ExceptionArgument.count:
return "count";
case ExceptionArgument.arrayIndex:
return "arrayIndex";
case ExceptionArgument.name:
return "name";
case ExceptionArgument.mode:
return "mode";
case ExceptionArgument.item:
return "item";
case ExceptionArgument.options:
return "options";
case ExceptionArgument.view:
return "view";
}
return string.Empty;
}
internal static string GetResourceName(ExceptionResource resource)
{
switch (resource)
{
case ExceptionResource.Argument_ImplementIComparable:
return "Argument_ImplementIComparable";
case ExceptionResource.Argument_InvalidType:
return "Argument_InvalidType";
case ExceptionResource.Argument_InvalidArgumentForComparison:
return "Argument_InvalidArgumentForComparison";
case ExceptionResource.Argument_InvalidRegistryKeyPermissionCheck:
return "Argument_InvalidRegistryKeyPermissionCheck";
case ExceptionResource.ArgumentOutOfRange_NeedNonNegNum:
return "ArgumentOutOfRange_NeedNonNegNum";
case ExceptionResource.Arg_ArrayPlusOffTooSmall:
return "Arg_ArrayPlusOffTooSmall";
case ExceptionResource.Arg_NonZeroLowerBound:
return "Arg_NonZeroLowerBound";
case ExceptionResource.Arg_RankMultiDimNotSupported:
return "Arg_RankMultiDimNotSupported";
case ExceptionResource.Arg_RegKeyDelHive:
return "Arg_RegKeyDelHive";
case ExceptionResource.Arg_RegKeyStrLenBug:
return "Arg_RegKeyStrLenBug";
case ExceptionResource.Arg_RegSetStrArrNull:
return "Arg_RegSetStrArrNull";
case ExceptionResource.Arg_RegSetMismatchedKind:
return "Arg_RegSetMismatchedKind";
case ExceptionResource.Arg_RegSubKeyAbsent:
return "Arg_RegSubKeyAbsent";
case ExceptionResource.Arg_RegSubKeyValueAbsent:
return "Arg_RegSubKeyValueAbsent";
case ExceptionResource.Argument_AddingDuplicate:
return "Argument_AddingDuplicate";
case ExceptionResource.Serialization_InvalidOnDeser:
return "Serialization_InvalidOnDeser";
case ExceptionResource.Serialization_MissingKeys:
return "Serialization_MissingKeys";
case ExceptionResource.Serialization_NullKey:
return "Serialization_NullKey";
case ExceptionResource.Argument_InvalidArrayType:
return "Argument_InvalidArrayType";
case ExceptionResource.NotSupported_KeyCollectionSet:
return "NotSupported_KeyCollectionSet";
case ExceptionResource.NotSupported_ValueCollectionSet:
return "NotSupported_ValueCollectionSet";
case ExceptionResource.ArgumentOutOfRange_SmallCapacity:
return "ArgumentOutOfRange_SmallCapacity";
case ExceptionResource.ArgumentOutOfRange_Index:
return "ArgumentOutOfRange_Index";
case ExceptionResource.Argument_InvalidOffLen:
return "Argument_InvalidOffLen";
case ExceptionResource.Argument_ItemNotExist:
return "Argument_ItemNotExist";
case ExceptionResource.ArgumentOutOfRange_Count:
return "ArgumentOutOfRange_Count";
case ExceptionResource.ArgumentOutOfRange_InvalidThreshold:
return "ArgumentOutOfRange_InvalidThreshold";
case ExceptionResource.ArgumentOutOfRange_ListInsert:
return "ArgumentOutOfRange_ListInsert";
case ExceptionResource.NotSupported_ReadOnlyCollection:
return "NotSupported_ReadOnlyCollection";
case ExceptionResource.InvalidOperation_CannotRemoveFromStackOrQueue:
return "InvalidOperation_CannotRemoveFromStackOrQueue";
case ExceptionResource.InvalidOperation_EmptyQueue:
return "InvalidOperation_EmptyQueue";
case ExceptionResource.InvalidOperation_EnumOpCantHappen:
return "InvalidOperation_EnumOpCantHappen";
case ExceptionResource.InvalidOperation_EnumFailedVersion:
return "InvalidOperation_EnumFailedVersion";
case ExceptionResource.InvalidOperation_EmptyStack:
return "InvalidOperation_EmptyStack";
case ExceptionResource.ArgumentOutOfRange_BiggerThanCollection:
return "ArgumentOutOfRange_BiggerThanCollection";
case ExceptionResource.InvalidOperation_EnumNotStarted:
return "InvalidOperation_EnumNotStarted";
case ExceptionResource.InvalidOperation_EnumEnded:
return "InvalidOperation_EnumEnded";
case ExceptionResource.NotSupported_SortedListNestedWrite:
return "NotSupported_SortedListNestedWrite";
case ExceptionResource.InvalidOperation_NoValue:
return "InvalidOperation_NoValue";
case ExceptionResource.InvalidOperation_RegRemoveSubKey:
return "InvalidOperation_RegRemoveSubKey";
case ExceptionResource.Security_RegistryPermission:
return "Security_RegistryPermission";
case ExceptionResource.UnauthorizedAccess_RegistryNoWrite:
return "UnauthorizedAccess_RegistryNoWrite";
case ExceptionResource.ObjectDisposed_RegKeyClosed:
return "ObjectDisposed_RegKeyClosed";
case ExceptionResource.NotSupported_InComparableType:
return "NotSupported_InComparableType";
case ExceptionResource.Argument_InvalidRegistryOptionsCheck:
return "Argument_InvalidRegistryOptionsCheck";
case ExceptionResource.Argument_InvalidRegistryViewCheck:
return "Argument_InvalidRegistryViewCheck";
}
return string.Empty;
}
internal static void IfNullAndNullsAreIllegalThenThrow<T>(object value, ExceptionArgument argName)
{
if ((value == null) && (default(T) != null))
{
ThrowArgumentNullException(argName);
}
}
internal static void ThrowArgumentException(ExceptionResource resource)
{
throw new ArgumentException((GetResourceName(resource)));
}
internal static void ThrowArgumentException(ExceptionResource resource, ExceptionArgument argument)
{
throw new ArgumentException((GetResourceName(resource)), GetArgumentName(argument));
}
internal static void ThrowArgumentNullException(ExceptionArgument argument)
{
throw new ArgumentNullException(GetArgumentName(argument));
}
internal static void ThrowArgumentOutOfRangeException()
{
throw new ArgumentOutOfRangeException(GetArgumentName(ExceptionArgument.index), (GetResourceName(ExceptionResource.ArgumentOutOfRange_Index)));
}
internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument)
{
throw new ArgumentOutOfRangeException(GetArgumentName(argument));
}
internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
{
throw new ArgumentOutOfRangeException(GetArgumentName(argument), (GetResourceName(resource)));
}
internal static void ThrowInvalidOperationException(ExceptionResource resource)
{
throw new InvalidOperationException((GetResourceName(resource)));
}
internal static void ThrowKeyNotFoundException()
{
throw new KeyNotFoundException();
}
internal static void ThrowNotSupportedException(ExceptionResource resource)
{
throw new NotSupportedException((GetResourceName(resource)));
}
internal static void ThrowObjectDisposedException(string objectName, ExceptionResource resource)
{
throw new ObjectDisposedException(objectName, (GetResourceName(resource)));
}
internal static void ThrowSecurityException(ExceptionResource resource)
{
throw new SecurityException((GetResourceName(resource)));
}
internal static void ThrowSerializationException(ExceptionResource resource)
{
throw new SerializationException((GetResourceName(resource)));
}
internal static void ThrowUnauthorizedAccessException(ExceptionResource resource)
{
throw new UnauthorizedAccessException((GetResourceName(resource)));
}
internal static void ThrowWrongKeyTypeArgumentException(object key, Type targetType)
{
throw new ArgumentException("Arg_WrongType");
}
internal static void ThrowWrongValueTypeArgumentException(object value, Type targetType)
{
throw new ArgumentException("Arg_WrongType");
}
}
}
| |
using Microsoft.VisualStudio.Services.Agent.Util;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Xunit;
using System;
namespace Microsoft.VisualStudio.Services.Agent.Tests
{
public sealed class LocStringsL0
{
private static readonly Regex ValidKeyRegex = new Regex("^[_a-zA-Z0-9]+$");
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Common")]
public void IsNotMissingCommonLocStrings()
{
ValidateLocStrings(new TestHostContext(this), project: "Microsoft.VisualStudio.Services.Agent");
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Agent")]
public void IsNotMissingListenerLocStrings()
{
ValidateLocStrings(new TestHostContext(this), project: "Agent.Listener");
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void IsNotMissingWorkerLocStrings()
{
ValidateLocStrings(new TestHostContext(this), project: "Agent.Worker");
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "LocString")]
public void IsLocStringsPrettyPrint()
{
// Load the strings.
string stringsFile = Path.Combine(TestUtil.GetSrcPath(), "Misc", "layoutbin", "en-US", "strings.json");
Assert.True(File.Exists(stringsFile), $"File does not exist: {stringsFile}");
var resourceDictionary = IOUtil.LoadObject<Dictionary<string, object>>(stringsFile);
// sort the dictionary.
Dictionary<string, object> sortedResourceDictionary = new Dictionary<string, object>();
foreach (var res in resourceDictionary.OrderBy(r => r.Key))
{
sortedResourceDictionary[res.Key] = res.Value;
}
// print to file.
string prettyStringsFile = Path.Combine(TestUtil.GetSrcPath(), "Misc", "layoutbin", "en-US", "strings.json.pretty");
IOUtil.SaveObject(sortedResourceDictionary, prettyStringsFile);
Assert.True(string.Equals(File.ReadAllText(stringsFile), File.ReadAllText(prettyStringsFile)), $"Orginal string.json file: {stringsFile} is not pretty printed, replace it with: {prettyStringsFile}");
// delete file on succeed
File.Delete(prettyStringsFile);
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "LocString")]
public void FindExtraLocStrings()
{
// Load the strings.
string stringsFile = Path.Combine(TestUtil.GetSrcPath(), "Misc", "layoutbin", "en-US", "strings.json");
Assert.True(File.Exists(stringsFile), $"File does not exist: {stringsFile}");
var resourceDictionary = IOUtil.LoadObject<Dictionary<string, object>>(stringsFile);
// Find all loc string key in source file.
//
// Note, narrow the search to each project folder only. Otherwise intermittent errors occur
// when recursively searching due to parallel tests are deleting temp folders (DirectoryNotFoundException).
var keys = new List<string>();
string[] sourceFiles =
Directory.GetFiles(TestUtil.GetProjectPath("Microsoft.VisualStudio.Services.Agent"), "*.cs", SearchOption.AllDirectories)
.Concat(Directory.GetFiles(TestUtil.GetProjectPath("Agent.Listener"), "*.cs", SearchOption.AllDirectories))
.Concat(Directory.GetFiles(TestUtil.GetProjectPath("Agent.Worker"), "*.cs", SearchOption.AllDirectories))
.ToArray();
foreach (string sourceFile in sourceFiles)
{
// Skip files in the obj directory.
if (sourceFile.Contains(StringUtil.Format("{0}obj{0}", Path.DirectorySeparatorChar)))
{
continue;
}
foreach (string line in File.ReadAllLines(sourceFile))
{
// Search for calls to the StringUtil.Loc method within the line.
const string Pattern = "StringUtil.Loc(";
int searchIndex = 0;
int patternIndex;
while (searchIndex < line.Length &&
(patternIndex = line.IndexOf(Pattern, searchIndex)) >= 0)
{
// Bump the search index in preparation for the for the next iteration within the same line.
searchIndex = patternIndex + Pattern.Length;
// Extract the resource key.
int keyStartIndex = patternIndex + Pattern.Length;
int keyEndIndex;
if (keyStartIndex + 2 < line.Length && // Key should start with a ", be followed by at least
line[keyStartIndex] == '"' && // one character, and end with a ".
(keyEndIndex = line.IndexOf('"', keyStartIndex + 1)) > 0)
{
// Remove the first and last double quotes.
keyStartIndex++;
keyEndIndex--;
string key = line.Substring(
startIndex: keyStartIndex,
length: keyEndIndex - keyStartIndex + 1);
if (ValidKeyRegex.IsMatch(key))
{
// A valid key was extracted.
keys.Add(key);
continue;
}
}
}
}
}
// find extra loc strings.
var extraKeys = resourceDictionary.Keys.Where(x => !keys.Contains(x))?.ToList();
if (extraKeys != null)
{
Assert.True(extraKeys.Count == 0, $"Please save company's money by removing extra loc strings:{Environment.NewLine}{string.Join(Environment.NewLine, extraKeys)}");
}
}
private void ValidateLocStrings(TestHostContext hc, string project)
{
using (hc)
{
Tracing trace = hc.GetTrace();
var keys = new List<string>();
var badLines = new List<BadLineInfo>();
// Search for source files within the project.
trace.Verbose("Searching source files:");
string[] sourceFiles = Directory.GetFiles(
TestUtil.GetProjectPath(project),
"*.cs",
SearchOption.AllDirectories);
foreach (string sourceFile in sourceFiles)
{
// Skip files in the obj directory.
if (sourceFile.Contains(StringUtil.Format("{0}obj{0}", Path.DirectorySeparatorChar)))
{
continue;
}
trace.Verbose($" {sourceFile}");
foreach (string line in File.ReadAllLines(sourceFile))
{
// Search for calls to the StringUtil.Loc method within the line.
const string Pattern = "StringUtil.Loc(";
int searchIndex = 0;
int patternIndex;
while (searchIndex < line.Length &&
(patternIndex = line.IndexOf(Pattern, searchIndex)) >= 0)
{
// Bump the search index in preparation for the for the next iteration within the same line.
searchIndex = patternIndex + Pattern.Length;
// Extract the resource key.
int keyStartIndex = patternIndex + Pattern.Length;
int keyEndIndex;
if (keyStartIndex + 2 < line.Length && // Key should start with a ", be followed by at least
line[keyStartIndex] == '"' && // one character, and end with a ".
(keyEndIndex = line.IndexOf('"', keyStartIndex + 1)) > 0)
{
// Remove the first and last double quotes.
keyStartIndex++;
keyEndIndex--;
string key = line.Substring(
startIndex: keyStartIndex,
length: keyEndIndex - keyStartIndex + 1);
if (ValidKeyRegex.IsMatch(key))
{
// A valid key was extracted.
keys.Add(key);
continue;
}
}
// Something went wrong. The pattern was found, but the resource key could not be determined.
badLines.Add(new BadLineInfo { File = sourceFile, Line = line });
}
}
}
// Load the strings.
string stringsFile = Path.Combine(TestUtil.GetSrcPath(), "Misc", "layoutbin", "en-US", "strings.json");
Assert.True(File.Exists(stringsFile), $"File does not exist: {stringsFile}");
var resourceDictionary = IOUtil.LoadObject<Dictionary<string, object>>(stringsFile);
// Find missing keys.
string[] missingKeys =
keys
.Where(x => !resourceDictionary.ContainsKey(x))
.OrderBy(x => x)
.ToArray();
if (missingKeys.Length > 0)
{
trace.Error("One or more resource keys missing from resources file:");
foreach (string missingKey in missingKeys)
{
trace.Error($" {missingKey}");
}
}
// Validate whether resource keys couldn't be interpreted.
if (badLines.Count > 0)
{
trace.Error("Bad lines detected. Unable to interpret resource key(s).");
IEnumerable<IGrouping<string, BadLineInfo>> badLineGroupings =
badLines
.GroupBy(x => x.File)
.OrderBy(x => x.Key)
.ToArray();
foreach (IGrouping<string, BadLineInfo> badLineGrouping in badLineGroupings)
{
trace.Error($"File: {badLineGrouping.First().File}");
foreach (BadLineInfo badLine in badLineGrouping)
{
trace.Error($" Line: {badLine.Line}");
}
}
}
Assert.True(missingKeys.Length == 0, $"One or more resource keys missing from resources files. Consult the trace log: {hc.TraceFileName}");
Assert.True(badLines.Count == 0, $"Unable to determine one or more resource keys. Consult the trace log: {hc.TraceFileName}");
}
}
private sealed class BadLineInfo
{
public string File { get; set; }
public string Line { get; set; }
}
}
}
| |
using System;
using NUnit.Framework;
using ProtoCore.DSASM.Mirror;
using ProtoTestFx.TD;
namespace ProtoTest.TD.Imperative
{
class WhileTest
{
public TestFrameWork thisTest = new TestFrameWork();
string testPath = "..\\..\\..\\Scripts\\TD\\Imperative\\WhileStatement\\";
[SetUp]
public void Setup()
{
}
[Test]
[Category("SmokeTest")]
public void T01_NegativeSyntax_Negative()
{
Assert.Throws(typeof(ProtoCore.Exceptions.CompileErrorsOccured), () =>
{
string src = @"[Imperative]
{
i = 0;
temp = 1;
while ( i < 5 ]
{
temp=temp+1;
i=i+1;
}
} ";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
});
}
[Test]
[Category("SmokeTest")]
public void T02_AssociativeBlock_Negative()
{
Assert.Throws(typeof(ProtoCore.Exceptions.CompileErrorsOccured), () =>
{
string src = @"[Associative]
{
i = 0;
temp = 1;
while ( i <= 5)
{
temp = temp + 1;
i = i + 1;
}
}";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
});
}
[Test]
[Category("SmokeTest")]
public void T03_UnnamedBlock_Negative()
{
Assert.Throws(typeof(ProtoCore.Exceptions.CompileErrorsOccured), () =>
{
string src = @"{
i = 0;
temp = 1;
while ( i < 5 )
{
temp = temp + 1;
i = i + 1;
}
}";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
});
}
[Test]
[Category("SmokeTest")]
public void T04_OutsideBlock_Negative()
{
Assert.Throws(typeof(ProtoCore.Exceptions.CompileErrorsOccured), () =>
{
string src = @"i = 0;
temp = 1;
while( i < 5 )
{
temp = temp + 1;
i = i + 1;
}";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
});
}
[Test]
[Category("SmokeTest")]
public void T05_WithinFunction()
{
string src = @"testvar;
[Imperative]
{
def fn1 : int (a : int)
{
i = 0;
temp = 1;
while ( i < a )
{
temp = temp + 1;
i = i + 1;
}
return = temp;
}
testvar = fn1(5);
}
";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
Assert.IsTrue((Int64)mirror.GetValue("testvar").Payload == 6);
}
[Test]
[Category("SmokeTest")]
public void T06_InsideNestedBlock()
{
string src = @"temp;
a;
b;
[Associative]
{
a = 4;
b = a*2;
temp = 0;
[Imperative]
{
i=0;
temp=1;
while(i<=5)
{
i=i+1;
temp=temp+1;
}
}
a = temp;
}";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
Assert.IsTrue((Int64)mirror.GetValue("temp").Payload == 7);
Assert.IsTrue((Int64)mirror.GetValue("a").Payload == 7);
Assert.IsTrue((Int64)mirror.GetValue("b").Payload == 14);
}
[Test]
[Category("SmokeTest")]
public void T07_BreakStatement()
{
string src = @"temp;
i;
[Imperative]
{
i=0;
temp=0;
while( i <= 5 )
{
i = i + 1;
if ( i == 3 )
break;
temp=temp+1;
}
}";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
Assert.IsTrue((Int64)mirror.GetValue("temp").Payload == 2);
Assert.IsTrue((Int64)mirror.GetValue("i").Payload == 3);
}
[Test]
[Category("SmokeTest")]
public void T08_ContinueStatement()
{
string src = @"temp;
i;
[Imperative]
{
i = 0;
temp = 0;
while ( i <= 5 )
{
i = i + 1;
if( i <= 3 )
{
continue;
}
temp=temp+1;
}
}";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
Assert.IsTrue((Int64)mirror.GetValue("temp").Payload == 3);
Assert.IsTrue((Int64)mirror.GetValue("i").Payload == 6);
}
[Test]
[Category("SmokeTest")]
public void T09_NestedWhileStatement()
{
string src = @"temp;
i;
a;
p;
[Imperative]
{
i = 1;
a = 0;
p = 0;
temp = 0;
while( i <= 5 )
{
a = 1;
while( a <= 5 )
{
p = 1;
while( p <= 5 )
{
temp = temp + 1;
p = p + 1;
}
a = a + 1;
}
i = i + 1;
}
} ";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
Assert.IsTrue((Int64)mirror.GetValue("temp").Payload == 125);
Assert.IsTrue((Int64)mirror.GetValue("i").Payload == 6);
Assert.IsTrue((Int64)mirror.GetValue("a").Payload == 6);
Assert.IsTrue((Int64)mirror.GetValue("p").Payload == 6);
}
[Test]
[Category("SmokeTest")]
public void T10_WhilewithAssgnmtStatement_Negative()
{
Assert.Throws(typeof(ProtoCore.Exceptions.CompileErrorsOccured), () =>
{
string src = @"[Imperative]
{
i = 2;
temp = 1;
while( i = 2 )
{
i = i + 1 ;
temp = temp + 1 ;
}
}";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
});
}
[Test]
[Category("SmokeTest")]
public void T11_WhilewithLogicalOperators()
{
string src = @"temp1;temp2;temp3;temp4;
[Imperative]
{
i1 = 5;
temp1 = 1;
while( i >= 2)
{
i1=i1-1;
temp1=temp1+1;
}
i2 = 5;
temp2 = 1;
while ( i2 != 1 )
{
i2 = i2 - 1;
temp2 = temp2 + 1;
}
temp3 = 2;
while( i2 == 1 )
{
temp3 = temp3 + 1;
i2 = i2 - 1;
}
while( ( i2 == 1 ) && ( i1 == 1 ) )
{
temp3=temp3+1;
i2=i2-1;
}
temp4 = 3;
while( ( i2 == 1 ) || ( i1 == 5 ) )
{
i1 = i1 - 1;
temp4 = 4;
}
}
";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
Assert.IsTrue((Int64)mirror.GetValue("temp1").Payload == 1);
Assert.IsTrue((Int64)mirror.GetValue("temp2").Payload == 5);
Assert.IsTrue((Int64)mirror.GetValue("temp3").Payload == 3);
Assert.IsTrue((Int64)mirror.GetValue("temp4").Payload == 4);
}
[Test]
[Category("SmokeTest")]
public void T12_WhileWithFunctionCall()
{
string src = @"testvar;
[Imperative]
{
def fn1 :int ( a : int )
{
i = 0;
temp = 1;
while ( i < a )
{
temp = temp + 1;
i = i + 1;
}
return = temp;
}
testvar = 8;
while ( testvar != fn1(6) )
{
testvar=testvar-1;
}
}";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
Assert.IsTrue((Int64)mirror.GetValue("testvar").Payload == 7);
}
[Test]
[Category("SmokeTest")]
public void T13_DoWhileStatment_negative()
{
Assert.Throws(typeof(ProtoCore.Exceptions.CompileErrorsOccured), () =>
{
string src = @"[Imperative]
{
a = 1;
temp = 1;
do
{
temp = temp + 1;
a = a + 1;
} while(a<3);
}
";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
});
}
[Test]
[Category("SmokeTest")]
public void T14_TestFactorialUsingWhileStmt()
{
string src = @"a;
factorial_a;
[Imperative]
{
a = 1;
b = 1;
while( a <= 5 )
{
a = a + 1;
b = b * (a-1) ;
}
factorial_a = b * a;
}";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
Assert.IsTrue((Int64)mirror.GetValue("a").Payload == 6);
Assert.IsTrue((Int64)mirror.GetValue("factorial_a").Payload == 720);
}
[Test]
[Category("SmokeTest")]
public void T15_TestWhileWithDecimalvalues()
{
string src = @"a;b;
[Imperative]
{
a = 1.5;
b = 1;
while(a <= 5.5)
{
a = a + 1;
b = b * (a-1) ;
}
}";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
Assert.IsTrue((double)mirror.GetValue("a").Payload == 6.5);
Assert.IsTrue((double)mirror.GetValue("b").Payload == 324.84375);
}
[Test]
[Category("SmokeTest")]
public void T16_TestWhileWithLogicalOperators()
{
string src = @"a;b;
[Imperative]
{
a = 1.5;
b = 1;
while(a <= 5.5 && b < 20)
{
a = a + 1;
b = b * (a-1) ;
}
}";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
Assert.IsTrue((double)mirror.GetValue("a").Payload == 5.5);
Assert.IsTrue((double)mirror.GetValue("b").Payload == 59.0625);
}
[Test]
[Category("SmokeTest")]
public void T17_TestWhileWithBool()
{
string src = @"a;
[Imperative]
{
a = 0;
while(a == false)
{
a = 1;
}
}";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
Assert.IsTrue((Int64)mirror.GetValue("a").Payload == 1);
}
[Test]
[Category("SmokeTest")]
public void T18_TestWhileWithNull()
{
string src = @"a;b;c;
[Imperative]
{
a = null;
c = null;
while(a == 0)
{
a = 1;
}
while(null == c)
{
c = 1;
}
while(a == b)
{
a = 2;
}
}";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
Assert.IsTrue((Int64)mirror.GetValue("a").Payload == 2);
Assert.IsTrue((Int64)mirror.GetValue("c").Payload == 1);
Assert.IsTrue(mirror.GetValue("b").DsasmValue.optype == ProtoCore.DSASM.AddressType.Null);
}
[Test]
[Category("SmokeTest")]
public void T19_TestWhileWithIf()
{
string src = @"a;b;
[Imperative]
{
a = 2;
b = a;
while ( a <= 4)
{
if(a < 4)
{
b = b + a;
}
else
{
b = b + 2*a;
}
a = a + 1;
}
}";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
Assert.IsTrue((Int64)mirror.GetValue("a").Payload == 5);
Assert.IsTrue((Int64)mirror.GetValue("b").Payload == 15);
}
[Test]
[Category("SmokeTest")]
public void T20_Test()
{
string src = @"a = 1;
";
ExecutionMirror mirror = thisTest.RunScriptSource(src);
}
[Test]
public void T20_TestWhileToCreate2DimArray()
{
// Assert.Fail("1463672 - Sprint 20 : rev 2140 : 'array' seems to be reserved as a keyword in a specific case ! ");
string code = @"
def Create2DArray( col : int)
{
result = [Imperative]
{
array = { 1, 2 };
counter = 0;
while( counter < col)
{
array[counter] = { 1, 2};
counter = counter + 1;
}
return = array;
}
return = result;
}
x = Create2DArray( 2) ;
";
ExecutionMirror mirror = thisTest.RunScriptSource(code);
Object[] v1 = new Object[] { new Object[] { 1, 2 }, new Object[] { 1, 2 } };
thisTest.Verify("x", v1);
}
[Test]
[Category("SmokeTest")]
public void T21_TestWhileToCallFunctionWithNoReturnType()
{
string code = @"
def foo ()
{
return = 0;
}
def test ()
{
temp = [Imperative]
{
t1 = foo();
t2 = 2;
while ( t2 > ( t1 + 1 ) )
{
t1 = t1 + 1;
}
return = t1;
}
return = temp;
}
x = test();
";
ExecutionMirror mirror = thisTest.RunScriptSource(code);
thisTest.Verify("x", 1);
}
[Test]
[Category("SmokeTest")]
public void T22_Defect_1463683()
{
string code = @"
def foo ()
{
return = 1;
}
def test ()
{
temp = [Imperative]
{
t1 = foo();
t2 = 3;
if ( t2 < ( t1 + 1 ) )
{
t1 = t1 + 2;
}
else
{
t1 = t1 ;
}
return = t1;
}
return = temp;
}
x = test();";
ExecutionMirror mirror = thisTest.RunScriptSource(code);
thisTest.Verify("x", 1);
}
[Test]
[Category("SmokeTest")]
public void T22_Defect_1463683_2()
{
string code = @"
def foo ()
{
return = 1;
}
class A
{
t1 : int;
t2 : int;
def test ()
{
temp = [Imperative]
{
t1 = foo();
t2 = 3;
if ( t2 < ( t1 + 1 ) )
{
t1 = t1 + 2;
}
else
{
t1 = t1 ;
}
return = t1;
}
return = temp;
}
}
a = A.A();
x = a.test();
x1 = a.t1;
x2 = a.t2;
y;y1;y2;
[Imperative]
{
y = a.test();
y1 = a.t1;
y2 = a.t2;
}";
ExecutionMirror mirror = thisTest.RunScriptSource(code);
thisTest.Verify("x", 1);
thisTest.Verify("x1", 1);
thisTest.Verify("x2", 3);
thisTest.Verify("y", 1);
thisTest.Verify("y1", 1);
thisTest.Verify("y2", 3);
}
[Test]
[Category("SmokeTest")]
public void T22_Defect_1463683_3()
{
string errmsg = "1467318 - Cannot return an array from a function whose return type is var with undefined rank (-2)";
string src = @"def foo ()
{
return = { 0, 1, 2 };
}
class A
{
t1;
t2;
def test ()
{
c = 0;
temp = [Imperative]
{
t1 = foo();
t2 = 0;
for ( i in t1 )
{
if (i < ( t2 + 1 ) )
{
t1[c] = i + 1;
}
else
{
t1[c] = i +2 ;
}
c = c + 1 ;
}
return = t1;
}
return = temp;
}
}
a = A.A();
x = a.test();
x1 = a.t1;
x2 = a.t2;
y;y1;y2;
[Imperative]
{
y = a.test();
y1 = a.t1;
y2 = a.t2;
}";
thisTest.VerifyRunScriptSource(src, errmsg);
Object[] v1 = new Object[] { 1, 3, 4 };
thisTest.Verify("x", v1);
thisTest.Verify("x1", v1);
thisTest.Verify("x2", 0);
thisTest.Verify("y", v1);
thisTest.Verify("y1", v1);
thisTest.Verify("y2", 0);
}
[Test]
[Category("SmokeTest")]
public void T22_Defect_1463683_4()
{
string code = @"
def foo ()
{
return = 1;
}
def test (t2)
{
temp = [Imperative]
{
t1 = foo();
if ( (t2 > ( t1 + 1 )) && (t2 >=3) )
{
t1 = t1 + 2;
}
else
{
t1 = t1 ;
}
return = t1;
}
return = temp;
}
x1 = test(3);
x2 = test(0);";
ExecutionMirror mirror = thisTest.RunScriptSource(code);
thisTest.Verify("x1", 3);
thisTest.Verify("x2", 1);
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="ProxySimple.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: Base class for all the Win32 and office Controls.
//
// The ProxySimple class is the base class for the leafs
// in the raw element tree. Also proxy that directly derives
// from this clas should not care about events
//
// The UIAutomation Simple class is limited to UI elements that are
// Hwnd based. This makes it of little use for Win32 and office controls.
// The ProxySimple class removes this limitation. This leads to a couple of
// changes; RuntTimeID and BoundingRect must be implemented by this object.
//
//
// Class ProxySimple: IRawElementProviderFragment, IRawElementProviderSimple
// BoundingRectangle
// RuntimeId
// Properties
// GetPatterns
// SetFocus
//
// Example: ComboboxButton, MenuItem, Office CommandBar button, ListViewSubitem
//
//
//
// History:
// 07/01/2003 : a-jeanp Created
// 08/06/2003: alexsn - Changes that allow more classes to be derived from Simple
// Description update
//---------------------------------------------------------------------------
// PRESHARP: In order to avoid generating warnings about unkown message numbers and unknown pragmas.
#pragma warning disable 1634, 1691
using System;
using System.Text;
using System.Windows.Automation;
using System.Windows.Automation.Provider;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Collections;
using Accessibility;
using System.Windows;
using System.Windows.Input;
using MS.Win32;
namespace MS.Internal.AutomationProxies
{
// Base Class for all the Windows Control.
// Implements the default behavior
//
// The distinction between Proxy siblings is made through an ID (called _item).
// The underlying hwnd is kept, as the proxy parent and a flag to _fSubtree.
class ProxySimple : IRawElementProviderSimple, IRawElementProviderFragment
{
// ------------------------------------------------------
//
// Constructors
//
// ------------------------------------------------------
#region Constructors
// Constructor.
// Param "hwnd" is the handle to underlying window
// Param "parent" is the Parent, must be a ProxyFragment
// Param "item" is the ID of item to represent
internal ProxySimple(IntPtr hwnd, ProxyFragment parent, int item)
{
_hwnd = hwnd;
_item = item;
_parent = parent;
// is element a leaf?
_fSubTree = (_parent != null);
}
#endregion
// ------------------------------------------------------
//
// Patterns Implementation
//
// ------------------------------------------------------
#region ProxySimple Methods
internal virtual ProviderOptions ProviderOptions
{
get
{
return ProviderOptions.ClientSideProvider;
}
}
// Returns the bounding rectangle of the control.
// If the control is not an hwnd, the subclass should implement this call
internal virtual Rect BoundingRectangle
{
get
{
if (_hwnd == IntPtr.Zero)
{
return Rect.Empty;
}
NativeMethods.Win32Rect controlRectangle = NativeMethods.Win32Rect.Empty;
if (!Misc.GetWindowRect(_hwnd, ref controlRectangle))
{
return Rect.Empty;
}
// Don't normalize, consumers & subclasses will normalize with conditionals
return controlRectangle.ToRect(false);
}
}
// Sets the focus to this item.
// By default, fails
internal virtual bool SetFocus()
{
return false;
}
// Returns the Run Time Id.
//
// The RunTimeID is a array of int with RID [0] set to 1 and RID [1] the hwnd
// identifier. The remaining of the chain are values one per sub node in
// the raw element tree.
// Avalon and other none hwnd based elements have RunTimeIDs that never starts
// with '1'. This makes the RunTimeId for Win32 controls uniq.
//
// By default the _item data member is used as ID for each depth
// in the element tree
internal virtual int [] GetRuntimeId ()
{
if (_fSubTree && !IsHwndElement())
{
// add the id for this level at the end of the chain
return Misc.AppendToRuntimeId(GetParent().GetRuntimeId(), _item);
}
else
{
// UIA handles runtimeID for the HWND part for us
return null;
}
}
// Get unique ID for this element...
// This is the internal version of GetRuntimeId called when a complete RuntimeId is needed internally (e.g.
// RuntimeId is needed to create StructureChangedEventArgs) vs when UIAutomation asks for a RuntimeId
// through IRawElementProviderFragment. WCTL #32188 : We need a helper method in UIAutomationCore that takes
// an hwnd and returns a RuntimeId. Symptom of this being broken is getting InvalidOperationException
// during events with message: Value cannot be null. Parameter name: runtimeId.
internal int[] MakeRuntimeId()
{
int idLen = ( _fSubTree && !IsHwndElement() ) ? 3 : 2;
int[] id = new int[idLen];
// Base runtime id is the number indicating Win32Provider + hwnd
id[0] = ProxySimple.Win32ProviderRuntimeIdBase;
id[1] = _hwnd.ToInt32();
// Append part id to make this unique
if ( idLen == 3 )
{
id[2] = _item;
}
return id;
}
internal virtual IRawElementProviderSimple HostRawElementProvider
{
get
{
if (_hwnd == IntPtr.Zero || (GetParent() != null && GetParent()._hwnd == _hwnd))
{
return null;
}
return AutomationInteropProvider.HostProviderFromHandle(_hwnd);
}
}
internal virtual ProxySimple GetParent()
{
return _parent;
}
// Process all the Element Properties
internal virtual object GetElementProperty(AutomationProperty idProp)
{
// we can handle some properties locally
if (idProp == AutomationElement.LocalizedControlTypeProperty)
{
return _sType;
}
else if(idProp == AutomationElement.ControlTypeProperty)
{
return _cControlType != null ? (object)_cControlType.Id : null;
}
else if (idProp == AutomationElement.IsContentElementProperty)
{
return _item >= 0 && _fIsContent;
}
else if (idProp == AutomationElement.NameProperty)
{
return LocalizedName;
}
else if (idProp == AutomationElement.AccessKeyProperty)
{
return GetAccessKey();
}
else if (idProp == AutomationElement.IsEnabledProperty)
{
return Misc.IsEnabled(_hwnd);
}
else if (idProp == AutomationElement.IsKeyboardFocusableProperty)
{
return IsKeyboardFocusable();
}
else if (idProp == AutomationElement.ProcessIdProperty)
{
// Get the pid of the process that the HWND lives in, not the
// pid that this proxy lives in
uint pid;
Misc.GetWindowThreadProcessId(_hwnd, out pid);
return (int)pid;
}
else if (idProp == AutomationElement.ClickablePointProperty)
{
NativeMethods.Win32Point pt = new NativeMethods.Win32Point();
if (GetClickablePoint(out pt, !IsHwndElement()))
{
// Due to P/Invoke marshalling issues, the reurn value is in the
// form of a {x,y} array instead of using the Point datatype
return new double[] { pt.x, pt.y };
}
return AutomationElement.NotSupported;
}
else if (idProp == AutomationElement.HasKeyboardFocusProperty)
{
// Check first if the hwnd has the Focus
// Punt if not the case, drill down otherwise
// If already focused, leave as-is. Calling SetForegroundWindow
// on an already focused HWND will remove focus!
return Misc.GetFocusedWindow() == _hwnd ? IsFocused() : false;
}
else if (idProp == AutomationElement.AutomationIdProperty)
{
// PerSharp/PreFast will flag this as a warning 6507/56507: Prefer 'string.IsNullOrEmpty(_sAutomationId)' over checks for null and/or emptiness.
// _sAutomationId being null is invalid, while being empty is a valid state.
// The use of IsNullOrEmpty while hide this.
#pragma warning suppress 6507
System.Diagnostics.Debug.Assert(_sAutomationId != null, "_sAutomationId is null!");
#pragma warning suppress 6507
return _sAutomationId.Length > 0 ? _sAutomationId : null;
}
else if (idProp == AutomationElement.IsOffscreenProperty)
{
return IsOffscreen();
}
else if (idProp == AutomationElement.HelpTextProperty)
{
return HelpText;
}
else if (idProp == AutomationElement.FrameworkIdProperty)
{
return WindowsFormsHelper.IsWindowsFormsControl(_hwnd) ? "WinForm" : "Win32";
}
return null;
}
internal virtual bool IsKeyboardFocusable()
{
// if it curently has focus it is obviosly focusable
if (Misc.GetFocusedWindow() == _hwnd && IsFocused())
{
return true;
}
// If it's visible and enabled it might be focusable
if (SafeNativeMethods.IsWindowVisible(_hwnd) && (bool)GetElementProperty(AutomationElement.IsEnabledProperty))
{
// If it is something that we know is focusable and have marked it that way in the specific
// proxy it should be focusable.
if (IsHwndElement())
{
// For a control that has the WS_TABSTOP style set, it should be focusable.
// Toolbars are genrealy not focusable but the short cut toolbar on the start menu is.
// The WS_TABSTOP will pick this up.
if (Misc.IsBitSet(WindowStyle, NativeMethods.WS_TABSTOP))
{
return true;
}
else
{
return _fIsKeyboardFocusable;
}
}
else
{
return _fIsKeyboardFocusable;
}
}
return false;
}
internal virtual bool IsOffscreen()
{
Rect itemRect = BoundingRectangle;
if (itemRect.IsEmpty)
{
return true;
}
// As per the specs, IsOffscreen only takes immediate parent-child relationship into account,
// so we only need to check if this item in offscreen with respect to its immediate parent.
ProxySimple parent = GetParent();
if (parent != null )
{
if ((bool)parent.GetElementProperty(AutomationElement.IsOffscreenProperty))
{
return true;
}
// Now check to see if this item in visible on its parent
Rect parentRect = parent.BoundingRectangle;
if (!parentRect.IsEmpty && !Misc.IsItemVisible(ref parentRect, ref itemRect))
{
return true;
}
}
// if this element is not on any monitor than it is off the screen.
NativeMethods.Win32Rect itemWin32Rect = new NativeMethods.Win32Rect(itemRect);
return UnsafeNativeMethods.MonitorFromRect(ref itemWin32Rect, UnsafeNativeMethods.MONITOR_DEFAULTTONULL) == IntPtr.Zero;
}
internal virtual string GetAccessKey()
{
// If the control is part of a dialog box or a form,
// get the accelerator from the static preceding that control
// on the dialog.
if (GetParent() == null && (bool)GetElementProperty(AutomationElement.IsKeyboardFocusableProperty))
{
string sRawName = Misc.GetControlName(_hwnd, false);
return string.IsNullOrEmpty(sRawName) ? null : Misc.AccessKey(sRawName);
}
return null;
}
// Returns a pattern interface if supported.
internal virtual object GetPatternProvider(AutomationPattern iid)
{
return null;
}
internal virtual ProxySimple[] GetEmbeddedFragmentRoots()
{
return null;
}
//Gets the controls help text
internal virtual string HelpText
{
get
{
return null;
}
}
// Gets the localized name
internal virtual string LocalizedName
{
get
{
return null;
}
}
#endregion
#region Dispatch Event
// Dispatch WinEvent notifications
//
// A Generic mechanism is implemented to support most WinEvents.
// On reception of a WinEvent, a Proxy is created and a call to this method
// is made. This method then raises a UIAutomation Events based on the
// WinEvents IDs. The old value for a property is always set to null
internal virtual void DispatchEvents(int eventId, object idProp, int idObject, int idChild)
{
EventManager.DispatchEvent(this, _hwnd, eventId, idProp, idObject);
}
internal virtual void RecursiveRaiseEvents(object idProp, AutomationPropertyChangedEventArgs e)
{
return;
}
#endregion
#region IRawElementProviderSimple
// ------------------------------------------------------
//
// Default implementation for the IRawElementProviderSimple.
// Maps the UIAutomation methods to ProxySimple methods.
//
// ------------------------------------------------------
ProviderOptions IRawElementProviderSimple.ProviderOptions
{
get
{
return ProviderOptions;
}
}
// Return the context associated with this element
IRawElementProviderSimple IRawElementProviderSimple.HostRawElementProvider
{
get
{
return HostRawElementProvider;
}
}
// Request the closest rectangle encompassing this element
Rect IRawElementProviderFragment.BoundingRectangle
{
get
{
// Spec says that if an element is offscreen, we have the option of letting
// the rect pass through or returning Rect.Empty; here, we intentionally
// let it pass through as a convenience for MITA.
// ProxySimple.BoundingRectanlgle
return BoundingRectangle;
}
}
// Request to return the element in the specified direction
// ProxySimple object are leaf so it returns null except for the parent
IRawElementProviderFragment IRawElementProviderFragment.Navigate(NavigateDirection direction)
{
System.Diagnostics.Debug.Assert(_parent != null, "Navigate: Leaf element does not have parent");
switch (direction)
{
case NavigateDirection.Parent:
{
return GetParent();
}
case NavigateDirection.NextSibling:
{
// NOTE: Do not use GetParent(), call _parent explicitly
return _parent.GetNextSibling(this);
}
case NavigateDirection.PreviousSibling:
{
// NOTE: Do not use GetParent(), call _parent explicitly
return _parent.GetPreviousSibling(this);
}
}
return null;
}
IRawElementProviderFragmentRoot IRawElementProviderFragment.FragmentRoot
{
// NOTE: The implementation below is correct one.
// DO NOT CHANGE IT, since things will break
// There can be only 1 ROOT for each constellation
get
{
// Traverse up the parents until you find a node with no parents, this is the root
ProxySimple walk = this;
while (walk.GetParent() != null)
{
walk = walk.GetParent();
}
return walk as IRawElementProviderFragmentRoot;
}
}
// Returns the Run Time Id, an array of ints as the concatenation of IDs.
int [] IRawElementProviderFragment.GetRuntimeId ()
{
//ProxySimple.GetRuntimeId ();
return GetRuntimeId ();
}
// Returns a pattern interface if supported.
object IRawElementProviderSimple.GetPatternProvider(int patternId)
{
AutomationPattern iid = AutomationPattern.LookupById(patternId);
return GetPatternProvider(iid);
}
// Returns a given property
// UIAutomation as a generic call for all the properties for all the patterns.
// This routine splits properties per pattern and calls the appropriate routine
// within a pattern.
// A default implementation is provided for some properties
object IRawElementProviderSimple.GetPropertyValue(int propertyId)
{
AutomationProperty idProp = AutomationProperty.LookupById(propertyId);
return GetElementProperty(idProp);
}
// If this UI is capable of hosting other UI that also supports UIAutomation,
// and the subtree rooted at this element contains such hosted UI fragments,
// this should return an array of those fragments.
//
// If this UI does not host other UI, it may return null.
IRawElementProviderSimple[] IRawElementProviderFragment.GetEmbeddedFragmentRoots()
{
return GetEmbeddedFragmentRoots();
}
// Request that focus is set to this item.
// The UIAutomation framework will ensure that the UI hosting this fragment
// is already focused before calling this method, so this method should only
// update its internal focus state; it should not attempt to give its own
// HWND the focus, for example.
void IRawElementProviderFragment.SetFocus()
{
// Make sure that the control is enabled
if (!SafeNativeMethods.IsWindowEnabled(_hwnd))
{
throw new ElementNotEnabledException();
}
// A number of the Override Proxies return null from the GetElementProperty() method. If
// a SetFocus() was called on them, the case to bool will cause a NullReferenceException.
// So make sure the return is of type bool before casting.
bool isKeyboardFocusable = true;
object isKeyboardFocusableProperty = GetElementProperty(AutomationElement.IsKeyboardFocusableProperty);
if (isKeyboardFocusableProperty is bool)
{
isKeyboardFocusable = (bool)isKeyboardFocusableProperty;
}
// UIAutomation already focuses the containing HWND for us, so only need to
// set focus on the item within that...
if (isKeyboardFocusable)
{
// Then set the focus on this item (virtual methods)
SetFocus();
return;
}
throw new InvalidOperationException(SR.Get(SRID.SetFocusFailed));
}
#endregion
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
// Returns the clickable point on the element
// In the case when clickable point is obtained - method returns true
// In the case when clickable point cannot be obtained - method returns false
internal bool GetClickablePoint(out NativeMethods.Win32Point pt, bool fClipClientRect)
{
NativeMethods.Win32Rect rcItem = new NativeMethods.Win32Rect(BoundingRectangle);
// Intersect the bounding Rectangle with the client rectangle for framents
// and simple items - use the override flag (used mostly for the non client area
if (fClipClientRect && !_fNonClientAreaElement)
{
NativeMethods.Win32Rect rcOutside = new NativeMethods.Win32Rect();
Misc.GetClientRectInScreenCoordinates(_hwnd, ref rcOutside);
if (!Misc.IntersectRect(ref rcItem, ref rcOutside, ref rcItem))
{
pt.x = pt.y = 0;
return false;
}
}
ArrayList alIn = new ArrayList(100);
ArrayList alOut = new ArrayList(100);
// Get the mid point to start with
pt.x = (rcItem.right - 1 + rcItem.left) / 2;
pt.y = (rcItem.bottom - 1 + rcItem.top) / 2;
alOut.Add(new ClickablePoint.CPRect(ref rcItem, true));
// First go through all the children to exclude whatever is on top
ProxyFragment proxyFrag = this as ProxyFragment;
if (proxyFrag != null)
{
ClickablePoint.ExcludeChildren(proxyFrag, alIn, alOut);
}
return ClickablePoint.GetPoint(_hwnd, alIn, alOut, ref pt);
}
internal string GetAccessibleName(int item)
{
string name = null;
IAccessible acc = AccessibleObject;
if (acc != null)
{
name = acc.get_accName(item);
name = string.IsNullOrEmpty(name) ? null : name;
}
return name;
}
#endregion
// ------------------------------------------------------
//
// Internal Properties
//
// ------------------------------------------------------
#region Internal Properties
// Returns the IAccessible interface for the container object
internal virtual IAccessible AccessibleObject
{
get
{
if (_IAccessible == null)
{
Accessible acc = null;
// We need to go search for it
_IAccessible = Accessible.AccessibleObjectFromWindow(_hwnd, NativeMethods.OBJID_CLIENT, ref acc) == NativeMethods.S_OK ? acc.IAccessible : null;
}
return _IAccessible;
}
set
{
_IAccessible = value;
}
}
// Get the hwnd for this element
internal IntPtr WindowHandle
{
get
{
return _hwnd;
}
}
// Reference to the window Handle
internal int WindowStyle
{
get
{
return Misc.GetWindowStyle(_hwnd);
}
}
//Gets the extended style of the window
internal int WindowExStyle
{
get
{
return Misc.GetWindowExStyle(_hwnd);
}
}
#endregion
// ------------------------------------------------------
//
// Internal Fields
//
// ------------------------------------------------------
#region Internal Fields
// Reference to the window Handle
internal IntPtr _hwnd;
// Is used to discriminate between items in a collection.
internal int _item;
// Parent of a subtree.
internal ProxyFragment _parent;
// Localized Control type name. If the control has a ControlType this should not be set.
internal string _sType;
// Must be set by a subclass, used to return the automation id
internal string _sAutomationId = "";
// Used by the IsFocussable Property.
// By default all elements are not Keyboard focusable, overide this flag
// to change the default behavior.
internal bool _fIsKeyboardFocusable;
// Top level Desktop window
internal static IntPtr _hwndDesktop = UnsafeNativeMethods.GetDesktopWindow();
// Identifies an element as hwnd-based; used as the first value in RuntimeId for Win32 providers.
internal const int Win32ProviderRuntimeIdBase = 1;
#endregion
// ------------------------------------------------------
//
// Protected Methods
//
// ------------------------------------------------------
#region Protected Methods
// This routine is only called on elements belonging to an hwnd
// that has the focus.
// Overload this routine for sub elements within an hwnd that can
// have the focus, tab items, listbox items ...
// The default implemention is to return true for proxy element
// that are hwnd.
protected virtual bool IsFocused ()
{
return this is ProxyHwnd;
}
protected bool IsHwndElement()
{
return this is ProxyHwnd;
}
#endregion
// ------------------------------------------------------
//
// Protected Fields
//
// ------------------------------------------------------
#region Protected Fields
// True if this is a WindowsForms control.
// This value is cached and calculated only when needed
protected WindowsFormsHelper.FormControlState _windowsForms = WindowsFormsHelper.FormControlState.Undeterminate;
// Which Controltype it is, Must be set by a subclass
protected ControlType _cControlType;
// Must be set by a subclass,
// Prevents the generic generation of the persistent IDs
protected bool _fHasPersistentID = true;
// Used by the GetClickablePoint Logic to figure out if clipping
// must happen on the Client Rect or the Non ClientRect
protected bool _fNonClientAreaElement;
// true if the parent is of type ProxyFragment
protected bool _fSubTree;
// Tells whether then control is Content or Peripheral
protected bool _fIsContent = true;
// The IAccessible interface associated with this node
protected IAccessible _IAccessible;
#endregion
}
}
| |
namespace CS461_Access_Control
{
partial class frmMain
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmMain));
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.tsslStatus = new System.Windows.Forms.ToolStripStatusLabel();
this.tsslReadPause = new System.Windows.Forms.ToolStripStatusLabel();
this.tsslClock = new System.Windows.Forms.ToolStripStatusLabel();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.settingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pbLogo = new System.Windows.Forms.PictureBox();
this.tmrTimeout = new System.Windows.Forms.Timer(this.components);
this.tmrClock = new System.Windows.Forms.Timer(this.components);
this.picPhoto = new System.Windows.Forms.PictureBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.txtName = new System.Windows.Forms.TextBox();
this.txtTitle = new System.Windows.Forms.TextBox();
this.txtID = new System.Windows.Forms.TextBox();
this.btnRead = new System.Windows.Forms.Button();
this.label4 = new System.Windows.Forms.Label();
this.txtTime = new System.Windows.Forms.TextBox();
this.txtCompany = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.txtLocation = new System.Windows.Forms.TextBox();
this.btnAccessLog = new System.Windows.Forms.Button();
this.statusStrip1.SuspendLayout();
this.menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pbLogo)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.picPhoto)).BeginInit();
this.SuspendLayout();
//
// statusStrip1
//
this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsslStatus,
this.tsslReadPause,
this.tsslClock});
this.statusStrip1.Location = new System.Drawing.Point(0, 503);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.Size = new System.Drawing.Size(789, 24);
this.statusStrip1.TabIndex = 0;
this.statusStrip1.Text = "statusStrip1";
//
// tsslStatus
//
this.tsslStatus.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.tsslStatus.Name = "tsslStatus";
this.tsslStatus.Size = new System.Drawing.Size(666, 19);
this.tsslStatus.Spring = true;
this.tsslStatus.Text = "Ready...";
this.tsslStatus.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// tsslReadPause
//
this.tsslReadPause.BackColor = System.Drawing.Color.Red;
this.tsslReadPause.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.tsslReadPause.Name = "tsslReadPause";
this.tsslReadPause.Size = new System.Drawing.Size(57, 19);
this.tsslReadPause.Text = "Pause";
//
// tsslClock
//
this.tsslClock.Name = "tsslClock";
this.tsslClock.Size = new System.Drawing.Size(51, 19);
this.tsslClock.Text = "00:00:00";
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.settingsToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(789, 24);
this.menuStrip1.TabIndex = 1;
this.menuStrip1.Text = "menuStrip1";
//
// settingsToolStripMenuItem
//
this.settingsToolStripMenuItem.Name = "settingsToolStripMenuItem";
this.settingsToolStripMenuItem.Size = new System.Drawing.Size(58, 20);
this.settingsToolStripMenuItem.Text = "Settings";
this.settingsToolStripMenuItem.Click += new System.EventHandler(this.settingsToolStripMenuItem_Click);
//
// pbLogo
//
this.pbLogo.Image = ((System.Drawing.Image)(resources.GetObject("pbLogo.Image")));
this.pbLogo.InitialImage = ((System.Drawing.Image)(resources.GetObject("pbLogo.InitialImage")));
this.pbLogo.Location = new System.Drawing.Point(0, 25);
this.pbLogo.Name = "pbLogo";
this.pbLogo.Size = new System.Drawing.Size(266, 100);
this.pbLogo.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pbLogo.TabIndex = 3;
this.pbLogo.TabStop = false;
//
// tmrTimeout
//
this.tmrTimeout.Interval = 5000;
this.tmrTimeout.Tick += new System.EventHandler(this.tmrTimeout_Tick);
//
// tmrClock
//
this.tmrClock.Interval = 30000;
this.tmrClock.Tick += new System.EventHandler(this.tmrClock_Tick);
//
// picPhoto
//
this.picPhoto.Location = new System.Drawing.Point(0, 131);
this.picPhoto.Name = "picPhoto";
this.picPhoto.Size = new System.Drawing.Size(265, 364);
this.picPhoto.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.picPhoto.TabIndex = 5;
this.picPhoto.TabStop = false;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(293, 160);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(68, 25);
this.label1.TabIndex = 6;
this.label1.Text = "Name";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(293, 224);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(53, 25);
this.label2.TabIndex = 7;
this.label2.Text = "Title";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(293, 287);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(32, 25);
this.label3.TabIndex = 8;
this.label3.Text = "ID";
//
// txtName
//
this.txtName.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtName.Location = new System.Drawing.Point(371, 157);
this.txtName.Name = "txtName";
this.txtName.Size = new System.Drawing.Size(406, 31);
this.txtName.TabIndex = 9;
//
// txtTitle
//
this.txtTitle.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtTitle.Location = new System.Drawing.Point(371, 221);
this.txtTitle.Name = "txtTitle";
this.txtTitle.Size = new System.Drawing.Size(406, 31);
this.txtTitle.TabIndex = 10;
//
// txtID
//
this.txtID.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtID.Location = new System.Drawing.Point(371, 284);
this.txtID.Name = "txtID";
this.txtID.Size = new System.Drawing.Size(406, 31);
this.txtID.TabIndex = 11;
//
// btnRead
//
this.btnRead.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnRead.Location = new System.Drawing.Point(679, 0);
this.btnRead.Name = "btnRead";
this.btnRead.Size = new System.Drawing.Size(110, 24);
this.btnRead.TabIndex = 2;
this.btnRead.Text = "Start";
this.btnRead.UseVisualStyleBackColor = true;
this.btnRead.Click += new System.EventHandler(this.btnRead_Click);
//
// label4
//
this.label4.AutoSize = true;
this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.Location = new System.Drawing.Point(293, 351);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(135, 25);
this.label4.TabIndex = 12;
this.label4.Text = "Access Time";
//
// txtTime
//
this.txtTime.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtTime.Location = new System.Drawing.Point(434, 348);
this.txtTime.Name = "txtTime";
this.txtTime.Size = new System.Drawing.Size(265, 31);
this.txtTime.TabIndex = 13;
//
// txtCompany
//
this.txtCompany.Font = new System.Drawing.Font("Microsoft Sans Serif", 24F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtCompany.Location = new System.Drawing.Point(298, 54);
this.txtCompany.Name = "txtCompany";
this.txtCompany.Size = new System.Drawing.Size(479, 44);
this.txtCompany.TabIndex = 14;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label5.Location = new System.Drawing.Point(293, 419);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(94, 25);
this.label5.TabIndex = 15;
this.label5.Text = "Location";
//
// txtLocation
//
this.txtLocation.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtLocation.Location = new System.Drawing.Point(434, 416);
this.txtLocation.Multiline = true;
this.txtLocation.Name = "txtLocation";
this.txtLocation.Size = new System.Drawing.Size(343, 79);
this.txtLocation.TabIndex = 16;
//
// btnAccessLog
//
this.btnAccessLog.Enabled = false;
this.btnAccessLog.Location = new System.Drawing.Point(705, 348);
this.btnAccessLog.Name = "btnAccessLog";
this.btnAccessLog.Size = new System.Drawing.Size(72, 31);
this.btnAccessLog.TabIndex = 17;
this.btnAccessLog.Text = "Access Log";
this.btnAccessLog.UseVisualStyleBackColor = true;
this.btnAccessLog.Click += new System.EventHandler(this.btnAccessLog_Click);
//
// frmMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(789, 527);
this.Controls.Add(this.btnAccessLog);
this.Controls.Add(this.txtLocation);
this.Controls.Add(this.label5);
this.Controls.Add(this.txtCompany);
this.Controls.Add(this.txtTime);
this.Controls.Add(this.label4);
this.Controls.Add(this.btnRead);
this.Controls.Add(this.txtID);
this.Controls.Add(this.txtTitle);
this.Controls.Add(this.txtName);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.picPhoto);
this.Controls.Add(this.pbLogo);
this.Controls.Add(this.statusStrip1);
this.Controls.Add(this.menuStrip1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
this.MainMenuStrip = this.menuStrip1;
this.MaximizeBox = false;
this.Name = "frmMain";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "CS461 Access Control";
this.Resize += new System.EventHandler(this.frmMain_Resize);
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.frmMain_FormClosing);
this.Load += new System.EventHandler(this.frmMain_Load);
this.statusStrip1.ResumeLayout(false);
this.statusStrip1.PerformLayout();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pbLogo)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.picPhoto)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.StatusStrip statusStrip1;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.PictureBox pbLogo;
private System.Windows.Forms.ToolStripStatusLabel tsslStatus;
private System.Windows.Forms.ToolStripStatusLabel tsslClock;
private System.Windows.Forms.Timer tmrTimeout;
private System.Windows.Forms.Timer tmrClock;
private System.Windows.Forms.ToolStripMenuItem settingsToolStripMenuItem;
private System.Windows.Forms.ToolStripStatusLabel tsslReadPause;
private System.Windows.Forms.PictureBox picPhoto;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox txtName;
private System.Windows.Forms.TextBox txtTitle;
private System.Windows.Forms.TextBox txtID;
private System.Windows.Forms.Button btnRead;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox txtTime;
private System.Windows.Forms.TextBox txtCompany;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.TextBox txtLocation;
private System.Windows.Forms.Button btnAccessLog;
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Serialization;
using OpenSim.Services.Interfaces;
using OpenSim.Services.Connectors.Simulation;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "RemoteSimulationConnectorModule")]
public class RemoteSimulationConnectorModule : ISharedRegionModule, ISimulationService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool initialized = false;
protected bool m_enabled = false;
protected Scene m_aScene;
// RemoteSimulationConnector does not care about local regions; it delegates that to the Local module
protected LocalSimulationConnectorModule m_localBackend;
protected SimulationServiceConnector m_remoteConnector;
protected bool m_safemode;
#region Region Module interface
public virtual void Initialise(IConfigSource configSource)
{
IConfig moduleConfig = configSource.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("SimulationServices", "");
if (name == Name)
{
m_localBackend = new LocalSimulationConnectorModule();
m_localBackend.InitialiseService(configSource);
m_remoteConnector = new SimulationServiceConnector();
m_enabled = true;
m_log.Info("[REMOTE SIMULATION CONNECTOR]: Remote simulation enabled.");
}
}
}
public virtual void PostInitialise()
{
}
public virtual void Close()
{
}
public void AddRegion(Scene scene)
{
if (!m_enabled)
return;
if (!initialized)
{
InitOnce(scene);
initialized = true;
}
InitEach(scene);
}
public void RemoveRegion(Scene scene)
{
if (m_enabled)
{
m_localBackend.RemoveScene(scene);
scene.UnregisterModuleInterface<ISimulationService>(this);
}
}
public void RegionLoaded(Scene scene)
{
if (!m_enabled)
return;
}
public Type ReplaceableInterface
{
get { return null; }
}
public virtual string Name
{
get { return "RemoteSimulationConnectorModule"; }
}
protected virtual void InitEach(Scene scene)
{
m_localBackend.Init(scene);
scene.RegisterModuleInterface<ISimulationService>(this);
}
protected virtual void InitOnce(Scene scene)
{
m_aScene = scene;
//m_regionClient = new RegionToRegionClient(m_aScene, m_hyperlinkService);
}
#endregion
#region ISimulationService
public IScene GetScene(UUID regionId)
{
return m_localBackend.GetScene(regionId);
}
public ISimulationService GetInnerService()
{
return m_localBackend;
}
/**
* Agent-related communications
*/
public bool CreateAgent(GridRegion source, GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, out string reason)
{
if (destination == null)
{
reason = "Given destination was null";
m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: CreateAgent was given a null destination");
return false;
}
// Try local first
if (m_localBackend.CreateAgent(source, destination, aCircuit, teleportFlags, out reason))
return true;
// else do the remote thing
if (!m_localBackend.IsLocalRegion(destination.RegionID))
{
return m_remoteConnector.CreateAgent(source, destination, aCircuit, teleportFlags, out reason);
}
return false;
}
public bool UpdateAgent(GridRegion destination, AgentData cAgentData)
{
if (destination == null)
return false;
// Try local first
if (m_localBackend.IsLocalRegion(destination.RegionID))
return m_localBackend.UpdateAgent(destination, cAgentData);
return m_remoteConnector.UpdateAgent(destination, cAgentData);
}
public bool UpdateAgent(GridRegion destination, AgentPosition cAgentData)
{
if (destination == null)
return false;
// Try local first
if (m_localBackend.IsLocalRegion(destination.RegionID))
return m_localBackend.UpdateAgent(destination, cAgentData);
return m_remoteConnector.UpdateAgent(destination, cAgentData);
}
public bool QueryAccess(GridRegion destination, UUID agentID, string agentHomeURI, bool viaTeleport, Vector3 position, string sversion, out string version, out string reason)
{
reason = "Communications failure";
version = "Unknown";
if (destination == null)
return false;
// Try local first
if (m_localBackend.QueryAccess(destination, agentID, agentHomeURI, viaTeleport, position, sversion, out version, out reason))
return true;
// else do the remote thing
if (!m_localBackend.IsLocalRegion(destination.RegionID))
return m_remoteConnector.QueryAccess(destination, agentID, agentHomeURI, viaTeleport, position, sversion, out version, out reason);
return false;
}
public bool ReleaseAgent(UUID origin, UUID id, string uri)
{
// Try local first
if (m_localBackend.ReleaseAgent(origin, id, uri))
return true;
// else do the remote thing
if (!m_localBackend.IsLocalRegion(origin))
return m_remoteConnector.ReleaseAgent(origin, id, uri);
return false;
}
public bool CloseAgent(GridRegion destination, UUID id, string auth_token)
{
if (destination == null)
return false;
// Try local first
if (m_localBackend.CloseAgent(destination, id, auth_token))
return true;
// else do the remote thing
if (!m_localBackend.IsLocalRegion(destination.RegionID))
return m_remoteConnector.CloseAgent(destination, id, auth_token);
return false;
}
/**
* Object-related communications
*/
public bool CreateObject(GridRegion destination, Vector3 newPosition, ISceneObject sog, bool isLocalCall)
{
if (destination == null)
return false;
// Try local first
if (m_localBackend.CreateObject(destination, newPosition, sog, isLocalCall))
{
//m_log.Debug("[REST COMMS]: LocalBackEnd SendCreateObject succeeded");
return true;
}
// else do the remote thing
if (!m_localBackend.IsLocalRegion(destination.RegionID))
return m_remoteConnector.CreateObject(destination, newPosition, sog, isLocalCall);
return false;
}
#endregion
}
}
| |
using Lucene.Net.Index;
using Lucene.Net.Store;
using Lucene.Net.Support;
using Lucene.Net.Util;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace Lucene.Net.Codecs.Pulsing
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Concrete class that reads the current doc/freq/skip postings format.
/// <para/>
/// @lucene.experimental
/// </summary>
// TODO: -- should we switch "hasProx" higher up? and
// create two separate docs readers, one that also reads
// prox and one that doesn't?
public class PulsingPostingsReader : PostingsReaderBase
{
// Fallback reader for non-pulsed terms:
private readonly PostingsReaderBase _wrappedPostingsReader;
private readonly SegmentReadState _segmentState;
private int _maxPositions;
private int _version;
private SortedDictionary<int, int> _fields;
public PulsingPostingsReader(SegmentReadState state, PostingsReaderBase wrappedPostingsReader)
{
_wrappedPostingsReader = wrappedPostingsReader;
_segmentState = state;
}
public override void Init(IndexInput termsIn)
{
_version = CodecUtil.CheckHeader(termsIn, PulsingPostingsWriter.CODEC,
PulsingPostingsWriter.VERSION_START,
PulsingPostingsWriter.VERSION_CURRENT);
_maxPositions = termsIn.ReadVInt32();
_wrappedPostingsReader.Init(termsIn);
if (_wrappedPostingsReader is PulsingPostingsReader || _version < PulsingPostingsWriter.VERSION_META_ARRAY)
{
_fields = null;
}
else
{
_fields = new SortedDictionary<int, int>();
var summaryFileName = IndexFileNames.SegmentFileName(_segmentState.SegmentInfo.Name,
_segmentState.SegmentSuffix, PulsingPostingsWriter.SUMMARY_EXTENSION);
IndexInput input = null;
try
{
input =
_segmentState.Directory.OpenInput(summaryFileName, _segmentState.Context);
CodecUtil.CheckHeader(input,
PulsingPostingsWriter.CODEC,
_version,
PulsingPostingsWriter.VERSION_CURRENT);
var numField = input.ReadVInt32();
for (var i = 0; i < numField; i++)
{
var fieldNum = input.ReadVInt32();
var longsSize = input.ReadVInt32();
_fields.Add(fieldNum, longsSize);
}
}
finally
{
IOUtils.DisposeWhileHandlingException(input);
}
}
}
internal class PulsingTermState : BlockTermState
{
internal bool Absolute { get; set; }
/// <summary>
/// NOTE: This was longs (field) in Lucene
/// </summary>
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
internal long[] Int64s { get; set; }
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
internal byte[] Postings { get; set; }
internal int PostingsSize { get; set; } // -1 if this term was not inlined
internal BlockTermState WrappedTermState { get; set; }
public override object Clone()
{
var clone = (PulsingTermState)base.Clone();
if (PostingsSize != -1)
{
clone.Postings = new byte[PostingsSize];
Array.Copy(Postings, 0, clone.Postings, 0, PostingsSize);
}
else
{
Debug.Assert(WrappedTermState != null);
clone.WrappedTermState = (BlockTermState)WrappedTermState.Clone();
clone.Absolute = Absolute;
if (Int64s == null) return clone;
clone.Int64s = new long[Int64s.Length];
Array.Copy(Int64s, 0, clone.Int64s, 0, Int64s.Length);
}
return clone;
}
public override void CopyFrom(TermState other)
{
base.CopyFrom(other);
var _other = (PulsingTermState)other;
PostingsSize = _other.PostingsSize;
if (_other.PostingsSize != -1)
{
if (Postings == null || Postings.Length < _other.PostingsSize)
{
Postings = new byte[ArrayUtil.Oversize(_other.PostingsSize, 1)];
}
Array.Copy(_other.Postings, 0, Postings, 0, _other.PostingsSize);
}
else
{
WrappedTermState.CopyFrom(_other.WrappedTermState);
}
}
public override string ToString()
{
if (PostingsSize == -1)
return "PulsingTermState: not inlined: wrapped=" + WrappedTermState;
return "PulsingTermState: inlined size=" + PostingsSize + " " + base.ToString();
}
}
public override BlockTermState NewTermState()
{
return new PulsingTermState {WrappedTermState = _wrappedPostingsReader.NewTermState()};
}
public override void DecodeTerm(long[] empty, DataInput input, FieldInfo fieldInfo, BlockTermState termState,
bool absolute)
{
var termState2 = (PulsingTermState) termState;
Debug.Assert(empty.Length == 0);
termState2.Absolute = termState2.Absolute || absolute;
// if we have positions, its total TF, otherwise its computed based on docFreq.
// TODO Double check this is right..
long count = fieldInfo.IndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0
? termState2.TotalTermFreq
: termState2.DocFreq;
if (count <= _maxPositions)
{
// Inlined into terms dict -- just read the byte[] blob in,
// but don't decode it now (we only decode when a DocsEnum
// or D&PEnum is pulled):
termState2.PostingsSize = input.ReadVInt32();
if (termState2.Postings == null || termState2.Postings.Length < termState2.PostingsSize)
{
termState2.Postings = new byte[ArrayUtil.Oversize(termState2.PostingsSize, 1)];
}
// TODO: sort of silly to copy from one big byte[]
// (the blob holding all inlined terms' blobs for
// current term block) into another byte[] (just the
// blob for this term)...
input.ReadBytes(termState2.Postings, 0, termState2.PostingsSize);
//System.out.println(" inlined bytes=" + termState.postingsSize);
termState2.Absolute = termState2.Absolute || absolute;
}
else
{
//System.out.println(" not inlined");
var longsSize = _fields == null ? 0 : _fields[fieldInfo.Number];
if (termState2.Int64s == null)
{
termState2.Int64s = new long[longsSize];
}
for (var i = 0; i < longsSize; i++)
{
termState2.Int64s[i] = input.ReadVInt64();
}
termState2.PostingsSize = -1;
termState2.WrappedTermState.DocFreq = termState2.DocFreq;
termState2.WrappedTermState.TotalTermFreq = termState2.TotalTermFreq;
_wrappedPostingsReader.DecodeTerm(termState2.Int64s, input, fieldInfo,
termState2.WrappedTermState,
termState2.Absolute);
termState2.Absolute = false;
}
}
public override DocsEnum Docs(FieldInfo field, BlockTermState termState, IBits liveDocs, DocsEnum reuse,
DocsFlags flags)
{
var termState2 = (PulsingTermState) termState;
if (termState2.PostingsSize != -1)
{
PulsingDocsEnum postings;
if (reuse is PulsingDocsEnum)
{
postings = (PulsingDocsEnum) reuse;
if (!postings.CanReuse(field))
{
postings = new PulsingDocsEnum(field);
}
}
else
{
// the 'reuse' is actually the wrapped enum
var previous = (PulsingDocsEnum) GetOther(reuse);
if (previous != null && previous.CanReuse(field))
{
postings = previous;
}
else
{
postings = new PulsingDocsEnum(field);
}
}
if (reuse != postings)
SetOther(postings, reuse); // postings.other = reuse
return postings.Reset(liveDocs, termState2);
}
if (!(reuse is PulsingDocsEnum))
return _wrappedPostingsReader.Docs(field, termState2.WrappedTermState, liveDocs, reuse, flags);
var wrapped = _wrappedPostingsReader.Docs(field, termState2.WrappedTermState, liveDocs,
GetOther(reuse), flags);
SetOther(wrapped, reuse); // wrapped.other = reuse
return wrapped;
}
public override DocsAndPositionsEnum DocsAndPositions(FieldInfo field, BlockTermState termState, IBits liveDocs,
DocsAndPositionsEnum reuse,
DocsAndPositionsFlags flags)
{
var termState2 = (PulsingTermState) termState;
if (termState2.PostingsSize != -1)
{
PulsingDocsAndPositionsEnum postings;
if (reuse is PulsingDocsAndPositionsEnum)
{
postings = (PulsingDocsAndPositionsEnum) reuse;
if (!postings.CanReuse(field))
{
postings = new PulsingDocsAndPositionsEnum(field);
}
}
else
{
// the 'reuse' is actually the wrapped enum
var previous = (PulsingDocsAndPositionsEnum) GetOther(reuse);
if (previous != null && previous.CanReuse(field))
{
postings = previous;
}
else
{
postings = new PulsingDocsAndPositionsEnum(field);
}
}
if (reuse != postings)
{
SetOther(postings, reuse); // postings.other = reuse
}
return postings.Reset(liveDocs, termState2);
}
if (!(reuse is PulsingDocsAndPositionsEnum))
return _wrappedPostingsReader.DocsAndPositions(field, termState2.WrappedTermState, liveDocs, reuse,
flags);
var wrapped = _wrappedPostingsReader.DocsAndPositions(field,
termState2.WrappedTermState,
liveDocs, (DocsAndPositionsEnum) GetOther(reuse),
flags);
SetOther(wrapped, reuse); // wrapped.other = reuse
return wrapped;
}
private class PulsingDocsEnum : DocsEnum
{
private byte[] _postingsBytes;
private readonly ByteArrayDataInput _postings = new ByteArrayDataInput();
private readonly IndexOptions _indexOptions;
private readonly bool _storePayloads;
private readonly bool _storeOffsets;
private IBits _liveDocs;
private int _docId = -1;
private int _accum;
private int _freq;
private int _payloadLength;
private int _cost;
public PulsingDocsEnum(FieldInfo fieldInfo)
{
_indexOptions = fieldInfo.IndexOptions;
_storePayloads = fieldInfo.HasPayloads;
_storeOffsets = _indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
}
public virtual PulsingDocsEnum Reset(IBits liveDocs, PulsingTermState termState)
{
Debug.Assert(termState.PostingsSize != -1);
// Must make a copy of termState's byte[] so that if
// app does TermsEnum.next(), this DocsEnum is not affected
if (_postingsBytes == null)
{
_postingsBytes = new byte[termState.PostingsSize];
}
else if (_postingsBytes.Length < termState.PostingsSize)
{
_postingsBytes = ArrayUtil.Grow(_postingsBytes, termState.PostingsSize);
}
System.Array.Copy(termState.Postings, 0, _postingsBytes, 0, termState.PostingsSize);
_postings.Reset(_postingsBytes, 0, termState.PostingsSize);
_docId = -1;
_accum = 0;
_freq = 1;
_cost = termState.DocFreq;
_payloadLength = 0;
this._liveDocs = liveDocs;
return this;
}
internal bool CanReuse(FieldInfo fieldInfo)
{
return _indexOptions == fieldInfo.IndexOptions && _storePayloads == fieldInfo.HasPayloads;
}
public override int NextDoc()
{
while (true)
{
if (_postings.Eof)
return _docId = NO_MORE_DOCS;
var code = _postings.ReadVInt32();
if (_indexOptions == IndexOptions.DOCS_ONLY)
{
_accum += code;
}
else
{
_accum += (int)((uint)code >> 1); ; // shift off low bit
_freq = (code & 1) != 0 ? 1 : _postings.ReadVInt32();
if (_indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0)
{
// Skip positions
if (_storePayloads)
{
for (var pos = 0; pos < _freq; pos++)
{
var posCode = _postings.ReadVInt32();
if ((posCode & 1) != 0)
{
_payloadLength = _postings.ReadVInt32();
}
if (_storeOffsets && (_postings.ReadVInt32() & 1) != 0)
{
// new offset length
_postings.ReadVInt32();
}
if (_payloadLength != 0)
{
_postings.SkipBytes(_payloadLength);
}
}
}
else
{
for (var pos = 0; pos < _freq; pos++)
{
// TODO: skipVInt
_postings.ReadVInt32();
if (_storeOffsets && (_postings.ReadVInt32() & 1) != 0)
{
// new offset length
_postings.ReadVInt32();
}
}
}
}
}
if (_liveDocs == null || _liveDocs.Get(_accum))
return (_docId = _accum);
}
}
public override int Freq
{
get { return _freq; }
}
public override int DocID
{
get { return _docId; }
}
public override int Advance(int target)
{
return _docId = SlowAdvance(target);
}
public override long GetCost()
{
return _cost;
}
}
private class PulsingDocsAndPositionsEnum : DocsAndPositionsEnum
{
private byte[] _postingsBytes;
private readonly ByteArrayDataInput _postings = new ByteArrayDataInput();
private readonly bool _storePayloads;
private readonly bool _storeOffsets;
// note: we could actually reuse across different options, if we passed this to reset()
// and re-init'ed storeOffsets accordingly (made it non-final)
private readonly IndexOptions _indexOptions;
private IBits _liveDocs;
private int _docId = -1;
private int _accum;
private int _freq;
private int _posPending;
private int _position;
private int _payloadLength;
private BytesRef _payload;
private int _startOffset;
private int _offsetLength;
private bool _payloadRetrieved;
private int _cost;
public PulsingDocsAndPositionsEnum(FieldInfo fieldInfo)
{
_indexOptions = fieldInfo.IndexOptions;
_storePayloads = fieldInfo.HasPayloads;
_storeOffsets = _indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
}
internal bool CanReuse(FieldInfo fieldInfo)
{
return _indexOptions == fieldInfo.IndexOptions && _storePayloads == fieldInfo.HasPayloads;
}
public virtual PulsingDocsAndPositionsEnum Reset(IBits liveDocs, PulsingTermState termState)
{
Debug.Assert(termState.PostingsSize != -1);
if (_postingsBytes == null)
{
_postingsBytes = new byte[termState.PostingsSize];
}
else if (_postingsBytes.Length < termState.PostingsSize)
{
_postingsBytes = ArrayUtil.Grow(_postingsBytes, termState.PostingsSize);
}
Array.Copy(termState.Postings, 0, _postingsBytes, 0, termState.PostingsSize);
_postings.Reset(_postingsBytes, 0, termState.PostingsSize);
this._liveDocs = liveDocs;
_payloadLength = 0;
_posPending = 0;
_docId = -1;
_accum = 0;
_cost = termState.DocFreq;
_startOffset = _storeOffsets ? 0 : -1; // always return -1 if no offsets are stored
_offsetLength = 0;
//System.out.println("PR d&p reset storesPayloads=" + storePayloads + " bytes=" + bytes.length + " this=" + this);
return this;
}
public override int NextDoc()
{
while (true)
{
SkipPositions();
if (_postings.Eof)
{
return _docId = NO_MORE_DOCS;
}
var code = _postings.ReadVInt32();
_accum += (int)((uint)code >> 1); // shift off low bit
_freq = (code & 1) != 0 ? 1 : _postings.ReadVInt32();
_posPending = _freq;
_startOffset = _storeOffsets ? 0 : -1; // always return -1 if no offsets are stored
if (_liveDocs != null && !_liveDocs.Get(_accum)) continue;
_position = 0;
return (_docId = _accum);
}
}
public override int Freq
{
get { return _freq; }
}
public override int DocID
{
get { return _docId; }
}
public override int Advance(int target)
{
return _docId = SlowAdvance(target);
}
public override int NextPosition()
{
Debug.Assert(_posPending > 0);
_posPending--;
if (_storePayloads)
{
if (!_payloadRetrieved)
{
_postings.SkipBytes(_payloadLength);
}
int code = _postings.ReadVInt32();
if ((code & 1) != 0)
{
_payloadLength = _postings.ReadVInt32();
}
_position += (int)((uint)code >> 1);
_payloadRetrieved = false;
}
else
{
_position += _postings.ReadVInt32();
}
if (_storeOffsets)
{
int offsetCode = _postings.ReadVInt32();
if ((offsetCode & 1) != 0)
{
// new offset length
_offsetLength = _postings.ReadVInt32();
}
_startOffset += (int)((uint)offsetCode >> 1);
}
return _position;
}
public override int StartOffset
{
get { return _startOffset; }
}
public override int EndOffset
{
get { return _startOffset + _offsetLength; }
}
private void SkipPositions()
{
while (_posPending != 0)
{
NextPosition();
}
if (_storePayloads && !_payloadRetrieved)
{
_postings.SkipBytes(_payloadLength);
_payloadRetrieved = true;
}
}
public override BytesRef GetPayload()
{
if (_payloadRetrieved)
return _payload;
if (_storePayloads && _payloadLength > 0)
{
_payloadRetrieved = true;
if (_payload == null)
{
_payload = new BytesRef(_payloadLength);
}
else
{
_payload.Grow(_payloadLength);
}
_postings.ReadBytes(_payload.Bytes, 0, _payloadLength);
_payload.Length = _payloadLength;
return _payload;
}
return null;
}
public override long GetCost()
{
return _cost;
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_wrappedPostingsReader.Dispose();
}
}
/// <summary>
/// For a docsenum, gets the 'other' reused enum.
/// Example: Pulsing(Standard).
/// When doing a term range query you are switching back and forth
/// between Pulsing and Standard.
/// <para/>
/// The way the reuse works is that Pulsing.other = Standard and
/// Standard.other = Pulsing.
/// </summary>
private DocsEnum GetOther(DocsEnum de)
{
if (de == null)
return null;
var atts = de.Attributes;
DocsEnum result;
atts.AddAttribute<IPulsingEnumAttribute>().Enums.TryGetValue(this, out result);
return result;
}
/// <summary>
/// For a docsenum, sets the 'other' reused enum.
/// see <see cref="GetOther(DocsEnum)"/> for an example.
/// </summary>
private DocsEnum SetOther(DocsEnum de, DocsEnum other)
{
var atts = de.Attributes;
return atts.AddAttribute<IPulsingEnumAttribute>().Enums[this] = other;
}
///<summary>
/// A per-docsenum attribute that stores additional reuse information
/// so that pulsing enums can keep a reference to their wrapped enums,
/// and vice versa. this way we can always reuse.
/// <para/>
/// @lucene.internal
/// </summary>
public interface IPulsingEnumAttribute : IAttribute
{
IDictionary<PulsingPostingsReader, DocsEnum> Enums { get; }
}
/// <summary>
/// Implementation of <see cref="PulsingEnumAttribute"/> for reuse of
/// wrapped postings readers underneath pulsing.
/// <para/>
/// @lucene.internal
/// </summary>
public sealed class PulsingEnumAttribute : Util.Attribute, IPulsingEnumAttribute
{
// we could store 'other', but what if someone 'chained' multiple postings readers,
// this could cause problems?
// TODO: we should consider nuking this map and just making it so if you do this,
// you don't reuse? and maybe pulsingPostingsReader should throw an exc if it wraps
// another pulsing, because this is just stupid and wasteful.
// we still have to be careful in case someone does Pulsing(Stomping(Pulsing(...
private readonly IDictionary<PulsingPostingsReader, DocsEnum> _enums = new IdentityHashMap<PulsingPostingsReader, DocsEnum>();
public IDictionary<PulsingPostingsReader, DocsEnum> Enums
{
get { return _enums; }
}
public override void Clear()
{
// our state is per-docsenum, so this makes no sense.
// its best not to clear, in case a wrapped enum has a per-doc attribute or something
// and is calling clearAttributes(), so they don't nuke the reuse information!
}
public override void CopyTo(Util.IAttribute target)
{
// this makes no sense for us, because our state is per-docsenum.
// we don't want to copy any stuff over to another docsenum ever!
}
}
public override long RamBytesUsed()
{
return ((_wrappedPostingsReader != null) ? _wrappedPostingsReader.RamBytesUsed() : 0);
}
public override void CheckIntegrity()
{
_wrappedPostingsReader.CheckIntegrity();
}
}
}
| |
#region License
//
// Author: Remo Gloor (remo.gloor@bbv.ch)
// Copyright (c) 2010, bbv Software Engineering AG.
//
// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL).
// See the file LICENSE.txt for details.
//
#endregion
namespace Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
/// <summary>
/// Extensions for MemberInfo
/// </summary>
public static class ExtensionsForMemberInfo
{
const BindingFlags DefaultFlags = BindingFlags.Public | BindingFlags.Instance;
#if !NO_LCG && !SILVERLIGHT
const BindingFlags Flags = DefaultFlags | BindingFlags.NonPublic;
#else
const BindingFlags Flags = DefaultFlags;
#endif
#if !MONO
private static MethodInfo parentDefinitionMethodInfo;
private static MethodInfo ParentDefinitionMethodInfo
{
get
{
if (parentDefinitionMethodInfo == null)
{
var runtimeAssemblyInfoType = typeof(MethodInfo).Assembly.GetType("System.Reflection.RuntimeMethodInfo");
parentDefinitionMethodInfo = runtimeAssemblyInfoType.GetMethod("GetParentDefinition", Flags);
}
return parentDefinitionMethodInfo;
}
}
#endif
/// <summary>
/// Determines whether the specified member has attribute.
/// </summary>
/// <typeparam name="T">The type of the attribute.</typeparam>
/// <param name="member">The member.</param>
/// <returns>
/// <c>true</c> if the specified member has attribute; otherwise, <c>false</c>.
/// </returns>
public static bool HasAttribute<T>(this MemberInfo member)
{
return member.HasAttribute(typeof(T));
}
/// <summary>
/// Determines whether the specified member has attribute.
/// </summary>
/// <param name="member">The member.</param>
/// <param name="type">The type of the attribute.</param>
/// <returns>
/// <c>true</c> if the specified member has attribute; otherwise, <c>false</c>.
/// </returns>
public static bool HasAttribute(this MemberInfo member, Type type)
{
var propertyInfo = member as PropertyInfo;
if (propertyInfo != null)
{
return IsDefined(propertyInfo, type, true);
}
#if NETCF
// Workaround for the CF bug that derived generic methods throw an exception for IsDefined
// This means that the Inject attribute can not be defined on base methods for CF framework
var methodInfo = member as MethodInfo;
if (methodInfo != null)
{
return methodInfo.IsDefined(type, false);
}
#endif
return member.IsDefined(type, true);
}
/// <summary>
/// Gets the property info from its declared tpe.
/// </summary>
/// <param name="memberInfo">The member info.</param>
/// <param name="propertyDefinition">The property definition.</param>
/// <param name="flags">The flags.</param>
/// <returns>The property info from the declared type of the property.</returns>
public static PropertyInfo GetPropertyFromDeclaredType(
this MemberInfo memberInfo,
PropertyInfo propertyDefinition,
BindingFlags flags)
{
return memberInfo.DeclaringType.GetProperty(
propertyDefinition.Name,
flags,
null,
propertyDefinition.PropertyType,
propertyDefinition.GetIndexParameters().Select(parameter => parameter.ParameterType).ToArray(),
null);
}
/// <summary>
/// Determines whether the specified property info is private.
/// </summary>
/// <param name="propertyInfo">The property info.</param>
/// <returns>
/// <c>true</c> if the specified property info is private; otherwise, <c>false</c>.
/// </returns>
public static bool IsPrivate(this PropertyInfo propertyInfo)
{
var getMethod = propertyInfo.GetGetMethod(true);
var setMethod = propertyInfo.GetSetMethod(true);
return (getMethod == null || getMethod.IsPrivate) && (setMethod == null || setMethod.IsPrivate);
}
/// <summary>
/// Gets the custom attributes.
/// This version is able to get custom attributes for properties from base types even if the property is none public.
/// </summary>
/// <param name="member">The member.</param>
/// <param name="attributeType">Type of the attribute.</param>
/// <param name="inherited">if set to <c>true</c> [inherited].</param>
/// <returns></returns>
public static object[] GetCustomAttributesExtended(this MemberInfo member, Type attributeType, bool inherited)
{
#if !NET_35 && !MONO_40
return Attribute.GetCustomAttributes(member, attributeType, inherited);
#else
var propertyInfo = member as PropertyInfo;
if (propertyInfo != null)
{
return GetCustomAttributes(propertyInfo, attributeType, inherited);
}
return member.GetCustomAttributes(attributeType, inherited);
#endif
}
private static PropertyInfo GetParentDefinition(PropertyInfo property)
{
var propertyMethod = property.GetGetMethod(true) ?? property.GetSetMethod(true);
if (propertyMethod != null)
{
propertyMethod = propertyMethod.GetParentDefinition(Flags);
if (propertyMethod != null)
{
return propertyMethod.GetPropertyFromDeclaredType(property, Flags);
}
}
return null;
}
private static MethodInfo GetParentDefinition(this MethodInfo method, BindingFlags flags)
{
#if MEDIUM_TRUST || MONO
var baseDefinition = method.GetBaseDefinition();
var type = method.DeclaringType.BaseType;
MethodInfo result = null;
while (result == null && type != null)
{
result = type.GetMethods(flags).Where(m => m.GetBaseDefinition().Equals(baseDefinition)).SingleOrDefault();
type = type.BaseType;
}
return result;
#else
if (ParentDefinitionMethodInfo == null)
{
return null;
}
return (MethodInfo)ParentDefinitionMethodInfo.Invoke(method, flags, null, null, CultureInfo.InvariantCulture);
#endif
}
private static bool IsDefined(PropertyInfo element, Type attributeType, bool inherit)
{
if (element.IsDefined(attributeType, inherit))
{
return true;
}
if (inherit)
{
if (!InternalGetAttributeUsage(attributeType).Inherited)
{
return false;
}
for (var info = GetParentDefinition(element);
info != null;
info = GetParentDefinition(info))
{
if (info.IsDefined(attributeType, false))
{
return true;
}
}
}
return false;
}
private static object[] GetCustomAttributes(PropertyInfo propertyInfo, Type attributeType, bool inherit)
{
if (inherit)
{
if (InternalGetAttributeUsage(attributeType).Inherited)
{
var attributeUsages = new Dictionary<Type, bool>();
var attributes = new List<object>();
attributes.AddRange(propertyInfo.GetCustomAttributes(attributeType, false));
for (var info = GetParentDefinition(propertyInfo);
info != null;
info = GetParentDefinition(info))
{
object[] customAttributes = info.GetCustomAttributes(attributeType, false);
AddAttributes(attributes, customAttributes, attributeUsages);
}
var result = Array.CreateInstance(attributeType, attributes.Count) as object[];
Array.Copy(attributes.ToArray(), result, result.Length);
return result;
}
}
return propertyInfo.GetCustomAttributes(attributeType, inherit);
}
private static void AddAttributes(List<object> attributes, object[] customAttributes, Dictionary<Type, bool> attributeUsages)
{
foreach (object attribute in customAttributes)
{
Type type = attribute.GetType();
if (!attributeUsages.ContainsKey(type))
{
attributeUsages[type] = InternalGetAttributeUsage(type).Inherited;
}
if (attributeUsages[type])
{
attributes.Add(attribute);
}
}
}
private static AttributeUsageAttribute InternalGetAttributeUsage(Type type)
{
object[] customAttributes = type.GetCustomAttributes(typeof(AttributeUsageAttribute), true);
return (AttributeUsageAttribute)customAttributes[0];
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2015 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.TestData.TestCaseAttributeFixture;
using NUnit.TestUtilities;
namespace NUnit.Framework.Attributes
{
[TestFixture]
public class TestCaseAttributeTests
{
[TestCase(12, 3, 4)]
[TestCase(12, 2, 6)]
[TestCase(12, 4, 3)]
public void IntegerDivisionWithResultPassedToTest(int n, int d, int q)
{
Assert.AreEqual(q, n / d);
}
[TestCase(12, 3, ExpectedResult = 4)]
[TestCase(12, 2, ExpectedResult = 6)]
[TestCase(12, 4, ExpectedResult = 3)]
public int IntegerDivisionWithResultCheckedByNUnit(int n, int d)
{
return n / d;
}
[TestCase(2, 2, ExpectedResult=4)]
public double CanConvertIntToDouble(double x, double y)
{
return x + y;
}
[TestCase("2.2", "3.3", ExpectedResult = 5.5)]
public decimal CanConvertStringToDecimal(decimal x, decimal y)
{
return x + y;
}
[TestCase(2.2, 3.3, ExpectedResult = 5.5)]
public decimal CanConvertDoubleToDecimal(decimal x, decimal y)
{
return x + y;
}
[TestCase(5, 2, ExpectedResult = 7)]
public decimal CanConvertIntToDecimal(decimal x, decimal y)
{
return x + y;
}
[TestCase(5, 2, ExpectedResult = 7)]
public short CanConvertSmallIntsToShort(short x, short y)
{
return (short)(x + y);
}
[TestCase(5, 2, ExpectedResult = 7)]
public byte CanConvertSmallIntsToByte(byte x, byte y)
{
return (byte)(x + y);
}
[TestCase(5, 2, ExpectedResult = 7)]
public sbyte CanConvertSmallIntsToSByte(sbyte x, sbyte y)
{
return (sbyte)(x + y);
}
[TestCase("MethodCausesConversionOverflow", RunState.NotRunnable)]
[TestCase("VoidTestCaseWithExpectedResult", RunState.NotRunnable)]
[TestCase("TestCaseWithNullableReturnValueAndNullExpectedResult", RunState.Runnable)]
public void TestCaseRunnableState(string methodName, RunState expectedState)
{
var test = (Test)TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseAttributeFixture), methodName).Tests[0];
Assert.AreEqual(expectedState, test.RunState);
}
[TestCase("12-October-1942")]
public void CanConvertStringToDateTime(DateTime dt)
{
Assert.AreEqual(1942, dt.Year);
}
[TestCase("4:44:15")]
public void CanConvertStringToTimeSpan(TimeSpan ts)
{
Assert.AreEqual(4, ts.Hours);
Assert.AreEqual(44, ts.Minutes);
Assert.AreEqual(15, ts.Seconds);
}
[TestCase(null)]
public void CanPassNullAsFirstArgument(object a)
{
Assert.IsNull(a);
}
[TestCase(new object[] { 1, "two", 3.0 })]
[TestCase(new object[] { "zip" })]
public void CanPassObjectArrayAsFirstArgument(object[] a)
{
}
[TestCase(new object[] { "a", "b" })]
public void CanPassArrayAsArgument(object[] array)
{
Assert.AreEqual("a", array[0]);
Assert.AreEqual("b", array[1]);
}
[TestCase("a", "b")]
public void ArgumentsAreCoalescedInObjectArray(object[] array)
{
Assert.AreEqual("a", array[0]);
Assert.AreEqual("b", array[1]);
}
[TestCase(1, "b")]
public void ArgumentsOfDifferentTypeAreCoalescedInObjectArray(object[] array)
{
Assert.AreEqual(1, array[0]);
Assert.AreEqual("b", array[1]);
}
[TestCase(ExpectedResult = null)]
public object ResultCanBeNull()
{
return null;
}
[TestCase("a", "b")]
public void HandlesParamsArrayAsSoleArgument(params string[] array)
{
Assert.AreEqual("a", array[0]);
Assert.AreEqual("b", array[1]);
}
[TestCase("a")]
public void HandlesParamsArrayWithOneItemAsSoleArgument(params string[] array)
{
Assert.AreEqual("a", array[0]);
}
[TestCase("a", "b", "c", "d")]
public void HandlesParamsArrayAsLastArgument(string s1, string s2, params object[] array)
{
Assert.AreEqual("a", s1);
Assert.AreEqual("b", s2);
Assert.AreEqual("c", array[0]);
Assert.AreEqual("d", array[1]);
}
[TestCase("a", "b")]
public void HandlesParamsArrayWithNoItemsAsLastArgument(string s1, string s2, params object[] array)
{
Assert.AreEqual("a", s1);
Assert.AreEqual("b", s2);
Assert.AreEqual(0, array.Length);
}
[TestCase("a", "b", "c")]
public void HandlesParamsArrayWithOneItemAsLastArgument(string s1, string s2, params object[] array)
{
Assert.AreEqual("a", s1);
Assert.AreEqual("b", s2);
Assert.AreEqual("c", array[0]);
}
[TestCase("a", "b", Explicit = true)]
public void ShouldNotRunAndShouldNotFailInConsoleRunner()
{
Assert.Fail();
}
[Test]
public void CanSpecifyDescription()
{
Test test = (Test)TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseAttributeFixture), "MethodHasDescriptionSpecified").Tests[0];
Assert.AreEqual("My Description", test.Properties.Get(PropertyNames.Description));
}
[Test]
public void CanSpecifyTestName_FixedText()
{
Test test = (Test)TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseAttributeFixture), "MethodHasTestNameSpecified_FixedText").Tests[0];
Assert.AreEqual("XYZ", test.Name);
Assert.AreEqual("NUnit.TestData.TestCaseAttributeFixture.TestCaseAttributeFixture.XYZ", test.FullName);
}
[Test]
public void CanSpecifyTestName_WithMethodName()
{
Test test = (Test)TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseAttributeFixture), "MethodHasTestNameSpecified_WithMethodName").Tests[0];
var expectedName = "MethodHasTestNameSpecified_WithMethodName+XYZ";
Assert.AreEqual(expectedName, test.Name);
Assert.AreEqual("NUnit.TestData.TestCaseAttributeFixture.TestCaseAttributeFixture." + expectedName, test.FullName);
}
[Test]
public void CanSpecifyCategory()
{
Test test = (Test)TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseAttributeFixture), "MethodHasSingleCategory").Tests[0];
IList categories = test.Properties["Category"];
Assert.AreEqual(new string[] { "XYZ" }, categories);
}
[Test]
public void CanSpecifyMultipleCategories()
{
Test test = (Test)TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseAttributeFixture), "MethodHasMultipleCategories").Tests[0];
IList categories = test.Properties["Category"];
Assert.AreEqual(new string[] { "X", "Y", "Z" }, categories);
}
[Test]
public void CanIgnoreIndividualTestCases()
{
TestSuite suite = TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseAttributeFixture), "MethodWithIgnoredTestCases");
Test testCase = TestFinder.Find("MethodWithIgnoredTestCases(1)", suite, false);
Assert.That(testCase.RunState, Is.EqualTo(RunState.Runnable));
testCase = TestFinder.Find("MethodWithIgnoredTestCases(2)", suite, false);
Assert.That(testCase.RunState, Is.EqualTo(RunState.Ignored));
testCase = TestFinder.Find("MethodWithIgnoredTestCases(3)", suite, false);
Assert.That(testCase.RunState, Is.EqualTo(RunState.Ignored));
Assert.That(testCase.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Don't Run Me!"));
}
[Test]
public void CanMarkIndividualTestCasesExplicit()
{
TestSuite suite = TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseAttributeFixture), "MethodWithExplicitTestCases");
Test testCase = TestFinder.Find("MethodWithExplicitTestCases(1)", suite, false);
Assert.That(testCase.RunState, Is.EqualTo(RunState.Runnable));
testCase = TestFinder.Find("MethodWithExplicitTestCases(2)", suite, false);
Assert.That(testCase.RunState, Is.EqualTo(RunState.Explicit));
testCase = TestFinder.Find("MethodWithExplicitTestCases(3)", suite, false);
Assert.That(testCase.RunState, Is.EqualTo(RunState.Explicit));
Assert.That(testCase.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Connection failing"));
}
#if !PORTABLE
[Test]
public void CanIncludePlatform()
{
bool isLinux = OSPlatform.CurrentPlatform.IsUnix;
bool isMacOSX = OSPlatform.CurrentPlatform.IsMacOSX;
TestSuite suite = TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseAttributeFixture), "MethodWithIncludePlatform");
Test testCase1 = TestFinder.Find("MethodWithIncludePlatform(1)", suite, false);
Test testCase2 = TestFinder.Find("MethodWithIncludePlatform(2)", suite, false);
Test testCase3 = TestFinder.Find("MethodWithIncludePlatform(3)", suite, false);
Test testCase4 = TestFinder.Find("MethodWithIncludePlatform(4)", suite, false);
if (isLinux)
{
Assert.That(testCase1.RunState, Is.EqualTo(RunState.Skipped));
Assert.That(testCase2.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(testCase3.RunState, Is.EqualTo(RunState.Skipped));
Assert.That(testCase4.RunState, Is.EqualTo(RunState.Skipped));
}
else if (isMacOSX)
{
Assert.That(testCase1.RunState, Is.EqualTo(RunState.Skipped));
Assert.That(testCase2.RunState, Is.EqualTo(RunState.Skipped));
Assert.That(testCase3.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(testCase4.RunState, Is.EqualTo(RunState.Skipped));
}
else
{
Assert.That(testCase1.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(testCase2.RunState, Is.EqualTo(RunState.Skipped));
Assert.That(testCase3.RunState, Is.EqualTo(RunState.Skipped));
Assert.That(testCase4.RunState, Is.EqualTo(RunState.Skipped));
}
}
[Test]
public void CanExcludePlatform()
{
bool isLinux = OSPlatform.CurrentPlatform.IsUnix;
bool isMacOSX = OSPlatform.CurrentPlatform.IsMacOSX;
TestSuite suite = TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseAttributeFixture), "MethodWitExcludePlatform");
Test testCase1 = TestFinder.Find("MethodWitExcludePlatform(1)", suite, false);
Test testCase2 = TestFinder.Find("MethodWitExcludePlatform(2)", suite, false);
Test testCase3 = TestFinder.Find("MethodWitExcludePlatform(3)", suite, false);
Test testCase4 = TestFinder.Find("MethodWitExcludePlatform(4)", suite, false);
if (isLinux)
{
Assert.That(testCase1.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(testCase2.RunState, Is.EqualTo(RunState.Skipped));
Assert.That(testCase3.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(testCase4.RunState, Is.EqualTo(RunState.Runnable));
}
else if (isMacOSX)
{
Assert.That(testCase1.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(testCase2.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(testCase3.RunState, Is.EqualTo(RunState.Skipped));
Assert.That(testCase4.RunState, Is.EqualTo(RunState.Runnable));
}
else
{
Assert.That(testCase1.RunState, Is.EqualTo(RunState.Skipped));
Assert.That(testCase2.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(testCase3.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(testCase4.RunState, Is.EqualTo(RunState.Runnable));
}
}
#endif
#region Nullable<> tests
[TestCase(12, 3, 4)]
[TestCase(12, 2, 6)]
[TestCase(12, 4, 3)]
public void NullableIntegerDivisionWithResultPassedToTest(int? n, int? d, int? q)
{
Assert.AreEqual(q, n / d);
}
[TestCase(12, 3, ExpectedResult = 4)]
[TestCase(12, 2, ExpectedResult = 6)]
[TestCase(12, 4, ExpectedResult = 3)]
public int? NullableIntegerDivisionWithResultCheckedByNUnit(int? n, int? d)
{
return n / d;
}
[TestCase(2, 2, ExpectedResult = 4)]
public double? CanConvertIntToNullableDouble(double? x, double? y)
{
return x + y;
}
[TestCase(1)]
public void CanConvertIntToNullableShort(short? x)
{
Assert.That(x.HasValue);
Assert.That(x.Value, Is.EqualTo(1));
}
[TestCase(1)]
public void CanConvertIntToNullableByte(byte? x)
{
Assert.That(x.HasValue);
Assert.That(x.Value, Is.EqualTo(1));
}
[TestCase(1)]
public void CanConvertIntToNullableSByte(sbyte? x)
{
Assert.That(x.HasValue);
Assert.That(x.Value, Is.EqualTo(1));
}
[TestCase("2.2", "3.3", ExpectedResult = 5.5)]
public decimal? CanConvertStringToNullableDecimal(decimal? x, decimal? y)
{
Assert.That(x.HasValue);
Assert.That(y.HasValue);
return x.Value + y.Value;
}
[TestCase(null)]
public void SupportsNullableDecimal(decimal? x)
{
Assert.That(x.HasValue, Is.False);
}
[TestCase(2.2, 3.3, ExpectedResult = 5.5)]
public decimal? CanConvertDoubleToNullableDecimal(decimal? x, decimal? y)
{
return x + y;
}
[TestCase(5, 2, ExpectedResult = 7)]
public decimal? CanConvertIntToNullableDecimal(decimal? x, decimal? y)
{
return x + y;
}
[TestCase(5, 2, ExpectedResult = 7)]
public short? CanConvertSmallIntsToNullableShort(short? x, short? y)
{
return (short)(x + y);
}
[TestCase(5, 2, ExpectedResult = 7)]
public byte? CanConvertSmallIntsToNullableByte(byte? x, byte? y)
{
return (byte)(x + y);
}
[TestCase(5, 2, ExpectedResult = 7)]
public sbyte? CanConvertSmallIntsToNullableSByte(sbyte? x, sbyte? y)
{
return (sbyte)(x + y);
}
[TestCase("12-October-1942")]
public void CanConvertStringToNullableDateTime(DateTime? dt)
{
Assert.That(dt.HasValue);
Assert.AreEqual(1942, dt.Value.Year);
}
[TestCase(null)]
public void SupportsNullableDateTime(DateTime? dt)
{
Assert.That(dt.HasValue, Is.False);
}
[TestCase("4:44:15")]
public void CanConvertStringToNullableTimeSpan(TimeSpan? ts)
{
Assert.That(ts.HasValue);
Assert.AreEqual(4, ts.Value.Hours);
Assert.AreEqual(44, ts.Value.Minutes);
Assert.AreEqual(15, ts.Value.Seconds);
}
[TestCase(null)]
public void SupportsNullableTimeSpan(TimeSpan? dt)
{
Assert.That(dt.HasValue, Is.False);
}
[TestCase(1)]
public void NullableSimpleFormalParametersWithArgument(int? a)
{
Assert.AreEqual(1, a);
}
[TestCase(null)]
public void NullableSimpleFormalParametersWithNullArgument(int? a)
{
Assert.IsNull(a);
}
[TestCase(null, ExpectedResult = null)]
[TestCase(1, ExpectedResult = 1)]
public int? TestCaseWithNullableReturnValue(int? a)
{
return a;
}
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using Lucene.Net.Index;
using NUnit.Framework;
using WhitespaceAnalyzer = Lucene.Net.Analysis.WhitespaceAnalyzer;
using Document = Lucene.Net.Documents.Document;
using Field = Lucene.Net.Documents.Field;
using NumericField = Lucene.Net.Documents.NumericField;
using IndexWriter = Lucene.Net.Index.IndexWriter;
using MaxFieldLength = Lucene.Net.Index.IndexWriter.MaxFieldLength;
using RAMDirectory = Lucene.Net.Store.RAMDirectory;
using NumericUtils = Lucene.Net.Util.NumericUtils;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
namespace Lucene.Net.Search
{
[TestFixture]
public class TestNumericRangeQuery32:LuceneTestCase
{
// distance of entries
private const int distance = 6666;
// shift the starting of the values to the left, to also have negative values:
private const int startOffset = - 1 << 15;
// number of docs to generate for testing
private const int noDocs = 10000;
private static RAMDirectory directory;
private static IndexSearcher searcher;
/// <summary>test for both constant score and boolean query, the other tests only use the constant score mode </summary>
private void TestRange(int precisionStep)
{
System.String field = "field" + precisionStep;
int count = 3000;
int lower = (distance * 3 / 2) + startOffset, upper = lower + count * distance + (distance / 3);
System.Int32 tempAux = (System.Int32) lower;
System.Int32 tempAux2 = (System.Int32) upper;
NumericRangeQuery<int> q = NumericRangeQuery.NewIntRange(field, precisionStep, tempAux, tempAux2, true, true);
System.Int32 tempAux3 = (System.Int32) lower;
System.Int32 tempAux4 = (System.Int32) upper;
NumericRangeFilter<int> f = NumericRangeFilter.NewIntRange(field, precisionStep, tempAux3, tempAux4, true, true);
int lastTerms = 0;
for (sbyte i = 0; i < 3; i++)
{
TopDocs topDocs;
int terms;
System.String type;
q.ClearTotalNumberOfTerms();
f.ClearTotalNumberOfTerms();
switch (i)
{
case 0:
type = " (constant score filter rewrite)";
q.RewriteMethod = MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE;
topDocs = searcher.Search(q, null, noDocs, Sort.INDEXORDER);
terms = q.TotalNumberOfTerms;
break;
case 1:
type = " (constant score boolean rewrite)";
q.RewriteMethod = MultiTermQuery.CONSTANT_SCORE_BOOLEAN_QUERY_REWRITE;
topDocs = searcher.Search(q, null, noDocs, Sort.INDEXORDER);
terms = q.TotalNumberOfTerms;
break;
case 2:
type = " (filter)";
topDocs = searcher.Search(new MatchAllDocsQuery(), f, noDocs, Sort.INDEXORDER);
terms = f.TotalNumberOfTerms;
break;
default:
return ;
}
System.Console.Out.WriteLine("Found " + terms + " distinct terms in range for field '" + field + "'" + type + ".");
ScoreDoc[] sd = topDocs.ScoreDocs;
Assert.IsNotNull(sd);
Assert.AreEqual(count, sd.Length, "Score doc count" + type);
Document doc = searcher.Doc(sd[0].Doc);
Assert.AreEqual(2 * distance + startOffset, System.Int32.Parse(doc.Get(field)), "First doc" + type);
doc = searcher.Doc(sd[sd.Length - 1].Doc);
Assert.AreEqual((1 + count) * distance + startOffset, System.Int32.Parse(doc.Get(field)), "Last doc" + type);
if (i > 0)
{
Assert.AreEqual(lastTerms, terms, "Distinct term number is equal for all query types");
}
lastTerms = terms;
}
}
[Test]
public virtual void TestRange_8bit()
{
TestRange(8);
}
[Test]
public virtual void TestRange_4bit()
{
TestRange(4);
}
[Test]
public virtual void TestRange_2bit()
{
TestRange(2);
}
[Test]
public virtual void TestInverseRange()
{
System.Int32 tempAux = 1000;
System.Int32 tempAux2 = - 1000;
NumericRangeFilter<int> f = NumericRangeFilter.NewIntRange("field8", 8, tempAux, tempAux2, true, true);
Assert.AreSame(DocIdSet.EMPTY_DOCIDSET, f.GetDocIdSet(searcher.IndexReader), "A inverse range should return the EMPTY_DOCIDSET instance");
//UPGRADE_TODO: The 'System.Int32' structure does not have an equivalent to NULL. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1291'"
System.Int32 tempAux3 = (System.Int32) System.Int32.MaxValue;
f = NumericRangeFilter.NewIntRange("field8", 8, tempAux3, null, false, false);
Assert.AreSame(DocIdSet.EMPTY_DOCIDSET, f.GetDocIdSet(searcher.IndexReader), "A exclusive range starting with Integer.MAX_VALUE should return the EMPTY_DOCIDSET instance");
//UPGRADE_TODO: The 'System.Int32' structure does not have an equivalent to NULL. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1291'"
System.Int32 tempAux4 = (System.Int32) System.Int32.MinValue;
f = NumericRangeFilter.NewIntRange("field8", 8, null, tempAux4, false, false);
Assert.AreSame(DocIdSet.EMPTY_DOCIDSET, f.GetDocIdSet(searcher.IndexReader), "A exclusive range ending with Integer.MIN_VALUE should return the EMPTY_DOCIDSET instance");
}
[Test]
public virtual void TestOneMatchQuery()
{
System.Int32 tempAux = 1000;
System.Int32 tempAux2 = 1000;
NumericRangeQuery<int> q = NumericRangeQuery.NewIntRange("ascfield8", 8, tempAux, tempAux2, true, true);
Assert.AreSame(MultiTermQuery.CONSTANT_SCORE_BOOLEAN_QUERY_REWRITE, q.RewriteMethod);
TopDocs topDocs = searcher.Search(q, noDocs);
ScoreDoc[] sd = topDocs.ScoreDocs;
Assert.IsNotNull(sd);
Assert.AreEqual(1, sd.Length, "Score doc count");
}
private void TestLeftOpenRange(int precisionStep)
{
System.String field = "field" + precisionStep;
int count = 3000;
int upper = (count - 1) * distance + (distance / 3) + startOffset;
//UPGRADE_TODO: The 'System.Int32' structure does not have an equivalent to NULL. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1291'"
System.Int32 tempAux = (System.Int32) upper;
NumericRangeQuery<int> q = NumericRangeQuery.NewIntRange(field, precisionStep, null, tempAux, true, true);
TopDocs topDocs = searcher.Search(q, null, noDocs, Sort.INDEXORDER);
System.Console.Out.WriteLine("Found " + q.TotalNumberOfTerms + " distinct terms in left open range for field '" + field + "'.");
ScoreDoc[] sd = topDocs.ScoreDocs;
Assert.IsNotNull(sd);
Assert.AreEqual(count, sd.Length, "Score doc count");
Document doc = searcher.Doc(sd[0].Doc);
Assert.AreEqual(startOffset, System.Int32.Parse(doc.Get(field)), "First doc");
doc = searcher.Doc(sd[sd.Length - 1].Doc);
Assert.AreEqual((count - 1) * distance + startOffset, System.Int32.Parse(doc.Get(field)), "Last doc");
}
[Test]
public virtual void TestLeftOpenRange_8bit()
{
TestLeftOpenRange(8);
}
[Test]
public virtual void TestLeftOpenRange_4bit()
{
TestLeftOpenRange(4);
}
[Test]
public virtual void TestLeftOpenRange_2bit()
{
TestLeftOpenRange(2);
}
private void TestRightOpenRange(int precisionStep)
{
System.String field = "field" + precisionStep;
int count = 3000;
int lower = (count - 1) * distance + (distance / 3) + startOffset;
NumericRangeQuery<int> q = NumericRangeQuery.NewIntRange(field, precisionStep, lower, null, true, true);
TopDocs topDocs = searcher.Search(q, null, noDocs, Sort.INDEXORDER);
System.Console.Out.WriteLine("Found " + q.TotalNumberOfTerms + " distinct terms in right open range for field '" + field + "'.");
ScoreDoc[] sd = topDocs.ScoreDocs;
Assert.IsNotNull(sd);
Assert.AreEqual(noDocs - count, sd.Length, "Score doc count");
Document doc = searcher.Doc(sd[0].Doc);
Assert.AreEqual(count * distance + startOffset, System.Int32.Parse(doc.Get(field)), "First doc");
doc = searcher.Doc(sd[sd.Length - 1].Doc);
Assert.AreEqual((noDocs - 1) * distance + startOffset, System.Int32.Parse(doc.Get(field)), "Last doc");
}
[Test]
public virtual void TestRightOpenRange_8bit()
{
TestRightOpenRange(8);
}
[Test]
public virtual void TestRightOpenRange_4bit()
{
TestRightOpenRange(4);
}
[Test]
public virtual void TestRightOpenRange_2bit()
{
TestRightOpenRange(2);
}
private void TestRandomTrieAndClassicRangeQuery(int precisionStep)
{
System.Random rnd = NewRandom();
System.String field = "field" + precisionStep;
int termCountT = 0, termCountC = 0;
for (int i = 0; i < 50; i++)
{
int lower = (int) (rnd.NextDouble() * noDocs * distance) + startOffset;
int upper = (int) (rnd.NextDouble() * noDocs * distance) + startOffset;
if (lower > upper)
{
int a = lower; lower = upper; upper = a;
}
// test inclusive range
System.Int32 tempAux = (System.Int32) lower;
System.Int32 tempAux2 = (System.Int32) upper;
NumericRangeQuery<int> tq = NumericRangeQuery.NewIntRange(field, precisionStep, tempAux, tempAux2, true, true);
TermRangeQuery cq = new TermRangeQuery(field, NumericUtils.IntToPrefixCoded(lower), NumericUtils.IntToPrefixCoded(upper), true, true);
TopDocs tTopDocs = searcher.Search(tq, 1);
TopDocs cTopDocs = searcher.Search(cq, 1);
Assert.AreEqual(cTopDocs.TotalHits, tTopDocs.TotalHits, "Returned count for NumericRangeQuery and TermRangeQuery must be equal");
termCountT += tq.TotalNumberOfTerms;
termCountC += cq.TotalNumberOfTerms;
// test exclusive range
System.Int32 tempAux3 = (System.Int32) lower;
System.Int32 tempAux4 = (System.Int32) upper;
tq = NumericRangeQuery.NewIntRange(field, precisionStep, tempAux3, tempAux4, false, false);
cq = new TermRangeQuery(field, NumericUtils.IntToPrefixCoded(lower), NumericUtils.IntToPrefixCoded(upper), false, false);
tTopDocs = searcher.Search(tq, 1);
cTopDocs = searcher.Search(cq, 1);
Assert.AreEqual(cTopDocs.TotalHits, tTopDocs.TotalHits, "Returned count for NumericRangeQuery and TermRangeQuery must be equal");
termCountT += tq.TotalNumberOfTerms;
termCountC += cq.TotalNumberOfTerms;
// test left exclusive range
System.Int32 tempAux5 = (System.Int32) lower;
System.Int32 tempAux6 = (System.Int32) upper;
tq = NumericRangeQuery.NewIntRange(field, precisionStep, tempAux5, tempAux6, false, true);
cq = new TermRangeQuery(field, NumericUtils.IntToPrefixCoded(lower), NumericUtils.IntToPrefixCoded(upper), false, true);
tTopDocs = searcher.Search(tq, 1);
cTopDocs = searcher.Search(cq, 1);
Assert.AreEqual(cTopDocs.TotalHits, tTopDocs.TotalHits, "Returned count for NumericRangeQuery and TermRangeQuery must be equal");
termCountT += tq.TotalNumberOfTerms;
termCountC += cq.TotalNumberOfTerms;
// test right exclusive range
System.Int32 tempAux7 = (System.Int32) lower;
System.Int32 tempAux8 = (System.Int32) upper;
tq = NumericRangeQuery.NewIntRange(field, precisionStep, tempAux7, tempAux8, true, false);
cq = new TermRangeQuery(field, NumericUtils.IntToPrefixCoded(lower), NumericUtils.IntToPrefixCoded(upper), true, false);
tTopDocs = searcher.Search(tq, 1);
cTopDocs = searcher.Search(cq, 1);
Assert.AreEqual(cTopDocs.TotalHits, tTopDocs.TotalHits, "Returned count for NumericRangeQuery and TermRangeQuery must be equal");
termCountT += tq.TotalNumberOfTerms;
termCountC += cq.TotalNumberOfTerms;
}
if (precisionStep == System.Int32.MaxValue)
{
Assert.AreEqual(termCountT, termCountC, "Total number of terms should be equal for unlimited precStep");
}
else
{
System.Console.Out.WriteLine("Average number of terms during random search on '" + field + "':");
System.Console.Out.WriteLine(" Trie query: " + (((double) termCountT) / (50 * 4)));
System.Console.Out.WriteLine(" Classical query: " + (((double) termCountC) / (50 * 4)));
}
}
[Test]
public virtual void TestRandomTrieAndClassicRangeQuery_8bit()
{
TestRandomTrieAndClassicRangeQuery(8);
}
[Test]
public virtual void TestRandomTrieAndClassicRangeQuery_4bit()
{
TestRandomTrieAndClassicRangeQuery(4);
}
[Test]
public virtual void TestRandomTrieAndClassicRangeQuery_2bit()
{
TestRandomTrieAndClassicRangeQuery(2);
}
[Test]
public virtual void TestRandomTrieAndClassicRangeQuery_NoTrie()
{
TestRandomTrieAndClassicRangeQuery(System.Int32.MaxValue);
}
private void TestRangeSplit(int precisionStep)
{
System.Random rnd = NewRandom();
System.String field = "ascfield" + precisionStep;
// 50 random tests
for (int i = 0; i < 50; i++)
{
int lower = (int) (rnd.NextDouble() * noDocs - noDocs / 2);
int upper = (int) (rnd.NextDouble() * noDocs - noDocs / 2);
if (lower > upper)
{
int a = lower; lower = upper; upper = a;
}
// test inclusive range
System.Int32 tempAux = (System.Int32) lower;
System.Int32 tempAux2 = (System.Int32) upper;
Query tq = NumericRangeQuery.NewIntRange(field, precisionStep, tempAux, tempAux2, true, true);
TopDocs tTopDocs = searcher.Search(tq, 1);
Assert.AreEqual(upper - lower + 1, tTopDocs.TotalHits, "Returned count of range query must be equal to inclusive range length");
// test exclusive range
System.Int32 tempAux3 = (System.Int32) lower;
System.Int32 tempAux4 = (System.Int32) upper;
tq = NumericRangeQuery.NewIntRange(field, precisionStep, tempAux3, tempAux4, false, false);
tTopDocs = searcher.Search(tq, 1);
Assert.AreEqual(System.Math.Max(upper - lower - 1, 0), tTopDocs.TotalHits, "Returned count of range query must be equal to exclusive range length");
// test left exclusive range
System.Int32 tempAux5 = (System.Int32) lower;
System.Int32 tempAux6 = (System.Int32) upper;
tq = NumericRangeQuery.NewIntRange(field, precisionStep, tempAux5, tempAux6, false, true);
tTopDocs = searcher.Search(tq, 1);
Assert.AreEqual(upper - lower, tTopDocs.TotalHits, "Returned count of range query must be equal to half exclusive range length");
// test right exclusive range
System.Int32 tempAux7 = (System.Int32) lower;
System.Int32 tempAux8 = (System.Int32) upper;
tq = NumericRangeQuery.NewIntRange(field, precisionStep, tempAux7, tempAux8, true, false);
tTopDocs = searcher.Search(tq, 1);
Assert.AreEqual(upper - lower, tTopDocs.TotalHits, "Returned count of range query must be equal to half exclusive range length");
}
}
[Test]
public virtual void TestRangeSplit_8bit()
{
TestRangeSplit(8);
}
[Test]
public virtual void TestRangeSplit_4bit()
{
TestRangeSplit(4);
}
[Test]
public virtual void TestRangeSplit_2bit()
{
TestRangeSplit(2);
}
/// <summary>we fake a float test using int2float conversion of NumericUtils </summary>
private void TestFloatRange(int precisionStep)
{
System.String field = "ascfield" + precisionStep;
int lower = - 1000;
int upper = + 2000;
System.Single tempAux = (float) NumericUtils.SortableIntToFloat(lower);
System.Single tempAux2 = (float) NumericUtils.SortableIntToFloat(upper);
Query tq = NumericRangeQuery.NewFloatRange(field, precisionStep, tempAux, tempAux2, true, true);
TopDocs tTopDocs = searcher.Search(tq, 1);
Assert.AreEqual(upper - lower + 1, tTopDocs.TotalHits, "Returned count of range query must be equal to inclusive range length");
System.Single tempAux3 = (float) NumericUtils.SortableIntToFloat(lower);
System.Single tempAux4 = (float) NumericUtils.SortableIntToFloat(upper);
Filter tf = NumericRangeFilter.NewFloatRange(field, precisionStep, tempAux3, tempAux4, true, true);
tTopDocs = searcher.Search(new MatchAllDocsQuery(), tf, 1);
Assert.AreEqual(upper - lower + 1, tTopDocs.TotalHits, "Returned count of range filter must be equal to inclusive range length");
}
[Test]
public virtual void TestFloatRange_8bit()
{
TestFloatRange(8);
}
[Test]
public virtual void TestFloatRange_4bit()
{
TestFloatRange(4);
}
[Test]
public virtual void TestFloatRange_2bit()
{
TestFloatRange(2);
}
private void TestSorting(int precisionStep)
{
System.Random rnd = NewRandom();
System.String field = "field" + precisionStep;
// 10 random tests, the index order is ascending,
// so using a reverse sort field should retun descending documents
for (int i = 0; i < 10; i++)
{
int lower = (int) (rnd.NextDouble() * noDocs * distance) + startOffset;
int upper = (int) (rnd.NextDouble() * noDocs * distance) + startOffset;
if (lower > upper)
{
int a = lower; lower = upper; upper = a;
}
System.Int32 tempAux = (System.Int32) lower;
System.Int32 tempAux2 = (System.Int32) upper;
Query tq = NumericRangeQuery.NewIntRange(field, precisionStep, tempAux, tempAux2, true, true);
TopDocs topDocs = searcher.Search(tq, null, noDocs, new Sort(new SortField(field, SortField.INT, true)));
if (topDocs.TotalHits == 0)
continue;
ScoreDoc[] sd = topDocs.ScoreDocs;
Assert.IsNotNull(sd);
int last = System.Int32.Parse(searcher.Doc(sd[0].Doc).Get(field));
for (int j = 1; j < sd.Length; j++)
{
int act = System.Int32.Parse(searcher.Doc(sd[j].Doc).Get(field));
Assert.IsTrue(last > act, "Docs should be sorted backwards");
last = act;
}
}
}
[Test]
public virtual void TestSorting_8bit()
{
TestSorting(8);
}
[Test]
public virtual void TestSorting_4bit()
{
TestSorting(4);
}
[Test]
public virtual void TestSorting_2bit()
{
TestSorting(2);
}
[Test]
public virtual void TestEqualsAndHash()
{
QueryUtils.CheckHashEquals(NumericRangeQuery.NewIntRange("test1", 4, 10, 20, true, true));
QueryUtils.CheckHashEquals(NumericRangeQuery.NewIntRange("test2", 4, 10, 20, false, true));
QueryUtils.CheckHashEquals(NumericRangeQuery.NewIntRange("test3", 4, 10, 20, true, false));
QueryUtils.CheckHashEquals(NumericRangeQuery.NewIntRange("test4", 4, 10, 20, false, false));
QueryUtils.CheckHashEquals(NumericRangeQuery.NewIntRange("test5", 4, 10, null, true, true));
QueryUtils.CheckHashEquals(NumericRangeQuery.NewIntRange("test6", 4, null, 20, true, true));
QueryUtils.CheckHashEquals(NumericRangeQuery.NewIntRange("test7", 4, null, null, true, true));
QueryUtils.CheckEqual(NumericRangeQuery.NewIntRange("test8", 4, 10, 20, true, true),
NumericRangeQuery.NewIntRange("test8", 4, 10, 20, true, true));
QueryUtils.CheckUnequal(NumericRangeQuery.NewIntRange("test9", 4, 10, 20, true, true),
NumericRangeQuery.NewIntRange("test9", 8, 10, 20, true, true));
QueryUtils.CheckUnequal(NumericRangeQuery.NewIntRange("test10a", 4, 10, 20, true, true),
NumericRangeQuery.NewIntRange("test10b", 4, 10, 20, true, true));
QueryUtils.CheckUnequal(NumericRangeQuery.NewIntRange("test11", 4, 10, 20, true, true),
NumericRangeQuery.NewIntRange("test11", 4, 20, 10, true, true));
QueryUtils.CheckUnequal(NumericRangeQuery.NewIntRange("test12", 4, 10, 20, true, true),
NumericRangeQuery.NewIntRange("test12", 4, 10, 20, false, true));
QueryUtils.CheckUnequal(NumericRangeQuery.NewIntRange("test13", 4, 10, 20, true, true),
NumericRangeQuery.NewFloatRange("test13", 4, 10f, 20f, true, true));
// the following produces a hash collision, because Long and Integer have the same hashcode, so only test equality:
Query q1 = NumericRangeQuery.NewIntRange("test14", 4, 10, 20, true, true);
Query q2 = NumericRangeQuery.NewLongRange("test14", 4, 10L, 20L, true, true);
Assert.IsFalse(q1.Equals(q2));
Assert.IsFalse(q2.Equals(q1));
}
private void testEnum(int lower, int upper)
{
NumericRangeQuery<int> q = NumericRangeQuery.NewIntRange("field4", 4, lower, upper, true, true);
FilteredTermEnum termEnum = q.GetEnum(searcher.IndexReader);
try
{
int count = 0;
do
{
Term t = termEnum.Term;
if (t != null)
{
int val = NumericUtils.PrefixCodedToInt(t.Text);
Assert.True(val >= lower && val <= upper, "value not in bounds");
count++;
}
else break;
} while (termEnum.Next());
Assert.False(termEnum.Next());
Console.WriteLine("TermEnum on 'field4' for range [" + lower + "," + upper + "] contained " + count +
" terms.");
}
finally
{
termEnum.Close();
}
}
public void testEnum()
{
int count = 3000;
int lower = (distance*3/2) + startOffset, upper = lower + count*distance + (distance/3);
// test enum with values
testEnum(lower, upper);
// test empty enum
testEnum(upper, lower);
// test empty enum outside of bounds
lower = distance*noDocs + startOffset;
upper = 2*lower;
testEnum(lower, upper);
}
static TestNumericRangeQuery32()
{
{
try
{
// set the theoretical maximum term count for 8bit (see docs for the number)
BooleanQuery.MaxClauseCount = 3 * 255 * 2 + 255;
directory = new RAMDirectory();
IndexWriter writer = new IndexWriter(directory, new WhitespaceAnalyzer(), true, MaxFieldLength.UNLIMITED);
NumericField field8 = new NumericField("field8", 8, Field.Store.YES, true), field4 = new NumericField("field4", 4, Field.Store.YES, true), field2 = new NumericField("field2", 2, Field.Store.YES, true), fieldNoTrie = new NumericField("field" + System.Int32.MaxValue, System.Int32.MaxValue, Field.Store.YES, true), ascfield8 = new NumericField("ascfield8", 8, Field.Store.NO, true), ascfield4 = new NumericField("ascfield4", 4, Field.Store.NO, true), ascfield2 = new NumericField("ascfield2", 2, Field.Store.NO, true);
Document doc = new Document();
// add fields, that have a distance to test general functionality
doc.Add(field8); doc.Add(field4); doc.Add(field2); doc.Add(fieldNoTrie);
// add ascending fields with a distance of 1, beginning at -noDocs/2 to test the correct splitting of range and inclusive/exclusive
doc.Add(ascfield8); doc.Add(ascfield4); doc.Add(ascfield2);
// Add a series of noDocs docs with increasing int values
for (int l = 0; l < noDocs; l++)
{
int val = distance * l + startOffset;
field8.SetIntValue(val);
field4.SetIntValue(val);
field2.SetIntValue(val);
fieldNoTrie.SetIntValue(val);
val = l - (noDocs / 2);
ascfield8.SetIntValue(val);
ascfield4.SetIntValue(val);
ascfield2.SetIntValue(val);
writer.AddDocument(doc);
}
writer.Optimize();
writer.Close();
searcher = new IndexSearcher(directory, true);
}
catch (System.Exception e)
{
throw new System.SystemException("", e);
}
}
}
}
}
| |
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// NOTE: This file based on
// http://github.com/googleapis/google-cloud-dotnet/blob/c4439e0099d9e4c414afbe666f0d2bb28f95b297/apis/Google.Cloud.Firestore/Google.Cloud.Firestore.Tests/SerializationTestData.cs
// This file has been modified from its original version. It has been adapted to use raw C# types
// instead of protos and to work in .Net 3.5.
using System;
using System.Collections.Generic;
using System.Linq;
using Firebase.Firestore;
namespace Firebase.Sample.Firestore {
internal static class SerializationTestData {
private static DateTime dateTime = new DateTime(1990, 1, 2, 3, 4, 5, DateTimeKind.Utc);
private static DateTimeOffset dateTimeOffset = new DateTimeOffset(1990, 1, 2, 3, 4, 5, TimeSpan.FromHours(1));
internal class TestCase {
internal enum TestOutcome {
Success,
// Given input type can be write to Firestore, can be read into Firestore raw types, but not
// the input type.
ReadToInputTypesNotSupported,
// Given input type cannot be write to Firestore, nor can any data be read into the input
// type.
Unsupported
}
private TestOutcome _result = TestOutcome.Success;
/// <summary>
/// Expected outcome of this test.
/// </summary>
internal TestOutcome Result {
get { return _result; }
private
set { _result = value; }
}
/// <summary>
/// The object to serialize into Firestore document.
/// </summary>
internal object Input { get; private set; }
/// <summary>
/// The expected output from the Firestore document deserialized to raw
/// Firestore type (<code>Dictionary<string, object></code>, or primitive types).
/// </summary>
internal object ExpectedRawOutput { get; private set; }
public TestCase(object input, object expectedRawOutput) {
Input = input;
ExpectedRawOutput = expectedRawOutput;
}
public TestCase(object input, object expectedRawOutput, TestOutcome result) {
Input = input;
ExpectedRawOutput = expectedRawOutput;
Result = result;
}
}
public static IEnumerable<TestCase> TestData(FirebaseFirestore database) {
return new List<TestCase> {
// Simple types
{ new TestCase(null, null) },
{ new TestCase(true, true) },
{ new TestCase(false, false) },
{ new TestCase("test", "test") },
{ new TestCase((byte)1, 1L) },
{ new TestCase((sbyte)1, 1L) },
{ new TestCase((short)1, 1L) },
{ new TestCase((ushort)1, 1L) },
{ new TestCase(1, 1L) },
{ new TestCase(1U, 1L) },
{ new TestCase(1L, 1L) },
{ new TestCase(1UL, 1L) },
{ new TestCase(1.5F, 1.5D) },
{ new TestCase(float.PositiveInfinity, double.PositiveInfinity) },
{ new TestCase(float.NegativeInfinity, double.NegativeInfinity) },
{ new TestCase(float.NaN, double.NaN) },
{ new TestCase(1.5D, 1.5D) },
{ new TestCase(double.PositiveInfinity, double.PositiveInfinity) },
{ new TestCase(double.NegativeInfinity, double.NegativeInfinity) },
{ new TestCase(double.NaN, double.NaN) },
// Min/max values of each integer type
{ new TestCase(byte.MinValue, (long)byte.MinValue) },
{ new TestCase(byte.MaxValue, (long)byte.MaxValue) },
{ new TestCase(sbyte.MinValue, (long)sbyte.MinValue) },
{ new TestCase(sbyte.MaxValue, (long)sbyte.MaxValue) },
{ new TestCase(short.MinValue, (long)short.MinValue) },
{ new TestCase(short.MaxValue, (long)short.MaxValue) },
{ new TestCase(ushort.MinValue, (long)ushort.MinValue) },
{ new TestCase(ushort.MaxValue, (long)ushort.MaxValue) },
{ new TestCase(int.MinValue, (long)int.MinValue) },
{ new TestCase(int.MaxValue, (long)int.MaxValue) },
{ new TestCase(uint.MinValue, (long)uint.MinValue) },
{ new TestCase(uint.MaxValue, (long)uint.MaxValue) },
{ new TestCase(long.MinValue, long.MinValue) },
{ new TestCase(long.MaxValue, long.MaxValue) },
// We don't cover the whole range of ulong
{ new TestCase((ulong)0, 0L) },
{ new TestCase((ulong) long.MaxValue, long.MaxValue) },
// Enum types
{ new TestCase(ByteEnum.MinValue, (long)byte.MinValue) },
{ new TestCase(ByteEnum.MaxValue, (long)byte.MaxValue) },
{ new TestCase(SByteEnum.MinValue, (long)sbyte.MinValue) },
{ new TestCase(SByteEnum.MaxValue, (long)sbyte.MaxValue) },
{ new TestCase(Int16Enum.MinValue, (long)short.MinValue) },
{ new TestCase(Int16Enum.MaxValue, (long)short.MaxValue) },
{ new TestCase(UInt16Enum.MinValue, (long)ushort.MinValue) },
{ new TestCase(UInt16Enum.MaxValue, (long)ushort.MaxValue) },
{ new TestCase(Int32Enum.MinValue, (long)int.MinValue) },
{ new TestCase(Int32Enum.MaxValue, (long)int.MaxValue) },
{ new TestCase(UInt32Enum.MinValue, (long)uint.MinValue) },
{ new TestCase(UInt32Enum.MaxValue, (long)uint.MaxValue) },
{ new TestCase(Int64Enum.MinValue, (long)long.MinValue) },
{ new TestCase(Int64Enum.MaxValue, (long)long.MaxValue) },
// We don't cover the whole range of ulong
{ new TestCase(UInt64Enum.MinValue, (long)0) },
{ new TestCase(UInt64Enum.MaxRepresentableValue, (long)long.MaxValue) },
{ new TestCase(CustomConversionEnum.Foo, "Foo") },
{ new TestCase(CustomConversionEnum.Bar, "Bar") },
// Timestamps
{ new TestCase(Timestamp.FromDateTime(dateTime), Timestamp.FromDateTime(dateTime)) },
{ new TestCase(dateTime, Timestamp.FromDateTime(dateTime)) },
{ new TestCase(dateTimeOffset, Timestamp.FromDateTimeOffset(dateTimeOffset)) },
// Blobs
{ new TestCase(new byte[] { 1, 2, 3, 4 }, Blob.CopyFrom(new byte[] { 1, 2, 3, 4 })) },
{ new TestCase(Blob.CopyFrom(new byte[] { 1, 2, 3, 4 }),
Blob.CopyFrom(new byte[] { 1, 2, 3, 4 })) },
// GeoPoints
{ new TestCase(new GeoPoint(1.5, 2.5), new GeoPoint(1.5, 2.5)) },
// Array values
{ new TestCase(new string[] { "x", "y" }, new List<object> { "x", "y" }) },
{ new TestCase(new List<string> { "x", "y" }, new List<object> { "x", "y" }) },
{ new TestCase(new int[] { 3, 4 }, new List<object> { 3L, 4L }) },
// Deliberately DateTime rather than Timestamp here - we need to be able to detect the
// element type to perform the per-element deserialization correctly
{ new TestCase(new List<DateTime> { dateTime, dateTime },
new List<object> { Timestamp.FromDateTime(dateTime),
Timestamp.FromDateTime(dateTime) }) },
// Map values (that can be deserialized again): dictionaries, attributed types, expandos
// (which are just dictionaries), custom serialized map-like values
// Dictionaries
{ new TestCase(new Dictionary<string, byte> { { "A", 10 }, { "B", 20 } },
new Dictionary<string, object> { { "A", 10L }, { "B", 20L } }) },
{ new TestCase(new Dictionary<string, int> { { "A", 10 }, { "B", 20 } },
new Dictionary<string, object> { { "A", 10L }, { "B", 20L } }) },
{ new TestCase(new Dictionary<string, object> { { "name", "Jon" }, { "score", 10L } },
new Dictionary<string, object> { { "name", "Jon" }, { "score", 10L } }) },
// Attributed type (each property has an attribute)
{ new TestCase(new GameResult { Name = "Jon", Score = 10 },
new Dictionary<string, object> { { "name", "Jon" }, { "Score", 10L } }) },
// Attributed type contained in a dictionary
{ new TestCase(
new Dictionary<string, GameResult> { { "result",
new GameResult { Name = "Jon", Score = 10 } } },
new Dictionary<string, object> {
{ "result", new Dictionary<string, object> { { "name", "Jon" }, { "Score", 10L } } }
}) },
// Attributed type containing a dictionary
{ new TestCase(
new DictionaryInterfaceContainer {
Integers = new Dictionary<string, int> { { "A", 10 }, { "B", 20 } }
},
new Dictionary<string, object> {
{ "Integers", new Dictionary<string, object> { { "A", 10L }, { "B", 20L } } }
}) },
// Attributed type serialized and deserialized by CustomPlayerConverter
{ new TestCase(new CustomPlayer { Name = "Amanda", Score = 15 },
new Dictionary<string, object> { { "PlayerName", "Amanda" },
{ "PlayerScore", 15L } }) },
// Attributed value type serialized and deserialized by CustomValueTypeConverter
{ new TestCase(new CustomValueType("xyz", 10),
new Dictionary<string, object> { { "Name", "xyz" }, { "Value", 10L } }) },
// Attributed type with enums (name and number)
{ new TestCase(new ModelWithEnums { EnumDefaultByName = CustomConversionEnum.Foo,
EnumAttributedByName = Int32Enum.MinValue,
EnumByNumber = Int32Enum.MaxValue },
new Dictionary<string, object> { { "EnumDefaultByName", "Foo" },
{ "EnumAttributedByName", "MinValue" },
{ "EnumByNumber", (long)int.MaxValue } }) },
// Attributed type with List field
{ new TestCase(new CustomUser { Name = "Jon", HighScore = 10,
Emails = new List<string> { "jon@example.com" } },
new Dictionary<string, object> {
{ "Name", "Jon" },
{ "HighScore", 10L },
{ "Emails", new List<object> { "jon@example.com" } }
}) },
// Attributed type with IEnumerable field
{ new TestCase(
new CustomUserEnumerableEmails() { Name = "Jon", HighScore = 10,
Emails = new List<string> { "jon@example.com" } },
new Dictionary<string, object> { { "Name", "Jon" },
{ "HighScore", 10L },
{ "Emails",
new List<object> { "jon@example.com" } } }) },
// Attributed type with Set field and custom converter.
{ new TestCase(
new CustomUserSetEmailsWithConverter() {
Name = "Jon", HighScore = 10, Emails = new HashSet<string> { "jon@example.com" }
},
new Dictionary<string, object> { { "Name", "Jon" },
{ "HighScore", 10L },
{ "Emails",
new List<object> { "jon@example.com" } } }) },
// Attributed struct
{ new TestCase(new StructModel { Name = "xyz", Value = 10 },
new Dictionary<string, object> { { "Name", "xyz" }, { "Value", 10L } }) },
// Document references
{ new TestCase(database.Document("a/b"), database.Document("a/b")) },
};
}
public static IEnumerable<TestCase> UnsupportedTestData() {
var testCases = new List<TestCase> {
// Nullable type handling
{ new TestCase(new NullableContainer { NullableValue = 10 },
new Dictionary<string, object> { { "NullableValue", 10L } },
TestCase.TestOutcome.Unsupported) },
{ new TestCase(new NullableEnumContainer { NullableValue = (Int32Enum)10 },
new Dictionary<string, object> { { "NullableValue", 10L } },
TestCase.TestOutcome.Unsupported) },
// This one fails because the `NullableContainer` it gets back has a random value
// while it should be null.
{ new TestCase(new NullableContainer { NullableValue = null },
new Dictionary<string, object> { { "NullableValue", null } },
TestCase.TestOutcome.Unsupported) },
{ new TestCase(new NullableEnumContainer { NullableValue = null },
new Dictionary<string, object> { { "NullableValue", null } },
TestCase.TestOutcome.Unsupported) },
{ new TestCase(
new CustomUserSetEmails { Name = "Jon", HighScore = 10,
Emails = new HashSet<string> { "jon@example.com" } },
new Dictionary<string, object> { { "Name", "Jon" },
{ "HighScore", 10L },
{ "Emails", new List<object> { "jon@example.com" } } },
TestCase.TestOutcome.ReadToInputTypesNotSupported) },
};
// TODO(b/198466069) Re-enable this test once the bug is fixed in dotnet3 runtimes.
if (Environment.Version.Major >= 4) {
// IEnumerable values cannot be assigned from a List.
// TODO(b/173894435): there should be a way to specify if it is serialization or
// deserialization failure.
testCases.Add(new TestCase(Enumerable.Range(3, 2).Select(i => (long)i),
Enumerable.Range(3, 2).Select(i => (long)i),
TestCase.TestOutcome.ReadToInputTypesNotSupported));
}
return testCases;
}
// Only equatable for the sake of testing; that's not a requirement of the serialization code.
[FirestoreData]
internal class GameResult : IEquatable<GameResult> {
[FirestoreProperty("name")]
public string Name { get; set; }
[FirestoreProperty] // No property name specified, so field will be Score
public int Score { get; set; }
public override int GetHashCode() { return Name.GetHashCode() ^ Score; }
public override bool Equals(object obj) { return Equals(obj as GameResult); }
public bool Equals(GameResult other) { return other != null && other.Name == Name && other.Score == Score; }
}
[FirestoreData]
internal class NullableContainer : IEquatable<NullableContainer> {
[FirestoreProperty]
public long? NullableValue { get; set; }
public override int GetHashCode() { return (int)NullableValue.GetValueOrDefault().GetHashCode(); }
public override bool Equals(object obj) { return Equals(obj as NullableContainer); }
public bool Equals(NullableContainer other) { return other != null && other.NullableValue == NullableValue; }
public override string ToString() { return String.Format("NullableContainer: {0}", NullableValue.GetValueOrDefault()); }
}
[FirestoreData]
internal class NullableEnumContainer : IEquatable<NullableEnumContainer> {
[FirestoreProperty]
public Int32Enum? NullableValue { get; set; }
public override int GetHashCode() { return (int)NullableValue.GetValueOrDefault().GetHashCode(); }
public override bool Equals(object obj) { return Equals(obj as NullableEnumContainer); }
public bool Equals(NullableEnumContainer other) { return other != null && other.NullableValue == NullableValue; }
}
[FirestoreData]
internal class DictionaryInterfaceContainer : IEquatable<DictionaryInterfaceContainer> {
[FirestoreProperty]
public IDictionary<string, int> Integers { get; set; }
public override int GetHashCode() { return Integers.Sum(pair => pair.Key.GetHashCode() + pair.Value); }
public override bool Equals(object obj) { return Equals(obj as DictionaryInterfaceContainer); }
public bool Equals(DictionaryInterfaceContainer other) {
if (other == null) {
return false;
}
if (Integers == other.Integers) {
return true;
}
if (Integers == null || other.Integers == null) {
return false;
}
if (Integers.Count != other.Integers.Count) {
return false;
}
int otherValue;
return Integers.All(pair => other.Integers.TryGetValue(pair.Key, out otherValue) && pair.Value == otherValue);
}
}
internal enum SByteEnum : sbyte {
MinValue = sbyte.MinValue,
MaxValue = sbyte.MaxValue
}
internal enum Int16Enum : short {
MinValue = short.MinValue,
MaxValue = short.MaxValue
}
internal enum Int32Enum : int {
MinValue = int.MinValue,
MaxValue = int.MaxValue
}
internal enum Int64Enum : long {
MinValue = long.MinValue,
MaxValue = long.MaxValue
}
internal enum ByteEnum : byte {
MinValue = byte.MinValue,
MaxValue = byte.MaxValue
}
internal enum UInt16Enum : ushort {
MinValue = ushort.MinValue,
MaxValue = ushort.MaxValue
}
internal enum UInt32Enum : uint {
MinValue = uint.MinValue,
MaxValue = uint.MaxValue
}
internal enum UInt64Enum : ulong {
MinValue = ulong.MinValue,
MaxRepresentableValue = long.MaxValue
}
[FirestoreData(ConverterType = typeof(FirestoreEnumNameConverter<CustomConversionEnum>))]
internal enum CustomConversionEnum {
Foo = 1,
Bar = 2
}
[FirestoreData]
public sealed class ModelWithEnums {
[FirestoreProperty]
public CustomConversionEnum EnumDefaultByName { get; set; }
[FirestoreProperty(ConverterType = typeof(FirestoreEnumNameConverter<Int32Enum>))]
public Int32Enum EnumAttributedByName { get; set; }
[FirestoreProperty]
public Int32Enum EnumByNumber { get; set; }
public override bool Equals(object obj) {
if (!(obj is ModelWithEnums)) {
return false;
}
ModelWithEnums other = obj as ModelWithEnums;
return EnumDefaultByName == other.EnumDefaultByName &&
EnumAttributedByName == other.EnumAttributedByName &&
EnumByNumber == other.EnumByNumber;
}
public override int GetHashCode() { return 0; }
}
[FirestoreData]
public sealed class CustomUser {
[FirestoreProperty]
public int HighScore { get; set; }
[FirestoreProperty]
public string Name { get; set; }
[FirestoreProperty] public List<string> Emails { get; set; }
public override bool Equals(object obj) {
if (!(obj is CustomUser)) {
return false;
}
CustomUser other = (CustomUser)obj;
return HighScore == other.HighScore && Name == other.Name &&
Emails.SequenceEqual(other.Emails);
}
public override int GetHashCode() {
return 0;
}
}
[FirestoreData]
public sealed class CustomUserEnumerableEmails {
[FirestoreProperty]
public int HighScore { get; set; }
[FirestoreProperty] public string Name { get; set; }
[FirestoreProperty] public IEnumerable<string> Emails { get; set; }
public override bool Equals(object obj) {
if (!(obj is CustomUserEnumerableEmails)) {
return false;
}
CustomUserEnumerableEmails other = (CustomUserEnumerableEmails)obj;
return HighScore == other.HighScore && Name == other.Name &&
Emails.SequenceEqual(other.Emails);
}
public override int GetHashCode() {
return 0;
}
}
[FirestoreData]
public sealed class CustomUserSetEmails {
[FirestoreProperty]
public int HighScore { get; set; }
[FirestoreProperty] public string Name { get; set; }
[FirestoreProperty] public HashSet<string> Emails { get; set; }
public override bool Equals(object obj) {
if (!(obj is CustomUserSetEmails)) {
return false;
}
CustomUserSetEmails other = (CustomUserSetEmails)obj;
return HighScore == other.HighScore && Name == other.Name &&
Emails.SequenceEqual(other.Emails);
}
public override int GetHashCode() {
return 0;
}
}
[FirestoreData(ConverterType = typeof(CustomUserSetEmailsConverter))]
public sealed class CustomUserSetEmailsWithConverter {
[FirestoreProperty]
public int HighScore { get; set; }
[FirestoreProperty] public string Name { get; set; }
[FirestoreProperty] public HashSet<string> Emails { get; set; }
public override bool Equals(object obj) {
if (!(obj is CustomUserSetEmailsWithConverter)) {
return false;
}
var other = (CustomUserSetEmailsWithConverter)obj;
return HighScore == other.HighScore && Name == other.Name &&
Emails.SequenceEqual(other.Emails);
}
public override int GetHashCode() {
return 0;
}
}
public class CustomUserSetEmailsConverter
: FirestoreConverter<CustomUserSetEmailsWithConverter> {
public override CustomUserSetEmailsWithConverter FromFirestore(object value) {
if (value == null) {
throw new ArgumentNullException("value"); // Shouldn't happen
}
var map = (Dictionary<string, object>)value;
var emails = (List<object>)map["Emails"];
var emailSet = new HashSet<string>(emails.Select(o => o.ToString()));
return new CustomUserSetEmailsWithConverter { Name = (string)map["Name"],
HighScore = Convert.ToInt32(map["HighScore"]),
Emails = emailSet };
}
public override object ToFirestore(CustomUserSetEmailsWithConverter value) {
return new Dictionary<string, object> {
{ "Name", value.Name },
{ "HighScore", value.HighScore },
{ "Emails", value.Emails },
};
}
}
[FirestoreData(ConverterType = typeof(EmailConverter))]
public sealed class Email {
public readonly string Address;
public Email(string address) { Address = address; }
}
public class EmailConverter : FirestoreConverter<Email> {
public override Email FromFirestore(object value) {
if (value == null) {
throw new ArgumentNullException("value"); // Shouldn't happen
} else if (value is string) {
return new Email(value as string);
} else {
throw new ArgumentException(String.Format("Unexpected data: {}", value.GetType()));
}
}
public override object ToFirestore(Email value) { return value == null ? null : value.Address; }
}
[FirestoreData]
public class GuidPair {
[FirestoreProperty]
public string Name { get; set; }
[FirestoreProperty(ConverterType = typeof(GuidConverter))]
public Guid Guid { get; set; }
[FirestoreProperty(ConverterType = typeof(GuidConverter))]
public Guid? GuidOrNull { get; set; }
}
// Like GuidPair, but without the converter specified - it has to come
// from a converter registry instead.
[FirestoreData]
public class GuidPair2 {
[FirestoreProperty]
public string Name { get; set; }
[FirestoreProperty]
public Guid Guid { get; set; }
[FirestoreProperty]
public Guid? GuidOrNull { get; set; }
}
public class GuidConverter : FirestoreConverter<Guid> {
public override Guid FromFirestore(object value) {
if (value == null) {
throw new ArgumentNullException("value"); // Shouldn't happen
} else if (value is string) {
return new Guid(value as string);
} else {
throw new ArgumentException(String.Format("Unexpected data: {0}", value.GetType()));
}
}
public override object ToFirestore(Guid value) { return value.ToString("N"); }
}
// Only equatable for the sake of testing; that's not a requirement of the serialization code.
[FirestoreData(ConverterType = typeof(CustomPlayerConverter))]
public class CustomPlayer : IEquatable<CustomPlayer> {
public string Name { get; set; }
public int Score { get; set; }
public override int GetHashCode() { return Name.GetHashCode() ^ Score; }
public override bool Equals(object obj) { return Equals(obj as CustomPlayer); }
public bool Equals(CustomPlayer other) { return other != null && other.Name == Name && other.Score == Score; }
}
public class CustomPlayerConverter : FirestoreConverter<CustomPlayer> {
public override CustomPlayer FromFirestore(object value) {
var map = (IDictionary<string, object>)value;
return new CustomPlayer {
Name = (string)map["PlayerName"],
// Unbox to long, then convert to int.
Score = (int)(long)map["PlayerScore"]
};
}
public override object ToFirestore(CustomPlayer value) {
return new Dictionary<string, object>
{
{ "PlayerName", value.Name },
{ "PlayerScore", value.Score }
};
}
}
[FirestoreData(ConverterType = typeof(CustomValueTypeConverter))]
internal struct CustomValueType : IEquatable<CustomValueType> {
public readonly string Name;
public readonly int Value;
public CustomValueType(string name, int value) {
Name = name;
Value = value;
}
public override int GetHashCode() { return Name.GetHashCode() + Value; }
public override bool Equals(object obj) { return obj is CustomValueType && Equals((CustomValueType)obj); }
public bool Equals(CustomValueType other) { return Name == other.Name && Value == other.Value; }
public override string ToString() { return String.Format("CustomValueType: {0}", new { Name, Value }); }
}
internal class CustomValueTypeConverter : FirestoreConverter<CustomValueType> {
public override CustomValueType FromFirestore(object value) {
var dictionary = (IDictionary<string, object>)value;
return new CustomValueType(
(string)dictionary["Name"],
(int)(long)dictionary["Value"]
);
}
public override object ToFirestore(CustomValueType value) {
return new Dictionary<string, object>
{
{ "Name", value.Name },
{ "Value", value.Value }
};
}
}
[FirestoreData]
internal struct StructModel : IEquatable<StructModel> {
[FirestoreProperty]
public string Name { get; set; }
[FirestoreProperty]
public int Value { get; set; }
public override int GetHashCode() { return Name.GetHashCode() + Value; }
public override bool Equals(object obj) { return obj is StructModel && Equals((StructModel)obj); }
public bool Equals(StructModel other) { return Name == other.Name && Value == other.Value; }
public override string ToString() { return String.Format("StructModel: {0}", new { Name, Value }); }
}
}
}
| |
//
// AuthenticodeDeformatter.cs: Authenticode signature validator
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2006 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.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Cryptography;
using Mono.Security.Cryptography;
using Mono.Security.X509;
namespace Mono.Security.Authenticode {
// References:
// a. http://www.cs.auckland.ac.nz/~pgut001/pubs/authenticode.txt
#if INSIDE_CORLIB
internal
#else
public
#endif
class AuthenticodeDeformatter : AuthenticodeBase {
private string filename;
private byte[] hash;
private X509CertificateCollection coll;
private ASN1 signedHash;
private DateTime timestamp;
private X509Certificate signingCertificate;
private int reason;
private bool trustedRoot;
private bool trustedTimestampRoot;
private byte[] entry;
private X509Chain signerChain;
private X509Chain timestampChain;
public AuthenticodeDeformatter () : base ()
{
reason = -1;
signerChain = new X509Chain ();
timestampChain = new X509Chain ();
}
public AuthenticodeDeformatter (string fileName) : this ()
{
FileName = fileName;
}
public string FileName {
get { return filename; }
set {
Reset ();
try {
CheckSignature (value);
}
catch (SecurityException) {
throw;
}
catch (Exception) {
reason = 1;
}
}
}
public byte[] Hash {
get {
if (signedHash == null)
return null;
return (byte[]) signedHash.Value.Clone ();
}
}
public int Reason {
get {
if (reason == -1)
IsTrusted ();
return reason;
}
}
public bool IsTrusted ()
{
if (entry == null) {
reason = 1;
return false;
}
if (signingCertificate == null) {
reason = 7;
return false;
}
if ((signerChain.Root == null) || !trustedRoot) {
reason = 6;
return false;
}
if (timestamp != DateTime.MinValue) {
if ((timestampChain.Root == null) || !trustedTimestampRoot) {
reason = 6;
return false;
}
// check that file was timestamped when certificates were valid
if (!signingCertificate.WasCurrent (Timestamp)) {
reason = 4;
return false;
}
}
else if (!signingCertificate.IsCurrent) {
// signature only valid if the certificate is valid
reason = 8;
return false;
}
if (reason == -1)
reason = 0;
return true;
}
public byte[] Signature {
get {
if (entry == null)
return null;
return (byte[]) entry.Clone ();
}
}
public DateTime Timestamp {
get { return timestamp; }
}
public X509CertificateCollection Certificates {
get { return coll; }
}
public X509Certificate SigningCertificate {
get { return signingCertificate; }
}
private bool CheckSignature (string fileName)
{
filename = fileName;
Open (filename);
entry = GetSecurityEntry ();
if (entry == null) {
// no signature is present
reason = 1;
Close ();
return false;
}
PKCS7.ContentInfo ci = new PKCS7.ContentInfo (entry);
if (ci.ContentType != PKCS7.Oid.signedData) {
Close ();
return false;
}
PKCS7.SignedData sd = new PKCS7.SignedData (ci.Content);
if (sd.ContentInfo.ContentType != spcIndirectDataContext) {
Close ();
return false;
}
coll = sd.Certificates;
ASN1 spc = sd.ContentInfo.Content;
signedHash = spc [0][1][1];
HashAlgorithm ha = null;
switch (signedHash.Length) {
case 16:
ha = HashAlgorithm.Create ("MD5");
hash = GetHash (ha);
break;
case 20:
ha = HashAlgorithm.Create ("SHA1");
hash = GetHash (ha);
break;
default:
reason = 5;
Close ();
return false;
}
Close ();
if (!signedHash.CompareValue (hash)) {
reason = 2;
}
// messageDigest is a hash of spcIndirectDataContext (which includes the file hash)
byte[] spcIDC = spc [0].Value;
ha.Initialize (); // re-using hash instance
byte[] messageDigest = ha.ComputeHash (spcIDC);
bool sign = VerifySignature (sd, messageDigest, ha);
return (sign && (reason == 0));
}
private bool CompareIssuerSerial (string issuer, byte[] serial, X509Certificate x509)
{
if (issuer != x509.IssuerName)
return false;
if (serial.Length != x509.SerialNumber.Length)
return false;
// MS shows the serial number inversed (so is Mono.Security.X509.X509Certificate)
int n = serial.Length;
for (int i=0; i < serial.Length; i++) {
if (serial [i] != x509.SerialNumber [--n])
return false;
}
// must be true
return true;
}
//private bool VerifySignature (ASN1 cs, byte[] calculatedMessageDigest, string hashName)
private bool VerifySignature (PKCS7.SignedData sd, byte[] calculatedMessageDigest, HashAlgorithm ha)
{
string contentType = null;
ASN1 messageDigest = null;
// string spcStatementType = null;
// string spcSpOpusInfo = null;
for (int i=0; i < sd.SignerInfo.AuthenticatedAttributes.Count; i++) {
ASN1 attr = (ASN1) sd.SignerInfo.AuthenticatedAttributes [i];
string oid = ASN1Convert.ToOid (attr[0]);
switch (oid) {
case "1.2.840.113549.1.9.3":
// contentType
contentType = ASN1Convert.ToOid (attr[1][0]);
break;
case "1.2.840.113549.1.9.4":
// messageDigest
messageDigest = attr[1][0];
break;
case "1.3.6.1.4.1.311.2.1.11":
// spcStatementType (Microsoft code signing)
// possible values
// - individualCodeSigning (1 3 6 1 4 1 311 2 1 21)
// - commercialCodeSigning (1 3 6 1 4 1 311 2 1 22)
// spcStatementType = ASN1Convert.ToOid (attr[1][0][0]);
break;
case "1.3.6.1.4.1.311.2.1.12":
// spcSpOpusInfo (Microsoft code signing)
/* try {
spcSpOpusInfo = System.Text.Encoding.UTF8.GetString (attr[1][0][0][0].Value);
}
catch (NullReferenceException) {
spcSpOpusInfo = null;
}*/
break;
default:
break;
}
}
if (contentType != spcIndirectDataContext)
return false;
// verify message digest
if (messageDigest == null)
return false;
if (!messageDigest.CompareValue (calculatedMessageDigest))
return false;
// verify signature
string hashOID = CryptoConfig.MapNameToOID (ha.ToString ());
// change to SET OF (not [0]) as per PKCS #7 1.5
ASN1 aa = new ASN1 (0x31);
foreach (ASN1 a in sd.SignerInfo.AuthenticatedAttributes)
aa.Add (a);
ha.Initialize ();
byte[] p7hash = ha.ComputeHash (aa.GetBytes ());
byte[] signature = sd.SignerInfo.Signature;
// we need to find the specified certificate
string issuer = sd.SignerInfo.IssuerName;
byte[] serial = sd.SignerInfo.SerialNumber;
foreach (X509Certificate x509 in coll) {
if (CompareIssuerSerial (issuer, serial, x509)) {
// don't verify is key size don't match
if (x509.PublicKey.Length > (signature.Length >> 3)) {
// return the signing certificate even if the signature isn't correct
// (required behaviour for 2.0 support)
signingCertificate = x509;
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider) x509.RSA;
if (rsa.VerifyHash (p7hash, hashOID, signature)) {
signerChain.LoadCertificates (coll);
trustedRoot = signerChain.Build (x509);
break;
}
}
}
}
// timestamp signature is optional
if (sd.SignerInfo.UnauthenticatedAttributes.Count == 0) {
trustedTimestampRoot = true;
} else {
for (int i = 0; i < sd.SignerInfo.UnauthenticatedAttributes.Count; i++) {
ASN1 attr = (ASN1) sd.SignerInfo.UnauthenticatedAttributes[i];
string oid = ASN1Convert.ToOid (attr[0]);
switch (oid) {
case PKCS7.Oid.countersignature:
// SEQUENCE {
// OBJECT IDENTIFIER
// countersignature (1 2 840 113549 1 9 6)
// SET {
PKCS7.SignerInfo cs = new PKCS7.SignerInfo (attr[1]);
trustedTimestampRoot = VerifyCounterSignature (cs, signature);
break;
default:
// we don't support other unauthenticated attributes
break;
}
}
}
return (trustedRoot && trustedTimestampRoot);
}
private bool VerifyCounterSignature (PKCS7.SignerInfo cs, byte[] signature)
{
// SEQUENCE {
// INTEGER 1
if (cs.Version != 1)
return false;
// SEQUENCE {
// SEQUENCE {
string contentType = null;
ASN1 messageDigest = null;
for (int i=0; i < cs.AuthenticatedAttributes.Count; i++) {
// SEQUENCE {
// OBJECT IDENTIFIER
ASN1 attr = (ASN1) cs.AuthenticatedAttributes [i];
string oid = ASN1Convert.ToOid (attr[0]);
switch (oid) {
case "1.2.840.113549.1.9.3":
// contentType
contentType = ASN1Convert.ToOid (attr[1][0]);
break;
case "1.2.840.113549.1.9.4":
// messageDigest
messageDigest = attr[1][0];
break;
case "1.2.840.113549.1.9.5":
// SEQUENCE {
// OBJECT IDENTIFIER
// signingTime (1 2 840 113549 1 9 5)
// SET {
// UTCTime '030124013651Z'
// }
// }
timestamp = ASN1Convert.ToDateTime (attr[1][0]);
break;
default:
break;
}
}
if (contentType != PKCS7.Oid.data)
return false;
// verify message digest
if (messageDigest == null)
return false;
// TODO: must be read from the ASN.1 structure
string hashName = null;
switch (messageDigest.Length) {
case 16:
hashName = "MD5";
break;
case 20:
hashName = "SHA1";
break;
}
HashAlgorithm ha = HashAlgorithm.Create (hashName);
if (!messageDigest.CompareValue (ha.ComputeHash (signature)))
return false;
// verify signature
byte[] counterSignature = cs.Signature;
// change to SET OF (not [0]) as per PKCS #7 1.5
ASN1 aa = new ASN1 (0x31);
foreach (ASN1 a in cs.AuthenticatedAttributes)
aa.Add (a);
byte[] p7hash = ha.ComputeHash (aa.GetBytes ());
// we need to try all certificates
string issuer = cs.IssuerName;
byte[] serial = cs.SerialNumber;
foreach (X509Certificate x509 in coll) {
if (CompareIssuerSerial (issuer, serial, x509)) {
if (x509.PublicKey.Length > counterSignature.Length) {
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider) x509.RSA;
// we need to HACK around bad (PKCS#1 1.5) signatures made by Verisign Timestamp Service
// and this means copying stuff into our own RSAManaged to get the required flexibility
RSAManaged rsam = new RSAManaged ();
rsam.ImportParameters (rsa.ExportParameters (false));
if (PKCS1.Verify_v15 (rsam, ha, p7hash, counterSignature, true)) {
timestampChain.LoadCertificates (coll);
return (timestampChain.Build (x509));
}
}
}
}
// no certificate can verify this signature!
return false;
}
private void Reset ()
{
filename = null;
entry = null;
hash = null;
signedHash = null;
signingCertificate = null;
reason = -1;
trustedRoot = false;
trustedTimestampRoot = false;
signerChain.Reset ();
timestampChain.Reset ();
timestamp = DateTime.MinValue;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PcapDotNet.Packets.Ethernet;
using PcapDotNet.Packets.Gre;
using PcapDotNet.Packets.Icmp;
using PcapDotNet.Packets.IpV4;
using PcapDotNet.Packets.TestUtils;
using PcapDotNet.TestUtils;
namespace PcapDotNet.Packets.Test
{
/// <summary>
/// Summary description for GreTests
/// </summary>
[TestClass]
[ExcludeFromCodeCoverage]
public class GreTests
{
/// <summary>
/// Gets or sets the test context which provides
/// information about and functionality for the current test run.
/// </summary>
public TestContext TestContext { get; set; }
#region Additional test attributes
//
// You can use the following additional attributes as you write your tests:
//
// Use ClassInitialize to run code before running the first test in the class
// [ClassInitialize()]
// public static void MyClassInitialize(TestContext testContext) { }
//
// Use ClassCleanup to run code after all tests in a class have run
// [ClassCleanup()]
// public static void MyClassCleanup() { }
//
// Use TestInitialize to run code before running each test
// [TestInitialize()]
// public void MyTestInitialize() { }
//
// Use TestCleanup to run code after each test has run
// [TestCleanup()]
// public void MyTestCleanup() { }
//
#endregion
[TestMethod]
public void RandomGreTest()
{
EthernetLayer ethernetLayer = new EthernetLayer
{
Source = new MacAddress("00:01:02:03:04:05"),
Destination = new MacAddress("A0:A1:A2:A3:A4:A5")
};
int seed = new Random().Next();
Console.WriteLine("Seed: " + seed);
Random random = new Random(seed);
for (int i = 0; i != 200; ++i)
{
IpV4Layer ipV4Layer = random.NextIpV4Layer(null);
ipV4Layer.HeaderChecksum = null;
Layer ipLayer = random.NextBool() ? (Layer)ipV4Layer : random.NextIpV6Layer(IpV4Protocol.Gre, false);
GreLayer greLayer = random.NextGreLayer();
PayloadLayer payloadLayer = random.NextPayloadLayer(random.Next(100));
PacketBuilder packetBuilder = new PacketBuilder(ethernetLayer, ipLayer, greLayer, payloadLayer);
Packet packet = packetBuilder.Build(DateTime.Now);
if (greLayer.Checksum == null &&
!new[] { EthernetType.IpV4, EthernetType.IpV6, EthernetType.Arp, EthernetType.VLanTaggedFrame }.Contains(packet.Ethernet.Ip.Gre.ProtocolType))
{
Assert.IsTrue(packet.IsValid, "IsValid, ProtocolType=" + packet.Ethernet.Ip.Gre.ProtocolType);
}
// Ethernet
ethernetLayer.EtherType = ipLayer == ipV4Layer ? EthernetType.IpV4 : EthernetType.IpV6;
Assert.AreEqual(ethernetLayer, packet.Ethernet.ExtractLayer(), "Ethernet Layer");
ethernetLayer.EtherType = EthernetType.None;
// IP.
if (ipLayer == ipV4Layer)
{
// IPv4.
ipV4Layer.Protocol = IpV4Protocol.Gre;
ipV4Layer.HeaderChecksum = ((IpV4Layer)packet.Ethernet.Ip.ExtractLayer()).HeaderChecksum;
Assert.AreEqual(ipV4Layer, packet.Ethernet.Ip.ExtractLayer());
ipV4Layer.HeaderChecksum = null;
Assert.AreEqual(ipV4Layer.Length, packet.Ethernet.IpV4.HeaderLength);
Assert.IsTrue(packet.Ethernet.IpV4.IsHeaderChecksumCorrect);
Assert.AreEqual(ipV4Layer.Length + greLayer.Length + payloadLayer.Length,
packet.Ethernet.Ip.TotalLength);
Assert.AreEqual(IpV4Datagram.DefaultVersion, packet.Ethernet.Ip.Version);
}
else
{
// IPv6.
Assert.AreEqual(ipLayer, packet.Ethernet.Ip.ExtractLayer());
}
// GRE
GreDatagram actualGre = packet.Ethernet.Ip.Gre;
GreLayer actualGreLayer = (GreLayer)actualGre.ExtractLayer();
if (greLayer.ChecksumPresent && greLayer.Checksum == null)
{
Assert.IsTrue(actualGre.IsChecksumCorrect);
greLayer.Checksum = actualGre.Checksum;
}
Assert.AreEqual(greLayer, actualGreLayer, "Layer");
if (actualGreLayer.Key != null)
actualGreLayer.SetKey(actualGreLayer.KeyPayloadLength.Value, actualGreLayer.KeyCallId.Value);
else
{
Assert.IsNull(actualGreLayer.KeyPayloadLength);
Assert.IsNull(actualGreLayer.KeyCallId);
}
Assert.AreEqual(greLayer, actualGreLayer, "Layer");
if (actualGre.KeyPresent)
{
Assert.AreEqual(greLayer.KeyPayloadLength, actualGre.KeyPayloadLength, "KeyPayloadLength");
Assert.AreEqual(greLayer.KeyCallId, actualGre.KeyCallId, "KeyCallId");
}
Assert.AreNotEqual(random.NextGreLayer(), actualGreLayer, "Not Layer");
Assert.AreEqual(greLayer.Length, actualGre.HeaderLength);
Assert.IsTrue(actualGre.KeyPresent ^ (greLayer.Key == null));
MoreAssert.IsSmaller(8, actualGre.RecursionControl);
MoreAssert.IsSmaller(32, actualGre.FutureUseBits);
Assert.IsTrue(actualGre.RoutingPresent ^ (greLayer.Routing == null && greLayer.RoutingOffset == null));
Assert.IsTrue(actualGre.SequenceNumberPresent ^ (greLayer.SequenceNumber == null));
Assert.IsTrue(!actualGre.StrictSourceRoute || actualGre.RoutingPresent);
if (actualGre.RoutingPresent)
{
Assert.IsNotNull(actualGre.ActiveSourceRouteEntryIndex);
if (actualGre.ActiveSourceRouteEntryIndex < actualGre.Routing.Count)
Assert.IsNotNull(actualGre.ActiveSourceRouteEntry);
foreach (GreSourceRouteEntry entry in actualGre.Routing)
{
Assert.AreNotEqual(entry, 2);
Assert.AreEqual(entry.GetHashCode(), entry.GetHashCode());
switch (entry.AddressFamily)
{
case GreSourceRouteEntryAddressFamily.AsSourceRoute:
GreSourceRouteEntryAs asEntry = (GreSourceRouteEntryAs)entry;
MoreAssert.IsInRange(0, asEntry.AsNumbers.Count, asEntry.NextAsNumberIndex);
if (asEntry.NextAsNumberIndex != asEntry.AsNumbers.Count)
Assert.AreEqual(asEntry.AsNumbers[asEntry.NextAsNumberIndex], asEntry.NextAsNumber);
break;
case GreSourceRouteEntryAddressFamily.IpSourceRoute:
GreSourceRouteEntryIp ipEntry = (GreSourceRouteEntryIp)entry;
MoreAssert.IsInRange(0, ipEntry.Addresses.Count, ipEntry.NextAddressIndex);
if (ipEntry.NextAddressIndex != ipEntry.Addresses.Count)
Assert.AreEqual(ipEntry.Addresses[ipEntry.NextAddressIndex], ipEntry.NextAddress);
break;
default:
GreSourceRouteEntryUnknown unknownEntry = (GreSourceRouteEntryUnknown)entry;
MoreAssert.IsInRange(0, unknownEntry.Data.Length, unknownEntry.PayloadOffset);
break;
}
}
}
else
{
Assert.IsNull(actualGre.ActiveSourceRouteEntry);
}
Assert.IsNotNull(actualGre.Payload);
switch (actualGre.ProtocolType)
{
case EthernetType.IpV4:
Assert.IsNotNull(actualGre.IpV4);
break;
case EthernetType.Arp:
Assert.IsNotNull(actualGre.Arp);
break;
}
}
}
[TestMethod]
public void GreAutomaticProtocolType()
{
Packet packet = PacketBuilder.Build(DateTime.Now, new EthernetLayer(), new IpV4Layer(), new GreLayer(), new IpV4Layer(), new IcmpEchoLayer());
Assert.IsTrue(packet.IsValid);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException), AllowDerivedTypes = false)]
public void GreAutomaticProtocolTypeNoNextLayer()
{
Packet packet = PacketBuilder.Build(DateTime.Now, new EthernetLayer(), new IpV4Layer(), new GreLayer());
Assert.IsTrue(packet.IsValid);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException), AllowDerivedTypes = false)]
public void GreAutomaticProtocolTypeBadNextLayer()
{
Packet packet = PacketBuilder.Build(DateTime.Now, new EthernetLayer(), new IpV4Layer(), new GreLayer(), new PayloadLayer());
Assert.IsTrue(packet.IsValid);
}
[TestMethod]
public void InvalidGreTest()
{
EthernetLayer ethernetLayer = new EthernetLayer
{
Source = new MacAddress("00:01:02:03:04:05"),
Destination = new MacAddress("A0:A1:A2:A3:A4:A5")
};
int seed = new Random().Next();
Console.WriteLine("Seed: " + seed);
Random random = new Random(seed);
for (int i = 0; i != 100; ++i)
{
IpV4Layer ipV4Layer = random.NextIpV4Layer(IpV4Protocol.Gre);
ipV4Layer.HeaderChecksum = null;
Layer ipLayer = random.NextBool() ? (Layer)ipV4Layer : random.NextIpV6Layer(IpV4Protocol.Gre, false);
GreLayer greLayer = random.NextGreLayer();
greLayer.Checksum = null;
greLayer.Routing = new List<GreSourceRouteEntry>
{
new GreSourceRouteEntryAs(new List<ushort> {123}.AsReadOnly(), 0),
new GreSourceRouteEntryIp(new List<IpV4Address> {random.NextIpV4Address()}.AsReadOnly(),
0)
}.AsReadOnly();
PacketBuilder packetBuilder = new PacketBuilder(ethernetLayer, ipLayer, greLayer);
Packet packet = packetBuilder.Build(DateTime.Now);
Assert.IsTrue(packet.IsValid ||
new[] { EthernetType.IpV4, EthernetType.IpV6, EthernetType.Arp, EthernetType.VLanTaggedFrame }.Contains(greLayer.ProtocolType),
"IsValid. ProtoclType=" + greLayer.ProtocolType);
GreDatagram gre = packet.Ethernet.Ip.Gre;
// Remove a byte from routing
Datagram newIpPayload = new Datagram(gre.Take(gre.Length - 1).ToArray());
packetBuilder = new PacketBuilder(ethernetLayer, ipLayer, new PayloadLayer {Data = newIpPayload});
packet = packetBuilder.Build(DateTime.Now);
Assert.IsNull(packet.Ethernet.Ip.Gre.Payload);
Assert.IsFalse(packet.IsValid);
// SreLength is too big
byte[] buffer = gre.ToArray();
buffer[buffer.Length - 1] = 200;
newIpPayload = new Datagram(buffer);
packetBuilder = new PacketBuilder(ethernetLayer, ipLayer, new PayloadLayer {Data = newIpPayload});
packet = packetBuilder.Build(DateTime.Now);
Assert.IsFalse(packet.IsValid);
// PayloadOffset is too big
buffer = gre.ToArray();
buffer[gre.Length - 10] = 100;
newIpPayload = new Datagram(buffer);
packetBuilder = new PacketBuilder(ethernetLayer, ipLayer, new PayloadLayer {Data = newIpPayload});
packet = packetBuilder.Build(DateTime.Now);
Assert.IsFalse(packet.IsValid);
// PayloadOffset isn't aligned to ip
buffer = gre.ToArray();
buffer[gre.Length - 10] = 3;
newIpPayload = new Datagram(buffer);
packetBuilder = new PacketBuilder(ethernetLayer, ipLayer, new PayloadLayer {Data = newIpPayload});
packet = packetBuilder.Build(DateTime.Now);
Assert.IsFalse(packet.IsValid);
// PayloadOffset isn't aligned to as
buffer = gre.ToArray();
buffer[gre.Length - 16] = 1;
newIpPayload = new Datagram(buffer);
packetBuilder = new PacketBuilder(ethernetLayer, ipLayer, new PayloadLayer {Data = newIpPayload});
packet = packetBuilder.Build(DateTime.Now);
Assert.IsFalse(packet.IsValid);
}
}
}
}
| |
namespace Humidifier.MediaLive
{
using System.Collections.Generic;
using ChannelTypes;
public class Channel : Humidifier.Resource
{
public static class Attributes
{
public static string Arn = "Arn" ;
public static string Inputs = "Inputs" ;
}
public override string AWSTypeName
{
get
{
return @"AWS::MediaLive::Channel";
}
}
/// <summary>
/// InputAttachments
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-channel.html#cfn-medialive-channel-inputattachments
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// ItemType: InputAttachment
/// </summary>
public List<InputAttachment> InputAttachments
{
get;
set;
}
/// <summary>
/// InputSpecification
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-channel.html#cfn-medialive-channel-inputspecification
/// Required: False
/// UpdateType: Mutable
/// Type: InputSpecification
/// </summary>
public InputSpecification InputSpecification
{
get;
set;
}
/// <summary>
/// ChannelClass
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-channel.html#cfn-medialive-channel-channelclass
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic ChannelClass
{
get;
set;
}
/// <summary>
/// EncoderSettings
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-channel.html#cfn-medialive-channel-encodersettings
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Json
/// </summary>
public dynamic EncoderSettings
{
get;
set;
}
/// <summary>
/// Destinations
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-channel.html#cfn-medialive-channel-destinations
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// ItemType: OutputDestination
/// </summary>
public List<OutputDestination> Destinations
{
get;
set;
}
/// <summary>
/// LogLevel
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-channel.html#cfn-medialive-channel-loglevel
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic LogLevel
{
get;
set;
}
/// <summary>
/// RoleArn
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-channel.html#cfn-medialive-channel-rolearn
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic RoleArn
{
get;
set;
}
/// <summary>
/// Tags
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-channel.html#cfn-medialive-channel-tags
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Json
/// </summary>
public dynamic Tags
{
get;
set;
}
/// <summary>
/// Name
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-channel.html#cfn-medialive-channel-name
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Name
{
get;
set;
}
}
namespace ChannelTypes
{
public class MediaPackageOutputDestinationSettings
{
/// <summary>
/// ChannelId
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-mediapackageoutputdestinationsettings.html#cfn-medialive-channel-mediapackageoutputdestinationsettings-channelid
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic ChannelId
{
get;
set;
}
}
public class HlsInputSettings
{
/// <summary>
/// BufferSegments
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-hlsinputsettings.html#cfn-medialive-channel-hlsinputsettings-buffersegments
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic BufferSegments
{
get;
set;
}
/// <summary>
/// Retries
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-hlsinputsettings.html#cfn-medialive-channel-hlsinputsettings-retries
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic Retries
{
get;
set;
}
/// <summary>
/// Bandwidth
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-hlsinputsettings.html#cfn-medialive-channel-hlsinputsettings-bandwidth
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic Bandwidth
{
get;
set;
}
/// <summary>
/// RetryInterval
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-hlsinputsettings.html#cfn-medialive-channel-hlsinputsettings-retryinterval
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic RetryInterval
{
get;
set;
}
}
public class VideoSelectorProgramId
{
/// <summary>
/// ProgramId
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-videoselectorprogramid.html#cfn-medialive-channel-videoselectorprogramid-programid
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic ProgramId
{
get;
set;
}
}
public class InputAttachment
{
/// <summary>
/// InputAttachmentName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-inputattachment.html#cfn-medialive-channel-inputattachment-inputattachmentname
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic InputAttachmentName
{
get;
set;
}
/// <summary>
/// InputId
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-inputattachment.html#cfn-medialive-channel-inputattachment-inputid
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic InputId
{
get;
set;
}
/// <summary>
/// InputSettings
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-inputattachment.html#cfn-medialive-channel-inputattachment-inputsettings
/// Required: False
/// UpdateType: Mutable
/// Type: InputSettings
/// </summary>
public InputSettings InputSettings
{
get;
set;
}
}
public class MultiplexProgramChannelDestinationSettings
{
/// <summary>
/// MultiplexId
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-multiplexprogramchanneldestinationsettings.html#cfn-medialive-channel-multiplexprogramchanneldestinationsettings-multiplexid
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic MultiplexId
{
get;
set;
}
/// <summary>
/// ProgramName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-multiplexprogramchanneldestinationsettings.html#cfn-medialive-channel-multiplexprogramchanneldestinationsettings-programname
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic ProgramName
{
get;
set;
}
}
public class EmbeddedSourceSettings
{
/// <summary>
/// Source608ChannelNumber
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-embeddedsourcesettings.html#cfn-medialive-channel-embeddedsourcesettings-source608channelnumber
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic Source608ChannelNumber
{
get;
set;
}
/// <summary>
/// Scte20Detection
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-embeddedsourcesettings.html#cfn-medialive-channel-embeddedsourcesettings-scte20detection
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Scte20Detection
{
get;
set;
}
/// <summary>
/// Source608TrackNumber
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-embeddedsourcesettings.html#cfn-medialive-channel-embeddedsourcesettings-source608tracknumber
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic Source608TrackNumber
{
get;
set;
}
/// <summary>
/// Convert608To708
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-embeddedsourcesettings.html#cfn-medialive-channel-embeddedsourcesettings-convert608to708
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Convert608To708
{
get;
set;
}
}
public class InputSpecification
{
/// <summary>
/// Codec
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-inputspecification.html#cfn-medialive-channel-inputspecification-codec
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Codec
{
get;
set;
}
/// <summary>
/// MaximumBitrate
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-inputspecification.html#cfn-medialive-channel-inputspecification-maximumbitrate
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic MaximumBitrate
{
get;
set;
}
/// <summary>
/// Resolution
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-inputspecification.html#cfn-medialive-channel-inputspecification-resolution
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Resolution
{
get;
set;
}
}
public class Scte27SourceSettings
{
/// <summary>
/// Pid
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-scte27sourcesettings.html#cfn-medialive-channel-scte27sourcesettings-pid
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic Pid
{
get;
set;
}
}
public class VideoSelectorPid
{
/// <summary>
/// Pid
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-videoselectorpid.html#cfn-medialive-channel-videoselectorpid-pid
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic Pid
{
get;
set;
}
}
public class InputSettings
{
/// <summary>
/// DeblockFilter
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-inputsettings.html#cfn-medialive-channel-inputsettings-deblockfilter
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic DeblockFilter
{
get;
set;
}
/// <summary>
/// FilterStrength
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-inputsettings.html#cfn-medialive-channel-inputsettings-filterstrength
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic FilterStrength
{
get;
set;
}
/// <summary>
/// InputFilter
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-inputsettings.html#cfn-medialive-channel-inputsettings-inputfilter
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic InputFilter
{
get;
set;
}
/// <summary>
/// SourceEndBehavior
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-inputsettings.html#cfn-medialive-channel-inputsettings-sourceendbehavior
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic SourceEndBehavior
{
get;
set;
}
/// <summary>
/// VideoSelector
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-inputsettings.html#cfn-medialive-channel-inputsettings-videoselector
/// Required: False
/// UpdateType: Mutable
/// Type: VideoSelector
/// </summary>
public VideoSelector VideoSelector
{
get;
set;
}
/// <summary>
/// AudioSelectors
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-inputsettings.html#cfn-medialive-channel-inputsettings-audioselectors
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// ItemType: AudioSelector
/// </summary>
public List<AudioSelector> AudioSelectors
{
get;
set;
}
/// <summary>
/// CaptionSelectors
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-inputsettings.html#cfn-medialive-channel-inputsettings-captionselectors
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// ItemType: CaptionSelector
/// </summary>
public List<CaptionSelector> CaptionSelectors
{
get;
set;
}
/// <summary>
/// DenoiseFilter
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-inputsettings.html#cfn-medialive-channel-inputsettings-denoisefilter
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic DenoiseFilter
{
get;
set;
}
/// <summary>
/// NetworkInputSettings
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-inputsettings.html#cfn-medialive-channel-inputsettings-networkinputsettings
/// Required: False
/// UpdateType: Mutable
/// Type: NetworkInputSettings
/// </summary>
public NetworkInputSettings NetworkInputSettings
{
get;
set;
}
}
public class AudioSelector
{
/// <summary>
/// SelectorSettings
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-audioselector.html#cfn-medialive-channel-audioselector-selectorsettings
/// Required: False
/// UpdateType: Mutable
/// Type: AudioSelectorSettings
/// </summary>
public AudioSelectorSettings SelectorSettings
{
get;
set;
}
/// <summary>
/// Name
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-audioselector.html#cfn-medialive-channel-audioselector-name
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Name
{
get;
set;
}
}
public class AudioLanguageSelection
{
/// <summary>
/// LanguageCode
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-audiolanguageselection.html#cfn-medialive-channel-audiolanguageselection-languagecode
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic LanguageCode
{
get;
set;
}
/// <summary>
/// LanguageSelectionPolicy
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-audiolanguageselection.html#cfn-medialive-channel-audiolanguageselection-languageselectionpolicy
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic LanguageSelectionPolicy
{
get;
set;
}
}
public class AribSourceSettings
{
}
public class AudioPidSelection
{
/// <summary>
/// Pid
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-audiopidselection.html#cfn-medialive-channel-audiopidselection-pid
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic Pid
{
get;
set;
}
}
public class DvbSubSourceSettings
{
/// <summary>
/// Pid
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-dvbsubsourcesettings.html#cfn-medialive-channel-dvbsubsourcesettings-pid
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic Pid
{
get;
set;
}
}
public class CaptionSelectorSettings
{
/// <summary>
/// DvbSubSourceSettings
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-captionselectorsettings.html#cfn-medialive-channel-captionselectorsettings-dvbsubsourcesettings
/// Required: False
/// UpdateType: Mutable
/// Type: DvbSubSourceSettings
/// </summary>
public DvbSubSourceSettings DvbSubSourceSettings
{
get;
set;
}
/// <summary>
/// Scte27SourceSettings
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-captionselectorsettings.html#cfn-medialive-channel-captionselectorsettings-scte27sourcesettings
/// Required: False
/// UpdateType: Mutable
/// Type: Scte27SourceSettings
/// </summary>
public Scte27SourceSettings Scte27SourceSettings
{
get;
set;
}
/// <summary>
/// AribSourceSettings
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-captionselectorsettings.html#cfn-medialive-channel-captionselectorsettings-aribsourcesettings
/// Required: False
/// UpdateType: Mutable
/// Type: AribSourceSettings
/// </summary>
public AribSourceSettings AribSourceSettings
{
get;
set;
}
/// <summary>
/// EmbeddedSourceSettings
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-captionselectorsettings.html#cfn-medialive-channel-captionselectorsettings-embeddedsourcesettings
/// Required: False
/// UpdateType: Mutable
/// Type: EmbeddedSourceSettings
/// </summary>
public EmbeddedSourceSettings EmbeddedSourceSettings
{
get;
set;
}
/// <summary>
/// Scte20SourceSettings
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-captionselectorsettings.html#cfn-medialive-channel-captionselectorsettings-scte20sourcesettings
/// Required: False
/// UpdateType: Mutable
/// Type: Scte20SourceSettings
/// </summary>
public Scte20SourceSettings Scte20SourceSettings
{
get;
set;
}
/// <summary>
/// TeletextSourceSettings
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-captionselectorsettings.html#cfn-medialive-channel-captionselectorsettings-teletextsourcesettings
/// Required: False
/// UpdateType: Mutable
/// Type: TeletextSourceSettings
/// </summary>
public TeletextSourceSettings TeletextSourceSettings
{
get;
set;
}
}
public class VideoSelectorSettings
{
/// <summary>
/// VideoSelectorProgramId
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-videoselectorsettings.html#cfn-medialive-channel-videoselectorsettings-videoselectorprogramid
/// Required: False
/// UpdateType: Mutable
/// Type: VideoSelectorProgramId
/// </summary>
public VideoSelectorProgramId VideoSelectorProgramId
{
get;
set;
}
/// <summary>
/// VideoSelectorPid
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-videoselectorsettings.html#cfn-medialive-channel-videoselectorsettings-videoselectorpid
/// Required: False
/// UpdateType: Mutable
/// Type: VideoSelectorPid
/// </summary>
public VideoSelectorPid VideoSelectorPid
{
get;
set;
}
}
public class TeletextSourceSettings
{
/// <summary>
/// PageNumber
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-teletextsourcesettings.html#cfn-medialive-channel-teletextsourcesettings-pagenumber
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic PageNumber
{
get;
set;
}
}
public class NetworkInputSettings
{
/// <summary>
/// ServerValidation
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-networkinputsettings.html#cfn-medialive-channel-networkinputsettings-servervalidation
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic ServerValidation
{
get;
set;
}
/// <summary>
/// HlsInputSettings
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-networkinputsettings.html#cfn-medialive-channel-networkinputsettings-hlsinputsettings
/// Required: False
/// UpdateType: Mutable
/// Type: HlsInputSettings
/// </summary>
public HlsInputSettings HlsInputSettings
{
get;
set;
}
}
public class Scte20SourceSettings
{
/// <summary>
/// Source608ChannelNumber
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-scte20sourcesettings.html#cfn-medialive-channel-scte20sourcesettings-source608channelnumber
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic Source608ChannelNumber
{
get;
set;
}
/// <summary>
/// Convert608To708
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-scte20sourcesettings.html#cfn-medialive-channel-scte20sourcesettings-convert608to708
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Convert608To708
{
get;
set;
}
}
public class AudioSelectorSettings
{
/// <summary>
/// AudioPidSelection
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-audioselectorsettings.html#cfn-medialive-channel-audioselectorsettings-audiopidselection
/// Required: False
/// UpdateType: Mutable
/// Type: AudioPidSelection
/// </summary>
public AudioPidSelection AudioPidSelection
{
get;
set;
}
/// <summary>
/// AudioLanguageSelection
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-audioselectorsettings.html#cfn-medialive-channel-audioselectorsettings-audiolanguageselection
/// Required: False
/// UpdateType: Mutable
/// Type: AudioLanguageSelection
/// </summary>
public AudioLanguageSelection AudioLanguageSelection
{
get;
set;
}
}
public class VideoSelector
{
/// <summary>
/// SelectorSettings
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-videoselector.html#cfn-medialive-channel-videoselector-selectorsettings
/// Required: False
/// UpdateType: Mutable
/// Type: VideoSelectorSettings
/// </summary>
public VideoSelectorSettings SelectorSettings
{
get;
set;
}
/// <summary>
/// ColorSpace
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-videoselector.html#cfn-medialive-channel-videoselector-colorspace
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic ColorSpace
{
get;
set;
}
/// <summary>
/// ColorSpaceUsage
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-videoselector.html#cfn-medialive-channel-videoselector-colorspaceusage
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic ColorSpaceUsage
{
get;
set;
}
}
public class OutputDestinationSettings
{
/// <summary>
/// StreamName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-outputdestinationsettings.html#cfn-medialive-channel-outputdestinationsettings-streamname
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic StreamName
{
get;
set;
}
/// <summary>
/// Username
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-outputdestinationsettings.html#cfn-medialive-channel-outputdestinationsettings-username
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Username
{
get;
set;
}
/// <summary>
/// PasswordParam
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-outputdestinationsettings.html#cfn-medialive-channel-outputdestinationsettings-passwordparam
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic PasswordParam
{
get;
set;
}
/// <summary>
/// Url
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-outputdestinationsettings.html#cfn-medialive-channel-outputdestinationsettings-url
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Url
{
get;
set;
}
}
public class OutputDestination
{
/// <summary>
/// MultiplexSettings
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-outputdestination.html#cfn-medialive-channel-outputdestination-multiplexsettings
/// Required: False
/// UpdateType: Mutable
/// Type: MultiplexProgramChannelDestinationSettings
/// </summary>
public MultiplexProgramChannelDestinationSettings MultiplexSettings
{
get;
set;
}
/// <summary>
/// Id
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-outputdestination.html#cfn-medialive-channel-outputdestination-id
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Id
{
get;
set;
}
/// <summary>
/// Settings
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-outputdestination.html#cfn-medialive-channel-outputdestination-settings
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// ItemType: OutputDestinationSettings
/// </summary>
public List<OutputDestinationSettings> Settings
{
get;
set;
}
/// <summary>
/// MediaPackageSettings
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-outputdestination.html#cfn-medialive-channel-outputdestination-mediapackagesettings
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// ItemType: MediaPackageOutputDestinationSettings
/// </summary>
public List<MediaPackageOutputDestinationSettings> MediaPackageSettings
{
get;
set;
}
}
public class CaptionSelector
{
/// <summary>
/// LanguageCode
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-captionselector.html#cfn-medialive-channel-captionselector-languagecode
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic LanguageCode
{
get;
set;
}
/// <summary>
/// SelectorSettings
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-captionselector.html#cfn-medialive-channel-captionselector-selectorsettings
/// Required: False
/// UpdateType: Mutable
/// Type: CaptionSelectorSettings
/// </summary>
public CaptionSelectorSettings SelectorSettings
{
get;
set;
}
/// <summary>
/// Name
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-captionselector.html#cfn-medialive-channel-captionselector-name
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Name
{
get;
set;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text.RegularExpressions;
namespace Cvv.WebUtility.Net.Dns
{
public enum RecordType
{
None = 0,
A = 1,
NS = 2,
CNAME = 5,
SOA = 6,
MB = 7,
MG = 8,
MR = 9,
NULL = 10,
WKS = 11,
PTR = 12,
HINFO = 13,
MINFO = 14,
MX = 15,
TXT = 16,
RP = 17,
AFSDB = 18,
X25 = 19,
ISDN = 20,
RT = 21,
NSAP = 22,
SIG = 24,
KEY = 25,
PX = 26,
AAAA = 28,
LOC = 29,
SRV = 33,
NAPTR = 35,
KX = 36,
A6 = 38,
DNAME = 39,
DS = 43,
TKEY = 249,
TSIG = 250,
All = 255
};
public enum OpCode
{
StandardQuery = 0,
InverseQuery = 1,
StatusRequest = 2
}
public class DnsQueryException : Exception
{
private Exception[] exceptions;
public DnsQueryException(string msg, Exception[] exs)
: base(msg)
{
exceptions = exs;
}
}
public class DnsQuery
{
const int DNS_PORT = 53;
const int MAX_TRIES = 1;
const byte IN_CLASS = 1;
private byte[] _query;
private string _domain;
private IPEndPoint _dnsServer;
private bool _recursiveQuery = true;
private Socket _reqSocket;
private int _numTries;
private int _reqId;
public DnsQuery() { }
public DnsQuery(string serverUrl)
{
IPHostEntry hostAddress = System.Net.Dns.GetHostEntry(serverUrl);
if (hostAddress.AddressList.Length > 0)
_dnsServer = new IPEndPoint(hostAddress.AddressList[0], DNS_PORT);
else
throw new DnsQueryException("Invalid DNS Server Name Specified", null);
}
public DnsQuery(IPAddress dnsAddress)
{
_dnsServer = new IPEndPoint(dnsAddress, DNS_PORT);
}
public DnsAnswer QueryServer(RecordType recType, int timeout)
{
if (_dnsServer == null)
throw new DnsQueryException("There is no Dns server set in Dns Query Component", null);
if (!ValidRecordType(recType))
throw new DnsQueryException("Invalid Record Type submitted to Dns Query Component", null);
//Result object
DnsAnswer res = null;
//UDP being unreliable we may need to try multiple times
//therefore we count how many times we have tried
_numTries = 0;
//as per RFC 1035 there is a max size on the dns response
byte[] dnsResponse = new byte[512];
Exception[] exceptions = new Exception[MAX_TRIES];
while (_numTries < MAX_TRIES)
{
try
{
CreateDnsQuery(recType);
_reqSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_reqSocket.ReceiveTimeout = timeout;
_reqSocket.SendTo(_query, _query.Length, SocketFlags.None, _dnsServer);
_reqSocket.Receive(dnsResponse);
if (dnsResponse[0] == _query[0] && dnsResponse[1] == _query[1])
//this is our response so format and return the answer to the query
res = new DnsAnswer(dnsResponse);
_numTries++;
if (res.ReturnCode == ReturnCode.Success)
return res;
}
catch (SocketException ex)
{
exceptions[_numTries] = ex;
_numTries++;
_reqId++;
if (_numTries > MAX_TRIES)
throw new DnsQueryException("Failure Querying DNS Server", exceptions);
}
finally
{
_reqId++;
_reqSocket.Close();
Query = null; //Force a new message be built
}
}
return res;
}
public DnsAnswer QueryServer(RecordType recType)
{
return this.QueryServer(recType, 5000);
}
private void CreateDnsQuery(RecordType recType)
{
List<Byte> queryBytes = new List<byte>();
queryBytes.Add((byte)(_reqId >> 8));
queryBytes.Add((byte)(_reqId));
//populate bit fields
queryBytes.Add((byte)(((byte)OpCode.StandardQuery << 3) | ( RecursiveQuery ? 0x01 : 0x00)));
queryBytes.Add(0x00);
//set number of questions we will always use to 1
queryBytes.Add(0x00);
queryBytes.Add(0x01);
//no requests, no name servers, no additional records in standard request
for (int i = 0; i < 6; i++)
queryBytes.Add(0x00);
InsertDomainName(queryBytes, _domain);
//query Type
queryBytes.Add(0x00);
queryBytes.Add((byte)recType);
//query class
queryBytes.Add(0x00);
queryBytes.Add(IN_CLASS);
Query = queryBytes.ToArray();
}
private void InsertDomainName(List<Byte> data, string domain)
{
//Write each segment of the domain name to the array
//Each segment is seperated by a '.' token and each segment is
//preceded by the couint of characters in the segment.
int length = 0;
int pos = 0;
while (pos < domain.Length)
{
int prev_pos = pos;
pos = domain.IndexOf('.', pos);
length = pos - prev_pos;
if (length < 0) //last segment
length = domain.Length - prev_pos;
//Add segment data to array
data.Add((byte)length);
for(int i = 0; i < length; i++)
data.Add((byte)domain[prev_pos++]);
//step past the '.'
pos = prev_pos;
pos++;
//pos++;
}
//Terminate with a zero
data.Add(0x00);
}
private bool ValidRecordType(RecordType t)
{
return (Enum.IsDefined(typeof(RecordType), t) || t == RecordType.All);
}
public byte[] Query
{
get { return _query; }
set { _query = value; }
}
public string Domain
{
get { return _domain; }
set
{
if (value.Length == 0 || value.Length > 255 ||
!Regex.IsMatch(value, @"^[a-z|A-Z|0-9|\-|_]{1,63}(\.[a-z|A-Z|0-9|\-]{1,63})+$"))
throw new DnsQueryException("Invalid Domain Name", null);
_domain = value;
}
}
public IPEndPoint DnsServer
{
get { return _dnsServer; }
set { _dnsServer = value; }
}
public bool RecursiveQuery
{
get { return _recursiveQuery; }
set { _recursiveQuery = value; }
}
public static List<IPAddress> GetMachineDnsServers()
{
List<IPAddress> dnsServers = new List<IPAddress>();
IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties();
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in nics)
{
IPInterfaceProperties properties = adapter.GetIPProperties();
foreach (IPAddress ipAddress in properties.DnsAddresses)
{
dnsServers.Add(ipAddress);
}
}
return dnsServers;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using System;
using System.Reflection;
using System.Collections.Generic;
#pragma warning disable 0414
namespace MethodInfoTests
{
public class Test
{
//Invoke a method using a matching MethodInfo from another/parent class.
[Fact]
public static void TestInvokeMethod1()
{
MethodInfo mi = null;
Co1333_b clsObj = new Co1333_b();
int retVal = -1;
int expectedVal = 0;
mi = getMethod(typeof(Co1333_b), "ReturnTheIntPlus");
retVal = (int)mi.Invoke(clsObj, (Object[])null);
Assert.True(retVal.Equals(expectedVal), String.Format("Failed! MethodInfo.Invoke did not return correct result. Expected {0} , Got {1}", expectedVal, retVal));
}
//Invoke a method using a matching MethodInfo from another/parent class.
[Fact]
public static void TestInvokeMethod2()
{
MethodInfo mi = null;
Co1333_b clsObj = new Co1333_b1();
int retVal = -1;
int expectedVal = 1;
mi = getMethod(typeof(Co1333_b), "ReturnTheIntPlus");
retVal = (int)mi.Invoke(clsObj, (Object[])null);
Assert.True(retVal.Equals(expectedVal), String.Format("Failed! MethodInfo.Invoke did not return correct result. Expected {0} , Got {1}", expectedVal, retVal));
}
// Invoke a method that requires Reflection to box a primitive integer for the invoked method's parm. // Bug 10829
[Fact]
public static void TestInvokeMethod3()
{
MethodInfo mi = null;
Co1333Invoke clsObj = new Co1333Invoke();
string retVal = "";
string expectedVal = "42";
Object[] varParams =
{
(int)42
};
mi = getMethod(typeof(Co1333Invoke), "ConvertI4ObjToString");
retVal = (String)mi.Invoke(clsObj, varParams);
Assert.True(retVal.Equals(expectedVal), String.Format("Failed! MethodInfo.Invoke did not return correct result. Expected {0} , Got {1}", expectedVal, retVal));
}
//Invoke a vanilla method that takes no parms but returns an integer
[Fact]
public static void TestInvokeMethod4()
{
MethodInfo mi = null;
Co1333Invoke clsObj = new Co1333Invoke();
int retVal = 0;
int expectedVal = 3;
mi = getMethod(typeof(Co1333Invoke), "Int4ReturnThree");
retVal = (int)mi.Invoke(clsObj, (Object[])null);
Assert.True(retVal.Equals(expectedVal), String.Format("Failed! MethodInfo.Invoke did not return correct result. Expected {0} , Got {1}", expectedVal, retVal));
}
//Invoke a vanilla method that takes no parms but returns an integer
[Fact]
public static void TestInvokeMethod5()
{
MethodInfo mi = null;
Co1333Invoke clsObj = new Co1333Invoke();
Int64 retVal = 0;
Int64 expectedVal = Int64.MaxValue;
mi = getMethod(typeof(Co1333Invoke), "ReturnLongMax");
retVal = (Int64)mi.Invoke(clsObj, (Object[])null);
Assert.True(retVal.Equals(expectedVal), String.Format("Failed! MethodInfo.Invoke did not return correct result. Expected {0} , Got {1}", expectedVal, retVal));
}
//Invoke a method that has parameters of primative types
[Fact]
public static void TestInvokeMethod6()
{
MethodInfo mi = null;
Co1333Invoke clsObj = new Co1333Invoke();
long retVal = 0;
long expectedVal = 100200L;
Object[] varParams =
{
( 200 ),
( 100000 )
};
mi = getMethod(typeof(Co1333Invoke), "ReturnI8Sum");
retVal = (long)mi.Invoke(clsObj, varParams);
Assert.True(retVal.Equals(expectedVal), String.Format("Failed! MethodInfo.Invoke did not return correct result. Expected {0} , Got {1}", expectedVal, retVal));
}
//Invoke a static method using null , that has parameters of primative types
[Fact]
public static void TestInvokeMethod7()
{
MethodInfo mi = null;
int retVal = 0;
int expectedVal = 110;
Object[] varParams =
{
( 10 ),
( 100 )
};
mi = getMethod(typeof(Co1333Invoke), "ReturnI4Sum");
retVal = (int)mi.Invoke(null, varParams);
Assert.True(retVal.Equals(expectedVal), String.Format("Failed! MethodInfo.Invoke did not return correct result. Expected {0} , Got {1}", expectedVal, retVal));
}
//Invoke a static method using class object , that has parameters of primative types
[Fact]
public static void TestInvokeMethod8()
{
MethodInfo mi = null;
Co1333Invoke clsObj = new Co1333Invoke();
int retVal = 0;
int expectedVal = 110;
Object[] varParams =
{
( 10 ),
( 100 )
};
mi = getMethod(typeof(Co1333Invoke), "ReturnI4Sum");
retVal = (int)mi.Invoke(clsObj, varParams);
Assert.True(retVal.Equals(expectedVal), String.Format("Failed! MethodInfo.Invoke did not return correct result. Expected {0} , Got {1}", expectedVal, retVal));
}
//Invoke inherited static method.
[Fact]
public static void TestInvokeMethod9()
{
MethodInfo mi = null;
Co1333Invoke clsObj = new Co1333Invoke();
bool retVal = false;
bool expectedVal = true;
Object[] varParams =
{
( 10 ),
};
mi = getMethod(typeof(Co1333_a), "IsEvenStatic");
retVal = (bool)mi.Invoke(clsObj, varParams);
Assert.True(retVal.Equals(expectedVal), String.Format("Failed! MethodInfo.Invoke did not return correct result. Expected {0} , Got {1}", expectedVal, retVal));
}
//Enum reflection in method signature
[Fact]
public static void TestInvokeMethod10()
{
MethodInfo mi = null;
Co1333Invoke clsObj = new Co1333Invoke();
int retVal = 0;
int expectedVal = (Int32)MyColorEnum.GREEN;
Object[] vars = new Object[1];
vars[0] = (MyColorEnum.RED);
mi = getMethod(typeof(Co1333Invoke), "GetAndRetMyEnum");
retVal = (int)mi.Invoke(clsObj, vars);
Assert.True(retVal.Equals(expectedVal), String.Format("Failed! MethodInfo.Invoke did not return correct result. Expected {0} , Got {1}", expectedVal, retVal));
}
//Call Interface Method
[Fact]
public static void TestInvokeMethod11()
{
MethodInfo mi = null;
MyClass clsObj = new MyClass();
int retVal = 0;
int expectedVal = 10;
mi = getMethod(typeof(MyInterface), "IMethod");
retVal = (int)mi.Invoke(clsObj, new object[] { });
Assert.True(retVal.Equals(expectedVal), String.Format("Failed! MethodInfo.Invoke did not return correct result. Expected {0} , Got {1}", expectedVal, retVal));
}
//Call Interface Method marked as new in class
[Fact]
public static void TestInvokeMethod12()
{
MethodInfo mi = null;
MyClass clsObj = new MyClass();
int retVal = 0;
int expectedVal = 20;
mi = getMethod(typeof(MyInterface), "IMethodNew");
retVal = (int)mi.Invoke(clsObj, new object[] { });
Assert.True(retVal.Equals(expectedVal), String.Format("Failed! MethodInfo.Invoke did not return correct result. Expected {0} , Got {1}", expectedVal, retVal));
}
// Gets MethodInfo object from current class
public static MethodInfo getMethod(string method)
{
return getMethod(typeof(Test), method);
}
//Gets MethodInfo object from a Type
public static MethodInfo getMethod(Type t, string method)
{
TypeInfo ti = t.GetTypeInfo();
IEnumerator<MethodInfo> alldefinedMethods = ti.DeclaredMethods.GetEnumerator();
MethodInfo mi = null;
while (alldefinedMethods.MoveNext())
{
if (alldefinedMethods.Current.Name.Equals(method))
{
//found method
mi = alldefinedMethods.Current;
break;
}
}
return mi;
}
}
public class Co1333_a
{
public static bool IsEvenStatic(int int4a)
{ return (int4a % 2 == 0) ? true : false; }
}
public class Co1333_b
{
public virtual int ReturnTheIntPlus()
{ return (0); }
}
public class Co1333_b1 : Co1333_b
{
public override int ReturnTheIntPlus()
{ return (1); }
}
public class Co1333_b2 : Co1333_b
{
public override int ReturnTheIntPlus()
{ return (2); }
}
public enum MyColorEnum
{
RED = 1,
YELLOW = 2,
GREEN = 3
}
public class Co1333Invoke
: Co1333_a
{
public MyColorEnum GetAndRetMyEnum(MyColorEnum myenum)
{
if (myenum == MyColorEnum.RED)
{
return MyColorEnum.GREEN;
}
else
return MyColorEnum.RED;
}
public String ConvertI4ObjToString(Object p_obj) // Bug 10829. Expecting Integer4 type of obj.
{
return (p_obj.ToString());
}
public int Int4ReturnThree()
{
return (3);
}
public long ReturnLongMax()
{
return (Int64.MaxValue);
}
public long ReturnI8Sum(int iFoo, long lFoo)
{
return ((long)iFoo + lFoo);
}
static public int ReturnI4Sum(int i4Foo, int i4Bar)
{
return (i4Foo + i4Bar);
}
}
public interface MyInterface
{
int IMethod();
int IMethodNew();
}
public class MyBaseClass : MyInterface
{
public int IMethod() { return 10; }
public int IMethodNew() { return 20; }
}
public class MyClass : MyBaseClass
{
public new int IMethodNew() { return 200; }
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEditor.SceneManagement;
using UnityEditorInternal;
using UnityEngine;
using Projeny.Internal;
namespace Projeny
{
public class PrjHelperResponse
{
public readonly bool Succeeded;
public readonly string ErrorMessage;
// The type here varies by request type
public readonly object Result;
PrjHelperResponse(
bool succeeded, string errorMessage, object result)
{
Succeeded = succeeded;
ErrorMessage = errorMessage;
Result = result;
}
public static PrjHelperResponse Error(string errorMessage)
{
return new PrjHelperResponse(false, errorMessage, null);
}
public static PrjHelperResponse Success(object result = null)
{
return new PrjHelperResponse(true, null, result);
}
}
public static class PrjHelper
{
public static bool UpdateLinks()
{
var result = PrjInterface.RunPrj(PrjInterface.CreatePrjRequest("updateLinks"));
// This sometimes causes out of memory issues for reasons unknown so just let user
// manually refresh
//AssetDatabase.Refresh();
if (!result.Succeeded)
{
DisplayPrjError("Updating directory links", result.ErrorMessage);
return false;
}
return true;
}
public static void ChangeProject(string projectName, string platformName = "windows")
{
if (!EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
{
// They hit cancel in the save dialog
return;
}
var platform = ProjenyEditorUtil.FromPlatformDirStr(platformName);
var result = PrjInterface.RunPrj(PrjInterface.CreatePrjRequestForProjectAndPlatform("updateLinks", projectName, platform));
if (result.Succeeded)
{
result = PrjInterface.RunPrj(PrjInterface.CreatePrjRequestForProjectAndPlatform("openUnity", projectName, platform));
if (result.Succeeded)
{
EditorApplication.Exit(0);
}
}
if (!result.Succeeded)
{
DisplayPrjError(
"Changing project to '{0}'"
.Fmt(projectName), result.ErrorMessage);
}
}
public static void ChangePlatform(BuildTarget desiredPlatform)
{
if (!EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
{
// They hit cancel in the save dialog
return;
}
if (ProjenyEditorUtil.GetPlatformFromDirectoryName() == desiredPlatform)
{
UnityEngine.Debug.Log("Projeny: Already at the desired platform, no need to change project.");
return;
}
var result = PrjInterface.RunPrj(PrjInterface.CreatePrjRequestForPlatform("updateLinks", desiredPlatform));
if (result.Succeeded)
{
result = PrjInterface.RunPrj(PrjInterface.CreatePrjRequestForPlatform("openUnity", desiredPlatform));
}
if (result.Succeeded)
{
EditorApplication.Exit(0);
}
else
{
DisplayPrjError(
"Changing platform to '{0}'"
.Fmt(desiredPlatform.ToString()), result.ErrorMessage);
}
}
public static void DisplayPrjError(string operationDescription, string errors)
{
var errorMessage = "Operation aborted. Projeny encountered errors when running '{0}'. Details: \n\n{1}".Fmt(operationDescription, errors);
Log.Error("Projeny: {0}", errorMessage);
EditorUtility.DisplayDialog("Error", errorMessage, "Ok");
}
public static IEnumerator OpenUnityForProjectAsync(string projectName)
{
var runner = PrjInterface.RunPrjAsync(
PrjInterface.CreatePrjRequestForProject("openUnity", projectName));
while (runner.MoveNext() && !(runner.Current is PrjResponse))
{
yield return runner.Current;
}
yield return CreateStandardResponse((PrjResponse)runner.Current);
}
// NOTE: It's up to the caller to call AssetDatabase.Refresh()
public static IEnumerator UpdateLinksAsync()
{
return UpdateLinksAsyncInternal(
PrjInterface.CreatePrjRequest("updateLinks"));
}
public static IEnumerator UpdateLinksAsyncForProject(string projectName)
{
return UpdateLinksAsyncInternal(
PrjInterface.CreatePrjRequestForProject("updateLinks", projectName));
}
static IEnumerator UpdateLinksAsyncInternal(PrjRequest req)
{
var runner = PrjInterface.RunPrjAsync(req);
while (runner.MoveNext() && !(runner.Current is PrjResponse))
{
yield return runner.Current;
}
yield return CreateStandardResponse((PrjResponse)runner.Current);
}
// NOTE: It's up to the calling code to update the solution first
public static IEnumerator OpenCustomSolutionAsync()
{
var runner = PrjInterface.RunPrjAsync(PrjInterface.CreatePrjRequest("openCustomSolution"));
while (runner.MoveNext() && !(runner.Current is PrjResponse))
{
yield return runner.Current;
}
yield return CreateStandardResponse((PrjResponse)runner.Current);
}
public static IEnumerator UpdateCustomSolutionAsync()
{
// Need the unity solution for defines and references
ProjenyEditorUtil.ForceGenerateUnitySolution();
var runner = PrjInterface.RunPrjAsync(PrjInterface.CreatePrjRequest("updateCustomSolution"));
while (runner.MoveNext() && !(runner.Current is PrjResponse))
{
yield return runner.Current;
}
yield return CreateStandardResponse((PrjResponse)runner.Current);
}
public static IEnumerator InstallReleaseAsync(string packageRoot, ReleaseInfo info)
{
var req = PrjInterface.CreatePrjRequest("installRelease");
req.Param1 = info.Id;
req.Param2 = packageRoot;
if (info.HasVersionCode)
{
req.Param3 = info.VersionCode.ToString();
}
var runner = PrjInterface.RunPrjAsync(req);
while (runner.MoveNext() && !(runner.Current is PrjResponse))
{
yield return runner.Current;
}
yield return CreateStandardResponse((PrjResponse)runner.Current);
}
static PrjHelperResponse CreateStandardResponse(PrjResponse response)
{
if (response.Succeeded)
{
return PrjHelperResponse.Success();
}
return PrjHelperResponse.Error(response.ErrorMessage);
}
public static IEnumerator CreateProjectAsync(string projectName, bool duplicateSettings)
{
var request = PrjInterface.CreatePrjRequest("createProject");
request.Param1 = projectName;
request.Param2 = duplicateSettings.ToString();
var runner = PrjInterface.RunPrjAsync(request);
while (runner.MoveNext() && !(runner.Current is PrjResponse))
{
yield return runner.Current;
}
yield return CreateStandardResponse((PrjResponse)runner.Current);
}
// Yields strings indicating status
// With final yield of type PrjHelperResponse with value type List<ReleaseInfo>
public static IEnumerator LookupReleaseListAsync()
{
var runner = PrjInterface.RunPrjAsync(PrjInterface.CreatePrjRequest("listReleases"));
while (runner.MoveNext() && !(runner.Current is PrjResponse))
{
yield return runner.Current;
}
var response = (PrjResponse)runner.Current;
if (response.Succeeded)
{
var docs = response.Output
.Split(new string[] { "---" }, StringSplitOptions.None);
yield return PrjHelperResponse.Success(
docs.Select(x => x.Trim())
.Where(x => x.Length > 0)
.Select(x => PrjSerializer.DeserializeReleaseInfo(x))
.Where(x => x != null).ToList());
}
else
{
yield return PrjHelperResponse.Error(response.ErrorMessage);
}
}
// NOTE: Returns null on failure
public static IEnumerator LookupPackagesListAsync()
{
var runner = PrjInterface.RunPrjAsync(PrjInterface.CreatePrjRequest("listPackages"));
while (runner.MoveNext() && !(runner.Current is PrjResponse))
{
yield return runner.Current;
}
var response = (PrjResponse)runner.Current;
if (response.Succeeded)
{
var docs = response.Output
.Split(new string[] { "---" }, StringSplitOptions.None);
yield return PrjHelperResponse.Success(
docs
.Select(x => PrjSerializer.DeserializePackageFolderInfo(x))
.Where(x => x != null).ToList());
}
else
{
yield return PrjHelperResponse.Error(response.ErrorMessage);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using Xunit;
namespace System.Net.Primitives.Functional.Tests
{
public static class CredentialCacheTest
{
private static readonly Uri uriPrefix1 = new Uri("http://microsoft:80");
private static readonly Uri uriPrefix2 = new Uri("http://softmicro:80");
private static readonly string host1 = "host1";
private static readonly string host2 = "host2";
private static readonly int port1 = 500;
private static readonly int port2 = 700;
private static readonly string authenticationType1 = "authenticationType1";
private static readonly string authenticationType2 = "authenticationType2";
private static readonly string authenticationTypeNTLM = "NTLM";
private static readonly string authenticationTypeKerberos = "Kerberos";
private static readonly string authenticationTypeNegotiate = "Negotiate";
private static readonly string authenticationTypeBasic = "Basic";
private static readonly string authenticationTypeDigest = "Digest";
private static readonly NetworkCredential customCredential = new NetworkCredential("username", "password");
private static readonly NetworkCredential credential1 = new NetworkCredential("username1", "password");
private static readonly NetworkCredential credential2 = new NetworkCredential("username2", "password");
private static readonly NetworkCredential credential3 = new NetworkCredential("username3", "password");
private static readonly NetworkCredential credential4 = new NetworkCredential("username4", "password");
private static readonly NetworkCredential credential5 = new NetworkCredential("username5", "password");
private static readonly NetworkCredential credential6 = new NetworkCredential("username6", "password");
private static readonly NetworkCredential credential7 = new NetworkCredential("username7", "password");
private static readonly NetworkCredential credential8 = new NetworkCredential("username8", "password");
private struct CredentialCacheCount
{
public CredentialCacheCount(CredentialCache cc, int count)
{
CredentialCache = cc;
Count = count;
}
public CredentialCache CredentialCache { get; }
public int Count { get; }
}
private static CredentialCache CreateUriCredentialCache() =>
CreateUriCredentialCacheCount().CredentialCache;
private static CredentialCacheCount CreateUriCredentialCacheCount(CredentialCache cc = null, int count = 0)
{
cc = cc ?? new CredentialCache();
cc.Add(uriPrefix1, authenticationType1, credential1); count++;
cc.Add(uriPrefix1, authenticationType2, credential2); count++;
cc.Add(uriPrefix2, authenticationType1, credential3); count++;
cc.Add(uriPrefix2, authenticationType2, credential4); count++;
return new CredentialCacheCount(cc, count);
}
private static CredentialCache CreateHostPortCredentialCache() =>
CreateHostPortCredentialCacheCount().CredentialCache;
private static CredentialCacheCount CreateHostPortCredentialCacheCount(CredentialCache cc = null, int count = 0)
{
cc = cc ?? new CredentialCache();
cc.Add(host1, port1, authenticationType1, credential1); count++;
cc.Add(host1, port1, authenticationType2, credential2); count++;
cc.Add(host1, port2, authenticationType1, credential3); count++;
cc.Add(host1, port2, authenticationType2, credential4); count++;
cc.Add(host2, port1, authenticationType1, credential5); count++;
cc.Add(host2, port1, authenticationType2, credential6); count++;
cc.Add(host2, port2, authenticationType1, credential7); count++;
cc.Add(host2, port2, authenticationType2, credential8); count++;
return new CredentialCacheCount(cc, count);
}
private static CredentialCacheCount CreateUriAndHostPortCredentialCacheCount()
{
CredentialCacheCount uri = CreateUriCredentialCacheCount();
return CreateHostPortCredentialCacheCount(uri.CredentialCache, uri.Count);
}
private static IEnumerable<CredentialCacheCount> GetCredentialCacheCounts()
{
yield return new CredentialCacheCount(new CredentialCache(), 0);
yield return CreateUriCredentialCacheCount();
yield return CreateHostPortCredentialCacheCount();
yield return CreateUriAndHostPortCredentialCacheCount();
}
public static IEnumerable<object[]> StandardAuthTypeWithNetworkCredential =>
new[]
{
new object[] {authenticationTypeNTLM, customCredential},
new object[] {authenticationTypeKerberos, customCredential},
new object[] {authenticationTypeNegotiate, customCredential},
new object[] {authenticationTypeBasic, customCredential},
new object[] {authenticationTypeDigest, customCredential},
new object[] {authenticationTypeNTLM, CredentialCache.DefaultNetworkCredentials as NetworkCredential},
new object[] {authenticationTypeKerberos, CredentialCache.DefaultNetworkCredentials as NetworkCredential},
new object[] {authenticationTypeNegotiate, CredentialCache.DefaultNetworkCredentials as NetworkCredential},
new object[] {authenticationTypeBasic, CredentialCache.DefaultNetworkCredentials as NetworkCredential},
new object[] {authenticationTypeDigest, CredentialCache.DefaultNetworkCredentials as NetworkCredential},
};
public static IEnumerable<object[]> CustomAuthTypeWithDefaultNetworkCredential =>
new[]
{
new object[] {authenticationType1, CredentialCache.DefaultNetworkCredentials as NetworkCredential},
new object[] {authenticationType2, CredentialCache.DefaultNetworkCredentials as NetworkCredential},
};
public static IEnumerable<object[]> CustomAuthTypeWithCustomNetworkCredential =>
new[]
{
new object[] {authenticationType1, customCredential},
new object[] {authenticationType1, customCredential},
new object[] {authenticationType2, customCredential},
new object[] {authenticationType2, customCredential},
};
[Fact]
public static void Ctor_Empty_Success()
{
CredentialCache cc = new CredentialCache();
}
[Fact]
public static void Add_UriAuthenticationTypeCredential_Success()
{
CredentialCache cc = CreateUriCredentialCache();
Assert.Equal(credential1, cc.GetCredential(uriPrefix1, authenticationType1));
Assert.Equal(credential2, cc.GetCredential(uriPrefix1, authenticationType2));
Assert.Equal(credential3, cc.GetCredential(uriPrefix2, authenticationType1));
Assert.Equal(credential4, cc.GetCredential(uriPrefix2, authenticationType2));
}
[Fact]
public static void Add_UriAuthenticationTypeCredential_Invalid()
{
CredentialCache cc = CreateUriCredentialCache();
Assert.Null(cc.GetCredential(new Uri("http://invalid.uri"), authenticationType1)); //No such uriPrefix
Assert.Null(cc.GetCredential(uriPrefix1, "invalid-authentication-type")); //No such authenticationType
AssertExtensions.Throws<ArgumentNullException>("uriPrefix", () => cc.Add(null, "some", new NetworkCredential())); //Null uriPrefix
AssertExtensions.Throws<ArgumentNullException>("authType", () => cc.Add(new Uri("http://microsoft:80"), null, new NetworkCredential())); //Null authenticationType
}
[Fact]
public static void Add_UriAuthenticationTypeCredential_DuplicateItem_Throws()
{
CredentialCache cc = new CredentialCache();
cc.Add(uriPrefix1, authenticationType1, credential1);
AssertExtensions.Throws<ArgumentException>(null, () => cc.Add(uriPrefix1, authenticationType1, credential1));
}
[Fact]
public static void Add_HostPortAuthenticationTypeCredential_Success()
{
CredentialCache cc = CreateHostPortCredentialCache();
Assert.Equal(credential1, cc.GetCredential(host1, port1, authenticationType1));
Assert.Equal(credential2, cc.GetCredential(host1, port1, authenticationType2));
Assert.Equal(credential3, cc.GetCredential(host1, port2, authenticationType1));
Assert.Equal(credential4, cc.GetCredential(host1, port2, authenticationType2));
Assert.Equal(credential5, cc.GetCredential(host2, port1, authenticationType1));
Assert.Equal(credential6, cc.GetCredential(host2, port1, authenticationType2));
Assert.Equal(credential7, cc.GetCredential(host2, port2, authenticationType1));
Assert.Equal(credential8, cc.GetCredential(host2, port2, authenticationType2));
}
[Fact]
public static void Add_HostPortAuthenticationTypeCredential_Invalid()
{
CredentialCache cc = CreateHostPortCredentialCache();
Assert.Null(cc.GetCredential("invalid-host", port1, authenticationType1)); //No such host
Assert.Null(cc.GetCredential(host1, 900, authenticationType1)); //No such port
Assert.Null(cc.GetCredential(host1, port1, "invalid-authentication-type")); //No such authenticationType
AssertExtensions.Throws<ArgumentNullException>("host", () => cc.Add(null, 500, "authenticationType", new NetworkCredential())); //Null host
AssertExtensions.Throws<ArgumentNullException>("authenticationType", () => cc.Add("host", 500, null, new NetworkCredential())); //Null authenticationType
var exception = Record.Exception(() => cc.Add("", 500, "authenticationType", new NetworkCredential()));
// On full framework we get exception.ParamName as null while it is "host" on netcore
Assert.NotNull(exception);
Assert.True(exception is ArgumentException);
ArgumentException ae = exception as ArgumentException;
Assert.True(ae.ParamName == "host" || ae.ParamName == null);
AssertExtensions.Throws<ArgumentOutOfRangeException>("port", () => cc.Add("host", -1, "authenticationType", new NetworkCredential())); //Port < 0
}
[Fact]
public static void Add_HostPortAuthenticationTypeCredential_DuplicateItem_Throws()
{
CredentialCache cc = new CredentialCache();
cc.Add(host1, port1, authenticationType1, credential1);
AssertExtensions.Throws<ArgumentException>(null, () => cc.Add(host1, port1, authenticationType1, credential1));
}
[Fact]
public static void Remove_UriAuthenticationType_Success()
{
CredentialCache cc = CreateUriCredentialCache();
cc.Remove(uriPrefix1, authenticationType1);
Assert.Null(cc.GetCredential(uriPrefix1, authenticationType1));
}
[Fact]
public static void Remove_UriAuthenticationType_Invalid()
{
CredentialCache cc = new CredentialCache();
//Doesn't throw, just returns
cc.Remove(null, "authenticationType");
cc.Remove(new Uri("http://some.com"), null);
cc.Remove(new Uri("http://some.com"), "authenticationType");
}
[Fact]
public static void Remove_HostPortAuthenticationType_Success()
{
CredentialCache cc = CreateHostPortCredentialCache();
cc.Remove(host1, port1, authenticationType1);
Assert.Null(cc.GetCredential(host1, port1, authenticationType1));
}
[Fact]
public static void Remove_HostPortAuthenticationType_Invalid()
{
CredentialCache cc = new CredentialCache();
//Doesn't throw, just returns
cc.Remove(null, 500, "authenticationType");
cc.Remove("host", 500, null);
cc.Remove("host", -1, "authenticationType");
cc.Remove("host", 500, "authenticationType");
}
[Fact]
public static void GetCredential_SimilarUriAuthenticationType_GetLongestUriPrefix()
{
CredentialCache cc = new CredentialCache();
cc.Add(new Uri("http://microsoft:80/greaterpath"), authenticationType1, credential2);
cc.Add(new Uri("http://microsoft:80/"), authenticationType1, credential1);
NetworkCredential nc = cc.GetCredential(new Uri("http://microsoft:80"), authenticationType1);
Assert.Equal(nc, credential2);
}
[Fact]
public static void GetCredential_UriAuthenticationType_Invalid()
{
CredentialCache cc = new CredentialCache();
AssertExtensions.Throws<ArgumentNullException>("uriPrefix", () => cc.GetCredential(null, "authenticationType")); //Null uriPrefix
AssertExtensions.Throws<ArgumentNullException>("authType", () => cc.GetCredential(new Uri("http://microsoft:80"), null)); //Null authenticationType
}
[Fact]
public static void GetCredential_HostPortAuthenticationType_Invalid()
{
CredentialCache cc = new CredentialCache();
AssertExtensions.Throws<ArgumentNullException>("host", () => cc.GetCredential(null, 500, "authenticationType")); //Null host
AssertExtensions.Throws<ArgumentNullException>("authenticationType", () => cc.GetCredential("host", 500, null)); //Null authenticationType
var exception = Record.Exception(() => cc.GetCredential("", 500, "authenticationType")); //Empty host
// On full framework we get exception.ParamName as null while it is "host" on netcore
Assert.NotNull(exception);
Assert.True(exception is ArgumentException);
ArgumentException ae = exception as ArgumentException;
Assert.True(ae.ParamName == "host" || ae.ParamName == null);
AssertExtensions.Throws<ArgumentOutOfRangeException>("port", () => cc.GetCredential("host", -1, "authenticationType")); //Port < 0
}
public static IEnumerable<object[]> GetEnumeratorWithCountTestData
{
get
{
foreach (CredentialCacheCount ccc in GetCredentialCacheCounts())
{
yield return new object[] { ccc.CredentialCache, ccc.Count };
}
}
}
[Theory]
[MemberData(nameof(GetEnumeratorWithCountTestData))]
public static void GetEnumerator_Enumerate_Success(CredentialCache cc, int count)
{
IEnumerator enumerator = cc.GetEnumerator();
Assert.NotNull(enumerator);
for (int iterations = 0; iterations < 2; iterations++)
{
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
for (int i = 0; i < count; i++)
{
Assert.True(enumerator.MoveNext());
Assert.NotNull(enumerator.Current);
}
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Reset();
}
}
public static IEnumerable<object[]> GetEnumeratorThenAddTestData
{
get
{
foreach (bool addUri in new[] { true, false })
{
foreach (CredentialCacheCount ccc in GetCredentialCacheCounts())
{
yield return new object[] { ccc.CredentialCache, addUri };
}
}
}
}
[Theory]
[MemberData(nameof(GetEnumeratorThenAddTestData))]
public static void GetEnumerator_MoveNextSynchronization_Invalid(CredentialCache cc, bool addUri)
{
//An InvalidOperationException is thrown when moving the enumerator
//when a credential is added to the cache after getting the enumerator
IEnumerator enumerator = cc.GetEnumerator();
if (addUri)
{
cc.Add(new Uri("http://whatever:80"), authenticationType1, credential1);
}
else
{
cc.Add("whatever", 80, authenticationType1, credential1);
}
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
}
[Theory]
[MemberData(nameof(GetEnumeratorThenAddTestData))]
public static void GetEnumerator_CurrentSynchronization_Invalid(CredentialCache cc, bool addUri)
{
//An InvalidOperationException is thrown when getting the current enumerated object
//when a credential is added to the cache after getting the enumerator
IEnumerator enumerator = cc.GetEnumerator();
enumerator.MoveNext();
if (addUri)
{
cc.Add(new Uri("http://whatever:80"), authenticationType1, credential1);
}
else
{
cc.Add("whatever", 80, authenticationType1, credential1);
}
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
}
public static IEnumerable<object[]> GetEnumeratorTestData
{
get
{
foreach (CredentialCacheCount ccc in GetCredentialCacheCounts())
{
yield return new object[] { ccc.CredentialCache };
}
}
}
[Theory]
[MemberData(nameof(GetEnumeratorTestData))]
public static void GetEnumerator_ResetIndexGetCurrent_Invalid(CredentialCache cc)
{
IEnumerator enumerator = cc.GetEnumerator();
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
}
[Fact]
public static void GetEnumerator_MoveNextIndex_Invalid()
{
CredentialCache cc = new CredentialCache();
IEnumerator enumerator = cc.GetEnumerator();
enumerator.MoveNext();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
}
[Fact]
public static void DefaultCredentials_Get_Success()
{
NetworkCredential c = CredentialCache.DefaultCredentials as NetworkCredential;
Assert.NotNull(c);
Assert.Equal(string.Empty, c.UserName);
Assert.Equal(string.Empty, c.Password);
Assert.Equal(string.Empty, c.Domain);
}
[Theory]
[MemberData(nameof(StandardAuthTypeWithNetworkCredential))]
[MemberData(nameof(CustomAuthTypeWithCustomNetworkCredential))]
public static void Add_UriAuthenticationType_Success(string authType, NetworkCredential nc)
{
// Default credentials cannot be supplied for the Basic authentication scheme.
if (string.Equals(authType, authenticationTypeBasic, StringComparison.OrdinalIgnoreCase) && (nc == CredentialCache.DefaultNetworkCredentials))
{
return;
}
CredentialCache cc = new CredentialCache();
// .NET Framework and .NET Core have different behaviors for Digest when default NetworkCredential is used.
if (string.Equals(authType, authenticationTypeDigest, StringComparison.OrdinalIgnoreCase) && (nc == CredentialCache.DefaultNetworkCredentials))
{
if (PlatformDetection.IsFullFramework)
{
// In .NET Framework, when authType == Digest, if WDigestAvailable == true, it will pass the validation.
// if WDigestAvailable == false, it will throw ArgumentException.
// It is not possible to easily determine if Digest is supported or not on .NET Framework. So, we will skip the test.
return;
}
else
{
// In .NET Core, WDigestAvailable will always be false (we don't support it).
// It will always throw ArgumentException.
AssertExtensions.Throws<ArgumentException>("authType", () => cc.Add(uriPrefix1, authType, nc));
return;
}
}
cc.Add(uriPrefix1, authType, nc);
Assert.Equal(nc, cc.GetCredential(uriPrefix1, authType));
}
[Theory]
[MemberData(nameof(CustomAuthTypeWithDefaultNetworkCredential))]
public static void Add_UriCustomAuthTypeWithDefaultCredential_ThrowsArgumentException(string authType, NetworkCredential nc)
{
CredentialCache cc = new CredentialCache();
AssertExtensions.Throws<ArgumentException>("authType", () => cc.Add(uriPrefix1, authType, nc));
}
[Theory]
[MemberData(nameof(StandardAuthTypeWithNetworkCredential))]
[MemberData(nameof(CustomAuthTypeWithCustomNetworkCredential))]
public static void Add_HostPortAuthenticationType_Success(string authType, NetworkCredential nc)
{
// Default credentials cannot be supplied for the Basic authentication scheme.
if (string.Equals(authType, "Basic", StringComparison.OrdinalIgnoreCase) && (nc == CredentialCache.DefaultNetworkCredentials))
{
return;
}
CredentialCache cc = new CredentialCache();
// .NET Framework and .NET Core have different behaviors for Digest when default NetworkCredential is used.
if (string.Equals(authType, authenticationTypeDigest, StringComparison.OrdinalIgnoreCase) && (nc == CredentialCache.DefaultNetworkCredentials))
{
if (PlatformDetection.IsFullFramework)
{
// In .NET Framework, when authType == Digest, if WDigestAvailable == true, it will pass the validation.
// if WDigestAvailable == false, it will throw ArgumentException.
// It is not possible to easily determine if Digest is supported or not on .NET Framework. So, we will skip the test.
return;
}
else
{
// In .NET Core, WDigestAvailable will always be false (we don't support it).
// It will always throw ArgumentException.
AssertExtensions.Throws<ArgumentException>("authenticationType", () => cc.Add(host1, port1, authType, nc));
return;
}
}
cc.Add(host1, port1, authType, nc);
Assert.Equal(nc, cc.GetCredential(host1, port1, authType));
}
[Theory]
[MemberData(nameof(CustomAuthTypeWithDefaultNetworkCredential))]
public static void Add_HostPortCustomAuthTypeWithDefaultCredential_ThrowsArgumentException(string authType, NetworkCredential nc)
{
CredentialCache cc = new CredentialCache();
AssertExtensions.Throws<ArgumentException>("authenticationType", () => cc.Add(host1, port1, authType, nc));
}
[Fact]
public static void AddRemove_UriAuthenticationType_Success()
{
NetworkCredential nc = customCredential;
CredentialCache cc = new CredentialCache();
cc.Add(uriPrefix1, authenticationType1, nc);
Assert.Equal(nc, cc.GetCredential(uriPrefix1, authenticationType1));
cc.Remove(uriPrefix1, authenticationType1);
Assert.Null(cc.GetCredential(uriPrefix1, authenticationType1));
}
[Fact]
public static void AddRemove_HostPortAuthenticationType_Success()
{
NetworkCredential nc = customCredential;
CredentialCache cc = new CredentialCache();
cc.Add(host1, port1, authenticationType1, nc);
Assert.Equal(nc, cc.GetCredential(host1, port1, authenticationType1));
cc.Remove(host1, port1, authenticationType1);
Assert.Null(cc.GetCredential(host1, port1, authenticationType1));
}
[Fact]
public static void DefaultNetworkCredentials_Get_Success()
{
NetworkCredential nc = CredentialCache.DefaultNetworkCredentials as NetworkCredential;
Assert.NotNull(nc);
Assert.Equal(string.Empty, nc.UserName);
Assert.Equal(string.Empty, nc.Password);
Assert.Equal(string.Empty, nc.Domain);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace OpenSim.Framework.Monitoring
{
/// <summary>
/// Singleton used to provide access to statistics reporters
/// </summary>
public class StatsManager
{
// Subcommand used to list other stats.
public const string AllSubCommand = "all";
// Subcommand used to list other stats.
public const string ListSubCommand = "list";
// All subcommands
public static HashSet<string> SubCommands = new HashSet<string> { AllSubCommand, ListSubCommand };
/// <summary>
/// Registered stats categorized by category/container/shortname
/// </summary>
/// <remarks>
/// Do not add or remove directly from this dictionary.
/// </remarks>
public static SortedDictionary<string, SortedDictionary<string, SortedDictionary<string, Stat>>> RegisteredStats
= new SortedDictionary<string, SortedDictionary<string, SortedDictionary<string, Stat>>>();
private static AssetStatsCollector assetStats;
private static UserStatsCollector userStats;
private static SimExtraStatsCollector simExtraStats = new SimExtraStatsCollector();
public static AssetStatsCollector AssetStats { get { return assetStats; } }
public static UserStatsCollector UserStats { get { return userStats; } }
public static SimExtraStatsCollector SimExtraStats { get { return simExtraStats; } }
public static void RegisterConsoleCommands(ICommandConsole console)
{
console.Commands.AddCommand(
"General",
false,
"show stats",
"show stats [list|all|<category>]",
"Show statistical information for this server",
"If no final argument is specified then legacy statistics information is currently shown.\n"
+ "If list is specified then statistic categories are shown.\n"
+ "If all is specified then all registered statistics are shown.\n"
+ "If a category name is specified then only statistics from that category are shown.\n"
+ "THIS STATS FACILITY IS EXPERIMENTAL AND DOES NOT YET CONTAIN ALL STATS",
HandleShowStatsCommand);
}
public static void HandleShowStatsCommand(string module, string[] cmd)
{
ICommandConsole con = MainConsole.Instance;
if (cmd.Length > 2)
{
var categoryName = cmd[2];
var containerName = cmd.Length > 3 ? cmd[3] : String.Empty;
if (categoryName == AllSubCommand)
{
foreach (var category in RegisteredStats.Values)
{
OutputCategoryStatsToConsole(con, category);
}
}
else if (categoryName == ListSubCommand)
{
con.Output("Statistic categories available are:");
foreach (string category in RegisteredStats.Keys)
con.OutputFormat(" {0}", category);
}
else
{
SortedDictionary<string, SortedDictionary<string, Stat>> category;
if (!RegisteredStats.TryGetValue(categoryName, out category))
{
con.OutputFormat("No such category as {0}", categoryName);
}
else
{
if (String.IsNullOrEmpty(containerName))
OutputCategoryStatsToConsole(con, category);
else
{
SortedDictionary<string, Stat> container;
if (category.TryGetValue(containerName, out container))
{
OutputContainerStatsToConsole(con, container);
}
else
{
con.OutputFormat("No such container {0} in category {1}", containerName, categoryName);
}
}
}
}
}
else
{
// Legacy
con.Output(SimExtraStats.Report());
}
}
private static void OutputCategoryStatsToConsole(
ICommandConsole con, SortedDictionary<string, SortedDictionary<string, Stat>> category)
{
foreach (var container in category.Values)
{
OutputContainerStatsToConsole(con, container);
}
}
private static void OutputContainerStatsToConsole( ICommandConsole con, SortedDictionary<string, Stat> container)
{
foreach (Stat stat in container.Values)
{
con.Output(stat.ToConsoleString());
}
}
/// <summary>
/// Start collecting statistics related to assets.
/// Should only be called once.
/// </summary>
public static AssetStatsCollector StartCollectingAssetStats()
{
assetStats = new AssetStatsCollector();
return assetStats;
}
/// <summary>
/// Start collecting statistics related to users.
/// Should only be called once.
/// </summary>
public static UserStatsCollector StartCollectingUserStats()
{
userStats = new UserStatsCollector();
return userStats;
}
/// <summary>
/// Registers a statistic.
/// </summary>
/// <param name='stat'></param>
/// <returns></returns>
public static bool RegisterStat(Stat stat)
{
SortedDictionary<string, SortedDictionary<string, Stat>> category = null, newCategory;
SortedDictionary<string, Stat> container = null, newContainer;
lock (RegisteredStats)
{
// Stat name is not unique across category/container/shortname key.
// XXX: For now just return false. This is to avoid problems in regression tests where all tests
// in a class are run in the same instance of the VM.
if (TryGetStat(stat, out category, out container))
return false;
// We take a copy-on-write approach here of replacing dictionaries when keys are added or removed.
// This means that we don't need to lock or copy them on iteration, which will be a much more
// common operation after startup.
if (container != null)
newContainer = new SortedDictionary<string, Stat>(container);
else
newContainer = new SortedDictionary<string, Stat>();
if (category != null)
newCategory = new SortedDictionary<string, SortedDictionary<string, Stat>>(category);
else
newCategory = new SortedDictionary<string, SortedDictionary<string, Stat>>();
newContainer[stat.ShortName] = stat;
newCategory[stat.Container] = newContainer;
RegisteredStats[stat.Category] = newCategory;
}
return true;
}
/// <summary>
/// Deregister a statistic
/// </summary>>
/// <param name='stat'></param>
/// <returns></returns>
public static bool DeregisterStat(Stat stat)
{
SortedDictionary<string, SortedDictionary<string, Stat>> category = null, newCategory;
SortedDictionary<string, Stat> container = null, newContainer;
lock (RegisteredStats)
{
if (!TryGetStat(stat, out category, out container))
return false;
newContainer = new SortedDictionary<string, Stat>(container);
newContainer.Remove(stat.ShortName);
newCategory = new SortedDictionary<string, SortedDictionary<string, Stat>>(category);
newCategory.Remove(stat.Container);
newCategory[stat.Container] = newContainer;
RegisteredStats[stat.Category] = newCategory;
return true;
}
}
public static bool TryGetStats(string category, out SortedDictionary<string, SortedDictionary<string, Stat>> stats)
{
return RegisteredStats.TryGetValue(category, out stats);
}
public static bool TryGetStat(
Stat stat,
out SortedDictionary<string, SortedDictionary<string, Stat>> category,
out SortedDictionary<string, Stat> container)
{
category = null;
container = null;
lock (RegisteredStats)
{
if (RegisteredStats.TryGetValue(stat.Category, out category))
{
if (category.TryGetValue(stat.Container, out container))
{
if (container.ContainsKey(stat.ShortName))
return true;
}
}
}
return false;
}
public static void RecordStats()
{
lock (RegisteredStats)
{
foreach (SortedDictionary<string, SortedDictionary<string, Stat>> category in RegisteredStats.Values)
{
foreach (SortedDictionary<string, Stat> container in category.Values)
{
foreach (Stat stat in container.Values)
{
if (stat.MeasuresOfInterest != MeasuresOfInterest.None)
stat.RecordValue();
}
}
}
}
}
}
/// <summary>
/// Stat type.
/// </summary>
/// <remarks>
/// A push stat is one which is continually updated and so it's value can simply by read.
/// A pull stat is one where reading the value triggers a collection method - the stat is not continually updated.
/// </remarks>
public enum StatType
{
Push,
Pull
}
/// <summary>
/// Measures of interest for this stat.
/// </summary>
[Flags]
public enum MeasuresOfInterest
{
None,
AverageChangeOverTime
}
/// <summary>
/// Verbosity of stat.
/// </summary>
/// <remarks>
/// Info will always be displayed.
/// </remarks>
public enum StatVerbosity
{
Debug,
Info
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void SubtractScalarDouble()
{
var test = new SimpleBinaryOpTest__SubtractScalarDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__SubtractScalarDouble
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Double> _fld1;
public Vector128<Double> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__SubtractScalarDouble testClass)
{
var result = Sse2.SubtractScalar(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__SubtractScalarDouble testClass)
{
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
{
var result = Sse2.SubtractScalar(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__SubtractScalarDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public SimpleBinaryOpTest__SubtractScalarDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.SubtractScalar(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.SubtractScalar(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.SubtractScalar(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.SubtractScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.SubtractScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.SubtractScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.SubtractScalar(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Double>* pClsVar1 = &_clsVar1)
fixed (Vector128<Double>* pClsVar2 = &_clsVar2)
{
var result = Sse2.SubtractScalar(
Sse2.LoadVector128((Double*)(pClsVar1)),
Sse2.LoadVector128((Double*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var result = Sse2.SubtractScalar(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.SubtractScalar(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.SubtractScalar(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__SubtractScalarDouble();
var result = Sse2.SubtractScalar(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__SubtractScalarDouble();
fixed (Vector128<Double>* pFld1 = &test._fld1)
fixed (Vector128<Double>* pFld2 = &test._fld2)
{
var result = Sse2.SubtractScalar(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.SubtractScalar(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
{
var result = Sse2.SubtractScalar(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.SubtractScalar(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.SubtractScalar(
Sse2.LoadVector128((Double*)(&test._fld1)),
Sse2.LoadVector128((Double*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.DoubleToInt64Bits(left[0] - right[0]) != BitConverter.DoubleToInt64Bits(result[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(left[i]) != BitConverter.DoubleToInt64Bits(result[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.SubtractScalar)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V8.Services
{
/// <summary>Settings for <see cref="ThirdPartyAppAnalyticsLinkServiceClient"/> instances.</summary>
public sealed partial class ThirdPartyAppAnalyticsLinkServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>
/// Get a new instance of the default <see cref="ThirdPartyAppAnalyticsLinkServiceSettings"/>.
/// </summary>
/// <returns>A new instance of the default <see cref="ThirdPartyAppAnalyticsLinkServiceSettings"/>.</returns>
public static ThirdPartyAppAnalyticsLinkServiceSettings GetDefault() =>
new ThirdPartyAppAnalyticsLinkServiceSettings();
/// <summary>
/// Constructs a new <see cref="ThirdPartyAppAnalyticsLinkServiceSettings"/> object with default settings.
/// </summary>
public ThirdPartyAppAnalyticsLinkServiceSettings()
{
}
private ThirdPartyAppAnalyticsLinkServiceSettings(ThirdPartyAppAnalyticsLinkServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetThirdPartyAppAnalyticsLinkSettings = existing.GetThirdPartyAppAnalyticsLinkSettings;
RegenerateShareableLinkIdSettings = existing.RegenerateShareableLinkIdSettings;
OnCopy(existing);
}
partial void OnCopy(ThirdPartyAppAnalyticsLinkServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>ThirdPartyAppAnalyticsLinkServiceClient.GetThirdPartyAppAnalyticsLink</c> and
/// <c>ThirdPartyAppAnalyticsLinkServiceClient.GetThirdPartyAppAnalyticsLinkAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetThirdPartyAppAnalyticsLinkSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>ThirdPartyAppAnalyticsLinkServiceClient.RegenerateShareableLinkId</c> and
/// <c>ThirdPartyAppAnalyticsLinkServiceClient.RegenerateShareableLinkIdAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings RegenerateShareableLinkIdSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="ThirdPartyAppAnalyticsLinkServiceSettings"/> object.</returns>
public ThirdPartyAppAnalyticsLinkServiceSettings Clone() => new ThirdPartyAppAnalyticsLinkServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="ThirdPartyAppAnalyticsLinkServiceClient"/> to provide simple configuration of
/// credentials, endpoint etc.
/// </summary>
internal sealed partial class ThirdPartyAppAnalyticsLinkServiceClientBuilder : gaxgrpc::ClientBuilderBase<ThirdPartyAppAnalyticsLinkServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public ThirdPartyAppAnalyticsLinkServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public ThirdPartyAppAnalyticsLinkServiceClientBuilder()
{
UseJwtAccessWithScopes = ThirdPartyAppAnalyticsLinkServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref ThirdPartyAppAnalyticsLinkServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ThirdPartyAppAnalyticsLinkServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override ThirdPartyAppAnalyticsLinkServiceClient Build()
{
ThirdPartyAppAnalyticsLinkServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<ThirdPartyAppAnalyticsLinkServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<ThirdPartyAppAnalyticsLinkServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private ThirdPartyAppAnalyticsLinkServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return ThirdPartyAppAnalyticsLinkServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<ThirdPartyAppAnalyticsLinkServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return ThirdPartyAppAnalyticsLinkServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => ThirdPartyAppAnalyticsLinkServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() =>
ThirdPartyAppAnalyticsLinkServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => ThirdPartyAppAnalyticsLinkServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>ThirdPartyAppAnalyticsLinkService client wrapper, for convenient use.</summary>
/// <remarks>
/// This service allows management of links between Google Ads and third party
/// app analytics.
/// </remarks>
public abstract partial class ThirdPartyAppAnalyticsLinkServiceClient
{
/// <summary>
/// The default endpoint for the ThirdPartyAppAnalyticsLinkService service, which is a host of
/// "googleads.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default ThirdPartyAppAnalyticsLinkService scopes.</summary>
/// <remarks>
/// The default ThirdPartyAppAnalyticsLinkService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="ThirdPartyAppAnalyticsLinkServiceClient"/> using the default
/// credentials, endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="ThirdPartyAppAnalyticsLinkServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="ThirdPartyAppAnalyticsLinkServiceClient"/>.</returns>
public static stt::Task<ThirdPartyAppAnalyticsLinkServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new ThirdPartyAppAnalyticsLinkServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="ThirdPartyAppAnalyticsLinkServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="ThirdPartyAppAnalyticsLinkServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="ThirdPartyAppAnalyticsLinkServiceClient"/>.</returns>
public static ThirdPartyAppAnalyticsLinkServiceClient Create() =>
new ThirdPartyAppAnalyticsLinkServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="ThirdPartyAppAnalyticsLinkServiceClient"/> which uses the specified call invoker for
/// remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="ThirdPartyAppAnalyticsLinkServiceSettings"/>.</param>
/// <returns>The created <see cref="ThirdPartyAppAnalyticsLinkServiceClient"/>.</returns>
internal static ThirdPartyAppAnalyticsLinkServiceClient Create(grpccore::CallInvoker callInvoker, ThirdPartyAppAnalyticsLinkServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
ThirdPartyAppAnalyticsLinkService.ThirdPartyAppAnalyticsLinkServiceClient grpcClient = new ThirdPartyAppAnalyticsLinkService.ThirdPartyAppAnalyticsLinkServiceClient(callInvoker);
return new ThirdPartyAppAnalyticsLinkServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC ThirdPartyAppAnalyticsLinkService client</summary>
public virtual ThirdPartyAppAnalyticsLinkService.ThirdPartyAppAnalyticsLinkServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the third party app analytics link in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::ThirdPartyAppAnalyticsLink GetThirdPartyAppAnalyticsLink(GetThirdPartyAppAnalyticsLinkRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the third party app analytics link in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::ThirdPartyAppAnalyticsLink> GetThirdPartyAppAnalyticsLinkAsync(GetThirdPartyAppAnalyticsLinkRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the third party app analytics link in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::ThirdPartyAppAnalyticsLink> GetThirdPartyAppAnalyticsLinkAsync(GetThirdPartyAppAnalyticsLinkRequest request, st::CancellationToken cancellationToken) =>
GetThirdPartyAppAnalyticsLinkAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Regenerate ThirdPartyAppAnalyticsLink.shareable_link_id that should be
/// provided to the third party when setting up app analytics.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual RegenerateShareableLinkIdResponse RegenerateShareableLinkId(RegenerateShareableLinkIdRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Regenerate ThirdPartyAppAnalyticsLink.shareable_link_id that should be
/// provided to the third party when setting up app analytics.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<RegenerateShareableLinkIdResponse> RegenerateShareableLinkIdAsync(RegenerateShareableLinkIdRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Regenerate ThirdPartyAppAnalyticsLink.shareable_link_id that should be
/// provided to the third party when setting up app analytics.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<RegenerateShareableLinkIdResponse> RegenerateShareableLinkIdAsync(RegenerateShareableLinkIdRequest request, st::CancellationToken cancellationToken) =>
RegenerateShareableLinkIdAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>ThirdPartyAppAnalyticsLinkService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// This service allows management of links between Google Ads and third party
/// app analytics.
/// </remarks>
public sealed partial class ThirdPartyAppAnalyticsLinkServiceClientImpl : ThirdPartyAppAnalyticsLinkServiceClient
{
private readonly gaxgrpc::ApiCall<GetThirdPartyAppAnalyticsLinkRequest, gagvr::ThirdPartyAppAnalyticsLink> _callGetThirdPartyAppAnalyticsLink;
private readonly gaxgrpc::ApiCall<RegenerateShareableLinkIdRequest, RegenerateShareableLinkIdResponse> _callRegenerateShareableLinkId;
/// <summary>
/// Constructs a client wrapper for the ThirdPartyAppAnalyticsLinkService service, with the specified gRPC
/// client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="ThirdPartyAppAnalyticsLinkServiceSettings"/> used within this client.
/// </param>
public ThirdPartyAppAnalyticsLinkServiceClientImpl(ThirdPartyAppAnalyticsLinkService.ThirdPartyAppAnalyticsLinkServiceClient grpcClient, ThirdPartyAppAnalyticsLinkServiceSettings settings)
{
GrpcClient = grpcClient;
ThirdPartyAppAnalyticsLinkServiceSettings effectiveSettings = settings ?? ThirdPartyAppAnalyticsLinkServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetThirdPartyAppAnalyticsLink = clientHelper.BuildApiCall<GetThirdPartyAppAnalyticsLinkRequest, gagvr::ThirdPartyAppAnalyticsLink>(grpcClient.GetThirdPartyAppAnalyticsLinkAsync, grpcClient.GetThirdPartyAppAnalyticsLink, effectiveSettings.GetThirdPartyAppAnalyticsLinkSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetThirdPartyAppAnalyticsLink);
Modify_GetThirdPartyAppAnalyticsLinkApiCall(ref _callGetThirdPartyAppAnalyticsLink);
_callRegenerateShareableLinkId = clientHelper.BuildApiCall<RegenerateShareableLinkIdRequest, RegenerateShareableLinkIdResponse>(grpcClient.RegenerateShareableLinkIdAsync, grpcClient.RegenerateShareableLinkId, effectiveSettings.RegenerateShareableLinkIdSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callRegenerateShareableLinkId);
Modify_RegenerateShareableLinkIdApiCall(ref _callRegenerateShareableLinkId);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetThirdPartyAppAnalyticsLinkApiCall(ref gaxgrpc::ApiCall<GetThirdPartyAppAnalyticsLinkRequest, gagvr::ThirdPartyAppAnalyticsLink> call);
partial void Modify_RegenerateShareableLinkIdApiCall(ref gaxgrpc::ApiCall<RegenerateShareableLinkIdRequest, RegenerateShareableLinkIdResponse> call);
partial void OnConstruction(ThirdPartyAppAnalyticsLinkService.ThirdPartyAppAnalyticsLinkServiceClient grpcClient, ThirdPartyAppAnalyticsLinkServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC ThirdPartyAppAnalyticsLinkService client</summary>
public override ThirdPartyAppAnalyticsLinkService.ThirdPartyAppAnalyticsLinkServiceClient GrpcClient { get; }
partial void Modify_GetThirdPartyAppAnalyticsLinkRequest(ref GetThirdPartyAppAnalyticsLinkRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_RegenerateShareableLinkIdRequest(ref RegenerateShareableLinkIdRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the third party app analytics link in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::ThirdPartyAppAnalyticsLink GetThirdPartyAppAnalyticsLink(GetThirdPartyAppAnalyticsLinkRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetThirdPartyAppAnalyticsLinkRequest(ref request, ref callSettings);
return _callGetThirdPartyAppAnalyticsLink.Sync(request, callSettings);
}
/// <summary>
/// Returns the third party app analytics link in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::ThirdPartyAppAnalyticsLink> GetThirdPartyAppAnalyticsLinkAsync(GetThirdPartyAppAnalyticsLinkRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetThirdPartyAppAnalyticsLinkRequest(ref request, ref callSettings);
return _callGetThirdPartyAppAnalyticsLink.Async(request, callSettings);
}
/// <summary>
/// Regenerate ThirdPartyAppAnalyticsLink.shareable_link_id that should be
/// provided to the third party when setting up app analytics.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override RegenerateShareableLinkIdResponse RegenerateShareableLinkId(RegenerateShareableLinkIdRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_RegenerateShareableLinkIdRequest(ref request, ref callSettings);
return _callRegenerateShareableLinkId.Sync(request, callSettings);
}
/// <summary>
/// Regenerate ThirdPartyAppAnalyticsLink.shareable_link_id that should be
/// provided to the third party when setting up app analytics.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<RegenerateShareableLinkIdResponse> RegenerateShareableLinkIdAsync(RegenerateShareableLinkIdRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_RegenerateShareableLinkIdRequest(ref request, ref callSettings);
return _callRegenerateShareableLinkId.Async(request, callSettings);
}
}
}
| |
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Language.V1.Snippets
{
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using apis = Google.Cloud.Language.V1;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
/// <summary>Generated snippets</summary>
public class GeneratedLanguageServiceClientSnippets
{
/// <summary>Snippet for AnalyzeSentimentAsync</summary>
public async Task AnalyzeSentimentAsync()
{
// Snippet: AnalyzeSentimentAsync(Document,CallSettings)
// Additional: AnalyzeSentimentAsync(Document,CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
Document document = new Document();
// Make the request
AnalyzeSentimentResponse response = await languageServiceClient.AnalyzeSentimentAsync(document);
// End snippet
}
/// <summary>Snippet for AnalyzeSentiment</summary>
public void AnalyzeSentiment()
{
// Snippet: AnalyzeSentiment(Document,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
Document document = new Document();
// Make the request
AnalyzeSentimentResponse response = languageServiceClient.AnalyzeSentiment(document);
// End snippet
}
/// <summary>Snippet for AnalyzeSentimentAsync</summary>
public async Task AnalyzeSentimentAsync_RequestObject()
{
// Snippet: AnalyzeSentimentAsync(AnalyzeSentimentRequest,CallSettings)
// Additional: AnalyzeSentimentAsync(AnalyzeSentimentRequest,CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
AnalyzeSentimentRequest request = new AnalyzeSentimentRequest
{
Document = new Document(),
};
// Make the request
AnalyzeSentimentResponse response = await languageServiceClient.AnalyzeSentimentAsync(request);
// End snippet
}
/// <summary>Snippet for AnalyzeSentiment</summary>
public void AnalyzeSentiment_RequestObject()
{
// Snippet: AnalyzeSentiment(AnalyzeSentimentRequest,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
AnalyzeSentimentRequest request = new AnalyzeSentimentRequest
{
Document = new Document(),
};
// Make the request
AnalyzeSentimentResponse response = languageServiceClient.AnalyzeSentiment(request);
// End snippet
}
/// <summary>Snippet for AnalyzeEntitiesAsync</summary>
public async Task AnalyzeEntitiesAsync()
{
// Snippet: AnalyzeEntitiesAsync(Document,EncodingType?,CallSettings)
// Additional: AnalyzeEntitiesAsync(Document,EncodingType?,CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
Document document = new Document();
EncodingType encodingType = EncodingType.None;
// Make the request
AnalyzeEntitiesResponse response = await languageServiceClient.AnalyzeEntitiesAsync(document, encodingType);
// End snippet
}
/// <summary>Snippet for AnalyzeEntities</summary>
public void AnalyzeEntities()
{
// Snippet: AnalyzeEntities(Document,EncodingType?,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
Document document = new Document();
EncodingType encodingType = EncodingType.None;
// Make the request
AnalyzeEntitiesResponse response = languageServiceClient.AnalyzeEntities(document, encodingType);
// End snippet
}
/// <summary>Snippet for AnalyzeEntitiesAsync</summary>
public async Task AnalyzeEntitiesAsync_RequestObject()
{
// Snippet: AnalyzeEntitiesAsync(AnalyzeEntitiesRequest,CallSettings)
// Additional: AnalyzeEntitiesAsync(AnalyzeEntitiesRequest,CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
AnalyzeEntitiesRequest request = new AnalyzeEntitiesRequest
{
Document = new Document(),
};
// Make the request
AnalyzeEntitiesResponse response = await languageServiceClient.AnalyzeEntitiesAsync(request);
// End snippet
}
/// <summary>Snippet for AnalyzeEntities</summary>
public void AnalyzeEntities_RequestObject()
{
// Snippet: AnalyzeEntities(AnalyzeEntitiesRequest,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
AnalyzeEntitiesRequest request = new AnalyzeEntitiesRequest
{
Document = new Document(),
};
// Make the request
AnalyzeEntitiesResponse response = languageServiceClient.AnalyzeEntities(request);
// End snippet
}
/// <summary>Snippet for AnalyzeEntitySentimentAsync</summary>
public async Task AnalyzeEntitySentimentAsync()
{
// Snippet: AnalyzeEntitySentimentAsync(Document,EncodingType?,CallSettings)
// Additional: AnalyzeEntitySentimentAsync(Document,EncodingType?,CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
Document document = new Document();
EncodingType encodingType = EncodingType.None;
// Make the request
AnalyzeEntitySentimentResponse response = await languageServiceClient.AnalyzeEntitySentimentAsync(document, encodingType);
// End snippet
}
/// <summary>Snippet for AnalyzeEntitySentiment</summary>
public void AnalyzeEntitySentiment()
{
// Snippet: AnalyzeEntitySentiment(Document,EncodingType?,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
Document document = new Document();
EncodingType encodingType = EncodingType.None;
// Make the request
AnalyzeEntitySentimentResponse response = languageServiceClient.AnalyzeEntitySentiment(document, encodingType);
// End snippet
}
/// <summary>Snippet for AnalyzeEntitySentimentAsync</summary>
public async Task AnalyzeEntitySentimentAsync_RequestObject()
{
// Snippet: AnalyzeEntitySentimentAsync(AnalyzeEntitySentimentRequest,CallSettings)
// Additional: AnalyzeEntitySentimentAsync(AnalyzeEntitySentimentRequest,CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
AnalyzeEntitySentimentRequest request = new AnalyzeEntitySentimentRequest
{
Document = new Document(),
};
// Make the request
AnalyzeEntitySentimentResponse response = await languageServiceClient.AnalyzeEntitySentimentAsync(request);
// End snippet
}
/// <summary>Snippet for AnalyzeEntitySentiment</summary>
public void AnalyzeEntitySentiment_RequestObject()
{
// Snippet: AnalyzeEntitySentiment(AnalyzeEntitySentimentRequest,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
AnalyzeEntitySentimentRequest request = new AnalyzeEntitySentimentRequest
{
Document = new Document(),
};
// Make the request
AnalyzeEntitySentimentResponse response = languageServiceClient.AnalyzeEntitySentiment(request);
// End snippet
}
/// <summary>Snippet for AnalyzeSyntaxAsync</summary>
public async Task AnalyzeSyntaxAsync()
{
// Snippet: AnalyzeSyntaxAsync(Document,EncodingType?,CallSettings)
// Additional: AnalyzeSyntaxAsync(Document,EncodingType?,CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
Document document = new Document();
EncodingType encodingType = EncodingType.None;
// Make the request
AnalyzeSyntaxResponse response = await languageServiceClient.AnalyzeSyntaxAsync(document, encodingType);
// End snippet
}
/// <summary>Snippet for AnalyzeSyntax</summary>
public void AnalyzeSyntax()
{
// Snippet: AnalyzeSyntax(Document,EncodingType?,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
Document document = new Document();
EncodingType encodingType = EncodingType.None;
// Make the request
AnalyzeSyntaxResponse response = languageServiceClient.AnalyzeSyntax(document, encodingType);
// End snippet
}
/// <summary>Snippet for AnalyzeSyntaxAsync</summary>
public async Task AnalyzeSyntaxAsync_RequestObject()
{
// Snippet: AnalyzeSyntaxAsync(AnalyzeSyntaxRequest,CallSettings)
// Additional: AnalyzeSyntaxAsync(AnalyzeSyntaxRequest,CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
AnalyzeSyntaxRequest request = new AnalyzeSyntaxRequest
{
Document = new Document(),
};
// Make the request
AnalyzeSyntaxResponse response = await languageServiceClient.AnalyzeSyntaxAsync(request);
// End snippet
}
/// <summary>Snippet for AnalyzeSyntax</summary>
public void AnalyzeSyntax_RequestObject()
{
// Snippet: AnalyzeSyntax(AnalyzeSyntaxRequest,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
AnalyzeSyntaxRequest request = new AnalyzeSyntaxRequest
{
Document = new Document(),
};
// Make the request
AnalyzeSyntaxResponse response = languageServiceClient.AnalyzeSyntax(request);
// End snippet
}
/// <summary>Snippet for ClassifyTextAsync</summary>
public async Task ClassifyTextAsync()
{
// Snippet: ClassifyTextAsync(Document,CallSettings)
// Additional: ClassifyTextAsync(Document,CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
Document document = new Document();
// Make the request
ClassifyTextResponse response = await languageServiceClient.ClassifyTextAsync(document);
// End snippet
}
/// <summary>Snippet for ClassifyText</summary>
public void ClassifyText()
{
// Snippet: ClassifyText(Document,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
Document document = new Document();
// Make the request
ClassifyTextResponse response = languageServiceClient.ClassifyText(document);
// End snippet
}
/// <summary>Snippet for ClassifyTextAsync</summary>
public async Task ClassifyTextAsync_RequestObject()
{
// Snippet: ClassifyTextAsync(ClassifyTextRequest,CallSettings)
// Additional: ClassifyTextAsync(ClassifyTextRequest,CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
ClassifyTextRequest request = new ClassifyTextRequest
{
Document = new Document(),
};
// Make the request
ClassifyTextResponse response = await languageServiceClient.ClassifyTextAsync(request);
// End snippet
}
/// <summary>Snippet for ClassifyText</summary>
public void ClassifyText_RequestObject()
{
// Snippet: ClassifyText(ClassifyTextRequest,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
ClassifyTextRequest request = new ClassifyTextRequest
{
Document = new Document(),
};
// Make the request
ClassifyTextResponse response = languageServiceClient.ClassifyText(request);
// End snippet
}
/// <summary>Snippet for AnnotateTextAsync</summary>
public async Task AnnotateTextAsync()
{
// Snippet: AnnotateTextAsync(Document,AnnotateTextRequest.Types.Features,EncodingType?,CallSettings)
// Additional: AnnotateTextAsync(Document,AnnotateTextRequest.Types.Features,EncodingType?,CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
Document document = new Document();
AnnotateTextRequest.Types.Features features = new AnnotateTextRequest.Types.Features();
EncodingType encodingType = EncodingType.None;
// Make the request
AnnotateTextResponse response = await languageServiceClient.AnnotateTextAsync(document, features, encodingType);
// End snippet
}
/// <summary>Snippet for AnnotateText</summary>
public void AnnotateText()
{
// Snippet: AnnotateText(Document,AnnotateTextRequest.Types.Features,EncodingType?,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
Document document = new Document();
AnnotateTextRequest.Types.Features features = new AnnotateTextRequest.Types.Features();
EncodingType encodingType = EncodingType.None;
// Make the request
AnnotateTextResponse response = languageServiceClient.AnnotateText(document, features, encodingType);
// End snippet
}
/// <summary>Snippet for AnnotateTextAsync</summary>
public async Task AnnotateTextAsync_RequestObject()
{
// Snippet: AnnotateTextAsync(AnnotateTextRequest,CallSettings)
// Additional: AnnotateTextAsync(AnnotateTextRequest,CancellationToken)
// Create client
LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync();
// Initialize request argument(s)
AnnotateTextRequest request = new AnnotateTextRequest
{
Document = new Document(),
Features = new AnnotateTextRequest.Types.Features(),
};
// Make the request
AnnotateTextResponse response = await languageServiceClient.AnnotateTextAsync(request);
// End snippet
}
/// <summary>Snippet for AnnotateText</summary>
public void AnnotateText_RequestObject()
{
// Snippet: AnnotateText(AnnotateTextRequest,CallSettings)
// Create client
LanguageServiceClient languageServiceClient = LanguageServiceClient.Create();
// Initialize request argument(s)
AnnotateTextRequest request = new AnnotateTextRequest
{
Document = new Document(),
Features = new AnnotateTextRequest.Types.Features(),
};
// Make the request
AnnotateTextResponse response = languageServiceClient.AnnotateText(request);
// End snippet
}
}
}
| |
namespace Macabresoft.Macabre2D.Framework;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.Serialization;
using Macabresoft.Core;
using Microsoft.Xna.Framework;
/// <summary>
/// Enumeration which defines how a circle's radius will scale when its body has a scale other
/// than (1, 1). This is necessary, because circle colliders need to stay circles. They cannot
/// become any other ellipse.
/// </summary>
public enum RadiusScalingType {
/// <summary>
/// No scaling will occur.
/// </summary>
None = 1,
/// <summary>
/// The circle's radius will scale on the body's X scale value.
/// </summary>
[Display(Name = "X Axis")]
X = 2,
/// <summary>
/// The circle's radius will scale on the body's Y scale value.
/// </summary>
[Display(Name = "Y Axis")]
Y = 3,
/// <summary>
/// The circle's radius will scale on an average of the body's X and Y scale values.
/// </summary>
Average = 4
}
/// <summary>
/// Collider representing a circle to be used by the physics engine.
/// </summary>
/// <seealso cref="Collider" />
[Display(Name = "Circle Collider")]
public sealed class CircleCollider : Collider {
private readonly ResettableLazy<float> _scaledRadius;
private float _radius = 1f;
private RadiusScalingType _radiusScalingType = RadiusScalingType.None;
/// <summary>
/// Initializes a new instance of the <see cref="CircleCollider" /> class.
/// </summary>
public CircleCollider() : base() {
this._scaledRadius = new ResettableLazy<float>(this.CreateScaledRadius);
}
/// <summary>
/// Initializes a new instance of the <see cref="CircleCollider" /> class.
/// </summary>
/// <param name="radius">The radius.</param>
public CircleCollider(float radius) : this() {
this.Radius = radius;
}
/// <summary>
/// Initializes a new instance of the <see cref="CircleCollider" /> class.
/// </summary>
/// <param name="radius">The radius.</param>
/// <param name="scalingType">Type of the scaling.</param>
public CircleCollider(float radius, RadiusScalingType scalingType) : this(radius) {
this._radiusScalingType = scalingType;
}
/// <summary>
/// Gets the center.
/// </summary>
/// <value>The center.</value>
public Vector2 Center => this.Transform.Position;
/// <inheritdoc />
public override ColliderType ColliderType => ColliderType.Circle;
/// <summary>
/// Gets the radius of this circle after all scaling operations have occurred.
/// </summary>
/// <value>The scaled radius.</value>
public float ScaledRadius => this._scaledRadius.Value;
/// <summary>
/// Gets or sets the radius.
/// </summary>
/// <value>The radius.</value>
[DataMember]
public float Radius {
get => this._radius;
set {
this._radius = value;
this.ResetLazyFields();
}
}
/// <summary>
/// Gets or sets the type of the radius scaling.
/// </summary>
/// <value>The type of the radius scaling.</value>
[DataMember(Name = "Radius Scaling")]
public RadiusScalingType RadiusScalingType {
get => this._radiusScalingType;
set {
if (this._radiusScalingType != value) {
this._radiusScalingType = value;
this.ResetLazyFields();
}
}
}
/// <inheritdoc />
public override bool Contains(Vector2 point) {
// Do we want to do <= here?
return Vector2.Distance(point, this.Center) <= this.ScaledRadius;
}
/// <inheritdoc />
public override bool Contains(Collider other) {
if (other is CircleCollider circle) {
var distance = Vector2.Distance(this.Center, circle.Center);
return this.ScaledRadius > distance + circle.ScaledRadius; // Should this be >= ?
}
if (other is PolygonCollider polygon) {
foreach (var point in polygon.WorldPoints) {
if (!this.Contains(point)) {
return false;
}
}
return true;
}
return false;
}
/// <inheritdoc />
public override IReadOnlyCollection<Vector2> GetAxesForSat(Collider other) {
var axes = new List<Vector2>();
if (other is PolygonCollider polygon) {
var distance = float.MaxValue;
var closestPoint = polygon.WorldPoints.First();
foreach (var point in polygon.WorldPoints) {
// Find the closest point on the polygon to the circle
var currentDistance = Vector2.Distance(point, this.Center);
if (currentDistance < distance) {
distance = currentDistance;
closestPoint = point;
}
}
var axis = new Vector2(closestPoint.X - this.Center.X, closestPoint.Y - this.Center.Y);
axis.Normalize();
axes.Add(axis);
}
else if (other is CircleCollider circle) {
var axis = this.Center - circle.Center;
if (axis != Vector2.Zero) {
axis.Normalize();
}
else {
axis = new Vector2(0f, 1f);
}
axes.Add(axis);
}
return axes;
}
/// <inheritdoc />
public override Vector2 GetCenter() {
return this.Center;
}
/// <inheritdoc />
public override Projection GetProjection(Vector2 axis) {
var minimum = Vector2.Dot(axis, this.Center);
var maximum = minimum + this.ScaledRadius;
minimum -= this.ScaledRadius;
return new Projection(axis, minimum, maximum);
}
/// <inheritdoc />
protected override BoundingArea CreateBoundingArea() {
return new BoundingArea(
this.Center.X - this.ScaledRadius,
this.Center.X + this.ScaledRadius,
this.Center.Y - this.ScaledRadius,
this.Center.Y + this.ScaledRadius);
}
/// <inheritdoc />
protected override void ResetLazyFields() {
base.ResetLazyFields();
this.ResetScaledRadius();
}
/// <inheritdoc />
protected override bool TryHit(LineSegment ray, out RaycastHit result) {
var distanceX = ray.Direction.X * ray.Distance;
var distanceY = ray.Direction.Y * ray.Distance;
var valueA = (float)(Math.Pow(distanceX, 2) + Math.Pow(distanceY, 2));
if (valueA <= 0.0000001f) {
result = RaycastHit.Empty;
return false;
}
var valueB = 2f * (distanceX * (ray.Start.X - this.Center.X) + distanceY * (ray.Start.Y - this.Center.Y));
var valueC = Math.Pow(ray.Start.X - this.Center.X, 2f) + Math.Pow(ray.Start.Y - this.Center.Y, 2f) - Math.Pow(this.ScaledRadius, 2f);
var det = Math.Pow(valueB, 2f) - 4f * valueA * valueC;
if (det < 0f) {
result = RaycastHit.Empty;
return false;
}
if (det == 0f) {
var t = -valueB / (2f * valueA);
var intersection = new Vector2(ray.Start.X + t * distanceX, ray.Start.Y + t * distanceY);
var normal = intersection - this.Center;
normal.Normalize();
result = new RaycastHit(this, intersection, normal);
}
else {
var t = (float)((-valueB + Math.Sqrt(det)) / (2f * valueA));
var intersectionA = new Vector2(ray.Start.X + t * distanceX, ray.Start.Y + t * distanceY);
t = (float)((-valueB - Math.Sqrt(det)) / (2f * valueA));
var intersectionB = new Vector2(ray.Start.X + t * distanceX, ray.Start.Y + t * distanceY);
if (Vector2.Distance(ray.Start, intersectionA) < Vector2.Distance(ray.Start, intersectionB)) {
var normal = intersectionA - this.Center;
normal.Normalize();
result = new RaycastHit(this, intersectionA, normal);
}
else {
var normal = intersectionB - this.Center;
normal.Normalize();
result = new RaycastHit(this, intersectionB, normal);
}
}
return true;
}
private float CreateScaledRadius() {
var result = this._radius;
if (this.Body != null) {
var worldTransform = this.Body.Transform;
result = this.RadiusScalingType switch {
RadiusScalingType.X => this._radius * worldTransform.Scale.X,
RadiusScalingType.Y => this._radius * worldTransform.Scale.Y,
RadiusScalingType.Average => this._radius * 0.5f * (worldTransform.Scale.X + worldTransform.Scale.Y),
_ => result
};
}
return result;
}
private void ResetScaledRadius() {
this._scaledRadius.Reset();
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
[Export(typeof(MiscellaneousFilesWorkspace))]
internal sealed partial class MiscellaneousFilesWorkspace : Workspace, IVsRunningDocTableEvents2, IVisualStudioHostProjectContainer
{
private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService;
private readonly IMetadataAsSourceFileService _fileTrackingMetadataAsSourceService;
private readonly IVsRunningDocumentTable4 _runningDocumentTable;
private readonly IVsTextManager _textManager;
private readonly RoslynDocumentProvider _documentProvider;
private readonly Dictionary<Guid, LanguageInformation> _languageInformationByLanguageGuid = new Dictionary<Guid, LanguageInformation>();
private readonly HashSet<DocumentKey> _filesInProjects = new HashSet<DocumentKey>();
private readonly Dictionary<ProjectId, HostProject> _hostProjects = new Dictionary<ProjectId, HostProject>();
private readonly Dictionary<uint, HostProject> _docCookiesToHostProject = new Dictionary<uint, HostProject>();
private readonly ImmutableArray<MetadataReference> _metadataReferences;
private uint _runningDocumentTableEventsCookie;
// document worker coordinator
private ISolutionCrawlerRegistrationService _registrationService;
[ImportingConstructor]
public MiscellaneousFilesWorkspace(
IVsEditorAdaptersFactoryService editorAdaptersFactoryService,
IMetadataAsSourceFileService fileTrackingMetadataAsSourceService,
SaveEventsService saveEventsService,
VisualStudioWorkspace visualStudioWorkspace,
SVsServiceProvider serviceProvider) :
base(visualStudioWorkspace.Services.HostServices, "MiscellaneousFiles")
{
_editorAdaptersFactoryService = editorAdaptersFactoryService;
_fileTrackingMetadataAsSourceService = fileTrackingMetadataAsSourceService;
_runningDocumentTable = (IVsRunningDocumentTable4)serviceProvider.GetService(typeof(SVsRunningDocumentTable));
_textManager = (IVsTextManager)serviceProvider.GetService(typeof(SVsTextManager));
((IVsRunningDocumentTable)_runningDocumentTable).AdviseRunningDocTableEvents(this, out _runningDocumentTableEventsCookie);
_metadataReferences = ImmutableArray.CreateRange(CreateMetadataReferences());
_documentProvider = new RoslynDocumentProvider(this, serviceProvider);
saveEventsService.StartSendingSaveEvents();
}
public void RegisterLanguage(Guid languageGuid, string languageName, string scriptExtension, ParseOptions parseOptions)
{
_languageInformationByLanguageGuid.Add(languageGuid, new LanguageInformation(languageName, scriptExtension, parseOptions));
}
internal void StartSolutionCrawler()
{
if (_registrationService == null)
{
lock (this)
{
if (_registrationService == null)
{
_registrationService = this.Services.GetService<ISolutionCrawlerRegistrationService>();
_registrationService.Register(this);
}
}
}
}
internal void StopSolutionCrawler()
{
if (_registrationService != null)
{
lock (this)
{
if (_registrationService != null)
{
_registrationService.Unregister(this, blockingShutdown: true);
_registrationService = null;
}
}
}
}
private LanguageInformation TryGetLanguageInformation(string filename)
{
Guid fileLanguageGuid;
LanguageInformation languageInformation = null;
if (ErrorHandler.Succeeded(_textManager.MapFilenameToLanguageSID(filename, out fileLanguageGuid)))
{
_languageInformationByLanguageGuid.TryGetValue(fileLanguageGuid, out languageInformation);
}
return languageInformation;
}
private IEnumerable<MetadataReference> CreateMetadataReferences()
{
var manager = this.Services.GetService<VisualStudioMetadataReferenceManager>();
var searchPaths = ReferencePathUtilities.GetReferencePaths();
return from fileName in new[] { "mscorlib.dll", "System.dll", "System.Core.dll" }
let fullPath = FileUtilities.ResolveRelativePath(fileName, basePath: null, baseDirectory: null, searchPaths: searchPaths, fileExists: File.Exists)
where fullPath != null
select manager.CreateMetadataReferenceSnapshot(fullPath, MetadataReferenceProperties.Assembly);
}
internal void OnFileIncludedInProject(IVisualStudioHostDocument document)
{
uint docCookie;
if (_runningDocumentTable.TryGetCookieForInitializedDocument(document.FilePath, out docCookie))
{
TryRemoveDocumentFromMiscellaneousWorkspace(docCookie, document.FilePath);
}
_filesInProjects.Add(document.Key);
}
internal void OnFileRemovedFromProject(IVisualStudioHostDocument document)
{
// Remove the document key from the filesInProjects map first because adding documents
// to the misc files workspace requires that they not appear in this map.
_filesInProjects.Remove(document.Key);
uint docCookie;
if (_runningDocumentTable.TryGetCookieForInitializedDocument(document.Key.Moniker, out docCookie))
{
AddDocumentToMiscellaneousOrMetadataAsSourceWorkspace(docCookie, document.Key.Moniker);
}
}
public int OnAfterAttributeChange(uint docCookie, uint grfAttribs)
{
return VSConstants.S_OK;
}
public int OnAfterAttributeChangeEx(uint docCookie, uint grfAttribs, IVsHierarchy pHierOld, uint itemidOld, string pszMkDocumentOld, IVsHierarchy pHierNew, uint itemidNew, string pszMkDocumentNew)
{
// Did we rename?
if ((grfAttribs & (uint)__VSRDTATTRIB.RDTA_MkDocument) != 0)
{
// We want to consider this file to be added in one of two situations:
//
// 1) the old file already was a misc file, at which point we might just be doing a rename from
// one name to another with the same extension
// 2) the old file was a different extension that we weren't tracking, which may have now changed
if (TryRemoveDocumentFromMiscellaneousWorkspace(docCookie, pszMkDocumentOld) || TryGetLanguageInformation(pszMkDocumentOld) == null)
{
// Add the new one, if appropriate.
AddDocumentToMiscellaneousOrMetadataAsSourceWorkspace(docCookie, pszMkDocumentNew);
}
}
// When starting a diff, the RDT doesn't call OnBeforeDocumentWindowShow, but it does call
// OnAfterAttributeChangeEx for the temporary buffer. The native IDE used this even to
// add misc files, so we'll do the same.
if ((grfAttribs & (uint)__VSRDTATTRIB.RDTA_DocDataReloaded) != 0)
{
var moniker = _runningDocumentTable.GetDocumentMoniker(docCookie);
if (moniker != null && TryGetLanguageInformation(moniker) != null && !_docCookiesToHostProject.ContainsKey(docCookie))
{
AddDocumentToMiscellaneousOrMetadataAsSourceWorkspace(docCookie, moniker);
}
}
return VSConstants.S_OK;
}
public int OnAfterDocumentWindowHide(uint docCookie, IVsWindowFrame pFrame)
{
return VSConstants.E_NOTIMPL;
}
public int OnAfterFirstDocumentLock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining)
{
return VSConstants.E_NOTIMPL;
}
public int OnAfterSave(uint docCookie)
{
return VSConstants.E_NOTIMPL;
}
public int OnBeforeDocumentWindowShow(uint docCookie, int fFirstShow, IVsWindowFrame pFrame)
{
return VSConstants.E_NOTIMPL;
}
public int OnBeforeLastDocumentUnlock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining)
{
if (dwReadLocksRemaining + dwEditLocksRemaining == 0)
{
TryRemoveDocumentFromMiscellaneousWorkspace(docCookie, _runningDocumentTable.GetDocumentMoniker(docCookie));
}
return VSConstants.S_OK;
}
private void AddDocumentToMiscellaneousOrMetadataAsSourceWorkspace(uint docCookie, string moniker)
{
var languageInformation = TryGetLanguageInformation(moniker);
if (languageInformation != null &&
!_filesInProjects.Any(d => StringComparer.OrdinalIgnoreCase.Equals(d.Moniker, moniker)) &&
!_docCookiesToHostProject.ContainsKey(docCookie))
{
// See if we should push to this to the metadata-to-source workspace instead.
if (_runningDocumentTable.IsDocumentInitialized(docCookie))
{
var vsTextBuffer = (IVsTextBuffer)_runningDocumentTable.GetDocumentData(docCookie);
var textBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(vsTextBuffer);
if (_fileTrackingMetadataAsSourceService.TryAddDocumentToWorkspace(moniker, textBuffer))
{
// We already added it, so we will keep it excluded from the misc files workspace
return;
}
}
var parseOptions = languageInformation.ParseOptions;
if (Path.GetExtension(moniker) == languageInformation.ScriptExtension)
{
parseOptions = parseOptions.WithKind(SourceCodeKind.Script);
}
// First, create the project
var hostProject = new HostProject(this, CurrentSolution.Id, languageInformation.LanguageName, parseOptions, _metadataReferences);
// Now try to find the document. We accept any text buffer, since we've already verified it's an appropriate file in ShouldIncludeFile.
var document = _documentProvider.TryGetDocumentForFile(hostProject, (uint)VSConstants.VSITEMID.Nil, moniker, parseOptions.Kind, t => true);
// If the buffer has not yet been initialized, we won't get a document.
if (document == null)
{
return;
}
// Since we have a document, we can do the rest of the project setup.
_hostProjects.Add(hostProject.Id, hostProject);
OnProjectAdded(hostProject.CreateProjectInfoForCurrentState());
OnDocumentAdded(document.GetInitialState());
hostProject.Document = document;
// Notify the document provider, so it knows the document is now open and a part of
// the project
_documentProvider.NotifyDocumentRegisteredToProject(document);
Contract.ThrowIfFalse(document.IsOpen);
var buffer = document.GetOpenTextBuffer();
OnDocumentOpened(document.Id, document.GetOpenTextContainer());
_docCookiesToHostProject.Add(docCookie, hostProject);
}
}
private bool TryRemoveDocumentFromMiscellaneousWorkspace(uint docCookie, string moniker)
{
HostProject hostProject;
if (_fileTrackingMetadataAsSourceService.TryRemoveDocumentFromWorkspace(moniker))
{
return true;
}
if (_docCookiesToHostProject.TryGetValue(docCookie, out hostProject))
{
var document = hostProject.Document;
OnDocumentClosed(document.Id, document.Loader);
OnDocumentRemoved(document.Id);
OnProjectRemoved(hostProject.Id);
_hostProjects.Remove(hostProject.Id);
_docCookiesToHostProject.Remove(docCookie);
return true;
}
return false;
}
protected override void Dispose(bool finalize)
{
StopSolutionCrawler();
var runningDocumentTableForEvents = (IVsRunningDocumentTable)_runningDocumentTable;
runningDocumentTableForEvents.UnadviseRunningDocTableEvents(_runningDocumentTableEventsCookie);
_runningDocumentTableEventsCookie = 0;
base.Dispose(finalize);
}
public override bool CanApplyChange(ApplyChangesKind feature)
{
switch (feature)
{
case ApplyChangesKind.ChangeDocument:
return true;
default:
return false;
}
}
protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText newText)
{
var hostDocument = this.GetDocument(documentId);
hostDocument.UpdateText(newText);
}
private HostProject GetHostProject(ProjectId id)
{
HostProject project;
_hostProjects.TryGetValue(id, out project);
return project;
}
internal IVisualStudioHostDocument GetDocument(DocumentId id)
{
var project = GetHostProject(id.ProjectId);
if (project != null && project.Document.Id == id)
{
return project.Document;
}
return null;
}
IEnumerable<IVisualStudioHostProject> IVisualStudioHostProjectContainer.GetProjects()
{
return _hostProjects.Values;
}
private class LanguageInformation
{
public LanguageInformation(string languageName, string scriptExtension, ParseOptions parseOptions)
{
this.LanguageName = languageName;
this.ScriptExtension = scriptExtension;
this.ParseOptions = parseOptions;
}
public string LanguageName { get; }
public string ScriptExtension { get; }
public ParseOptions ParseOptions { get; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
using System.Runtime.Serialization;
namespace System.IO
{
[Serializable]
public sealed partial class DirectoryInfo : FileSystemInfo
{
[System.Security.SecuritySafeCritical]
public DirectoryInfo(String path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
Contract.EndContractBlock();
OriginalPath = PathHelpers.ShouldReviseDirectoryPathToCurrent(path) ? "." : path;
FullPath = Path.GetFullPath(path);
DisplayPath = GetDisplayName(OriginalPath);
}
[System.Security.SecuritySafeCritical]
internal DirectoryInfo(String fullPath, String originalPath)
{
Debug.Assert(Path.IsPathRooted(fullPath), "fullPath must be fully qualified!");
// Fast path when we know a DirectoryInfo exists.
OriginalPath = originalPath ?? Path.GetFileName(fullPath);
FullPath = fullPath;
DisplayPath = GetDisplayName(OriginalPath);
}
private DirectoryInfo(SerializationInfo info, StreamingContext context) : base(info, context)
{
DisplayPath = GetDisplayName(OriginalPath);
}
public override String Name
{
get
{
return GetDirName(FullPath);
}
}
public DirectoryInfo Parent
{
[System.Security.SecuritySafeCritical]
get
{
string s = FullPath;
// FullPath might end in either "parent\child" or "parent\child", and in either case we want
// the parent of child, not the child. Trim off an ending directory separator if there is one,
// but don't mangle the root.
if (!PathHelpers.IsRoot(s))
{
s = PathHelpers.TrimEndingDirectorySeparator(s);
}
string parentName = Path.GetDirectoryName(s);
return parentName != null ?
new DirectoryInfo(parentName, null) :
null;
}
}
[System.Security.SecuritySafeCritical]
public DirectoryInfo CreateSubdirectory(String path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
Contract.EndContractBlock();
return CreateSubdirectoryHelper(path);
}
[System.Security.SecurityCritical] // auto-generated
private DirectoryInfo CreateSubdirectoryHelper(String path)
{
Debug.Assert(path != null);
PathHelpers.ThrowIfEmptyOrRootedPath(path);
String newDirs = Path.Combine(FullPath, path);
String fullPath = Path.GetFullPath(newDirs);
if (0 != String.Compare(FullPath, 0, fullPath, 0, FullPath.Length, PathInternal.StringComparison))
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidSubPath, path, DisplayPath), nameof(path));
}
FileSystem.Current.CreateDirectory(fullPath);
// Check for read permission to directory we hand back by calling this constructor.
return new DirectoryInfo(fullPath);
}
[System.Security.SecurityCritical]
public void Create()
{
FileSystem.Current.CreateDirectory(FullPath);
}
// Tests if the given path refers to an existing DirectoryInfo on disk.
//
// Your application must have Read permission to the directory's
// contents.
//
public override bool Exists
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
try
{
return FileSystemObject.Exists;
}
catch
{
return false;
}
}
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search criteria (i.e. "*.txt").
[SecurityCritical]
public FileInfo[] GetFiles(String searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
Contract.EndContractBlock();
return InternalGetFiles(searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search criteria (i.e. "*.txt").
public FileInfo[] GetFiles(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalGetFiles(searchPattern, searchOption);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search criteria (i.e. "*.txt").
private FileInfo[] InternalGetFiles(String searchPattern, SearchOption searchOption)
{
Debug.Assert(searchPattern != null);
Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
IEnumerable<FileInfo> enumerable = (IEnumerable<FileInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Files);
return EnumerableHelpers.ToArray(enumerable);
}
// Returns an array of Files in the DirectoryInfo specified by path
public FileInfo[] GetFiles()
{
return InternalGetFiles("*", SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current directory.
public DirectoryInfo[] GetDirectories()
{
return InternalGetDirectories("*", SearchOption.TopDirectoryOnly);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (i.e. "*.txt").
public FileSystemInfo[] GetFileSystemInfos(String searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
Contract.EndContractBlock();
return InternalGetFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (i.e. "*.txt").
public FileSystemInfo[] GetFileSystemInfos(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalGetFileSystemInfos(searchPattern, searchOption);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (i.e. "*.txt").
private FileSystemInfo[] InternalGetFileSystemInfos(String searchPattern, SearchOption searchOption)
{
Debug.Assert(searchPattern != null);
Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
IEnumerable<FileSystemInfo> enumerable = FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Both);
return EnumerableHelpers.ToArray(enumerable);
}
// Returns an array of strongly typed FileSystemInfo entries which will contain a listing
// of all the files and directories.
public FileSystemInfo[] GetFileSystemInfos()
{
return InternalGetFileSystemInfos("*", SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (i.e. "System*" could match the System & System32
// directories).
public DirectoryInfo[] GetDirectories(String searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
Contract.EndContractBlock();
return InternalGetDirectories(searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (i.e. "System*" could match the System & System32
// directories).
public DirectoryInfo[] GetDirectories(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalGetDirectories(searchPattern, searchOption);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (i.e. "System*" could match the System & System32
// directories).
private DirectoryInfo[] InternalGetDirectories(String searchPattern, SearchOption searchOption)
{
Debug.Assert(searchPattern != null);
Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
IEnumerable<DirectoryInfo> enumerable = (IEnumerable<DirectoryInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Directories);
return EnumerableHelpers.ToArray(enumerable);
}
public IEnumerable<DirectoryInfo> EnumerateDirectories()
{
return InternalEnumerateDirectories("*", SearchOption.TopDirectoryOnly);
}
public IEnumerable<DirectoryInfo> EnumerateDirectories(String searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
Contract.EndContractBlock();
return InternalEnumerateDirectories(searchPattern, SearchOption.TopDirectoryOnly);
}
public IEnumerable<DirectoryInfo> EnumerateDirectories(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalEnumerateDirectories(searchPattern, searchOption);
}
private IEnumerable<DirectoryInfo> InternalEnumerateDirectories(String searchPattern, SearchOption searchOption)
{
Debug.Assert(searchPattern != null);
Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return (IEnumerable<DirectoryInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Directories);
}
public IEnumerable<FileInfo> EnumerateFiles()
{
return InternalEnumerateFiles("*", SearchOption.TopDirectoryOnly);
}
public IEnumerable<FileInfo> EnumerateFiles(String searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
Contract.EndContractBlock();
return InternalEnumerateFiles(searchPattern, SearchOption.TopDirectoryOnly);
}
public IEnumerable<FileInfo> EnumerateFiles(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalEnumerateFiles(searchPattern, searchOption);
}
private IEnumerable<FileInfo> InternalEnumerateFiles(String searchPattern, SearchOption searchOption)
{
Debug.Assert(searchPattern != null);
Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return (IEnumerable<FileInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Files);
}
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos()
{
return InternalEnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly);
}
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(String searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
Contract.EndContractBlock();
return InternalEnumerateFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly);
}
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalEnumerateFileSystemInfos(searchPattern, searchOption);
}
private IEnumerable<FileSystemInfo> InternalEnumerateFileSystemInfos(String searchPattern, SearchOption searchOption)
{
Debug.Assert(searchPattern != null);
Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Both);
}
// Returns the root portion of the given path. The resulting string
// consists of those rightmost characters of the path that constitute the
// root of the path. Possible patterns for the resulting string are: An
// empty string (a relative path on the current drive), "\" (an absolute
// path on the current drive), "X:" (a relative path on a given drive,
// where X is the drive letter), "X:\" (an absolute path on a given drive),
// and "\\server\share" (a UNC path for a given server and share name).
// The resulting string is null if path is null.
//
public DirectoryInfo Root
{
[System.Security.SecuritySafeCritical]
get
{
String rootPath = Path.GetPathRoot(FullPath);
return new DirectoryInfo(rootPath);
}
}
[System.Security.SecuritySafeCritical]
public void MoveTo(String destDirName)
{
if (destDirName == null)
throw new ArgumentNullException(nameof(destDirName));
if (destDirName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destDirName));
Contract.EndContractBlock();
String fullDestDirName = Path.GetFullPath(destDirName);
if (fullDestDirName[fullDestDirName.Length - 1] != Path.DirectorySeparatorChar)
fullDestDirName = fullDestDirName + PathHelpers.DirectorySeparatorCharAsString;
String fullSourcePath;
if (FullPath.Length > 0 && FullPath[FullPath.Length - 1] == Path.DirectorySeparatorChar)
fullSourcePath = FullPath;
else
fullSourcePath = FullPath + PathHelpers.DirectorySeparatorCharAsString;
if (PathInternal.IsDirectoryTooLong(fullSourcePath))
throw new PathTooLongException(SR.IO_PathTooLong);
if (PathInternal.IsDirectoryTooLong(fullDestDirName))
throw new PathTooLongException(SR.IO_PathTooLong);
StringComparison pathComparison = PathInternal.StringComparison;
if (String.Equals(fullSourcePath, fullDestDirName, pathComparison))
throw new IOException(SR.IO_SourceDestMustBeDifferent);
String sourceRoot = Path.GetPathRoot(fullSourcePath);
String destinationRoot = Path.GetPathRoot(fullDestDirName);
if (!String.Equals(sourceRoot, destinationRoot, pathComparison))
throw new IOException(SR.IO_SourceDestMustHaveSameRoot);
if (!Exists)
throw new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, FullPath));
if (FileSystem.Current.DirectoryExists(fullDestDirName))
throw new IOException(SR.Format(SR.IO_AlreadyExists_Name, fullDestDirName));
FileSystem.Current.MoveDirectory(FullPath, fullDestDirName);
FullPath = fullDestDirName;
OriginalPath = destDirName;
DisplayPath = GetDisplayName(OriginalPath);
// Flush any cached information about the directory.
Invalidate();
}
[System.Security.SecuritySafeCritical]
public override void Delete()
{
FileSystem.Current.RemoveDirectory(FullPath, false);
}
[System.Security.SecuritySafeCritical]
public void Delete(bool recursive)
{
FileSystem.Current.RemoveDirectory(FullPath, recursive);
}
/// <summary>
/// Returns the original path. Use FullPath or Name properties for the path / directory name.
/// </summary>
public override String ToString()
{
return DisplayPath;
}
private static String GetDisplayName(String originalPath)
{
Debug.Assert(originalPath != null);
// Desktop documents that the path returned by ToString() should be the original path.
// For SL/Phone we only gave the directory name regardless of what was passed in.
return PathHelpers.ShouldReviseDirectoryPathToCurrent(originalPath) ?
"." :
originalPath;
}
private static String GetDirName(String fullPath)
{
Debug.Assert(fullPath != null);
return PathHelpers.IsRoot(fullPath) ?
fullPath :
Path.GetFileName(PathHelpers.TrimEndingDirectorySeparator(fullPath));
}
}
}
| |
//
// 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.
//
namespace NLog
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Internal.Fakeables;
/// <summary>
/// Creates and manages instances of <see cref="T:NLog.Logger" /> objects.
/// </summary>
public sealed class LogManager
{
private static readonly LogFactory factory = new LogFactory();
private static IAppDomain currentAppDomain;
private static ICollection<Assembly> _hiddenAssemblies;
private static readonly object lockObject = new object();
/// <summary>
/// Delegate used to set/get the culture in use.
/// </summary>
[Obsolete]
public delegate CultureInfo GetCultureInfo();
#if !SILVERLIGHT && !MONO
/// <summary>
/// Initializes static members of the LogManager class.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Significant logic in .cctor()")]
static LogManager()
{
SetupTerminationEvents();
}
#endif
/// <summary>
/// Prevents a default instance of the LogManager class from being created.
/// </summary>
private LogManager()
{
}
/// <summary>
/// Gets the default <see cref="NLog.LogFactory" /> instance.
/// </summary>
internal static LogFactory LogFactory
{
get { return factory; }
}
/// <summary>
/// Occurs when logging <see cref="Configuration" /> changes.
/// </summary>
public static event EventHandler<LoggingConfigurationChangedEventArgs> ConfigurationChanged
{
add { factory.ConfigurationChanged += value; }
remove { factory.ConfigurationChanged -= value; }
}
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
/// <summary>
/// Occurs when logging <see cref="Configuration" /> gets reloaded.
/// </summary>
public static event EventHandler<LoggingConfigurationReloadedEventArgs> ConfigurationReloaded
{
add { factory.ConfigurationReloaded += value; }
remove { factory.ConfigurationReloaded -= value; }
}
#endif
/// <summary>
/// Gets or sets a value indicating whether NLog should throw exceptions.
/// By default exceptions are not thrown under any circumstances.
/// </summary>
public static bool ThrowExceptions
{
get { return factory.ThrowExceptions; }
set { factory.ThrowExceptions = value; }
}
/// <summary>
/// Gets or sets a value indicating whether <see cref="NLogConfigurationException"/> should be thrown.
/// </summary>
/// <value>A value of <c>true</c> if exception should be thrown; otherwise, <c>false</c>.</value>
/// <remarks>
/// This option is for backwards-compatiblity.
/// By default exceptions are not thrown under any circumstances.
///
/// </remarks>
public static bool? ThrowConfigExceptions
{
get { return factory.ThrowConfigExceptions; }
set { factory.ThrowConfigExceptions = value; }
}
internal static IAppDomain CurrentAppDomain
{
get { return currentAppDomain ?? (currentAppDomain = AppDomainWrapper.CurrentDomain); }
set
{
#if !SILVERLIGHT && !MONO
currentAppDomain.DomainUnload -= TurnOffLogging;
currentAppDomain.ProcessExit -= TurnOffLogging;
#endif
currentAppDomain = value;
}
}
/// <summary>
/// Gets or sets the current logging configuration.
/// <see cref="NLog.LogFactory.Configuration" />
/// </summary>
public static LoggingConfiguration Configuration
{
get { return factory.Configuration; }
set { factory.Configuration = value; }
}
/// <summary>
/// Gets or sets the global log threshold. Log events below this threshold are not logged.
/// </summary>
public static LogLevel GlobalThreshold
{
get { return factory.GlobalThreshold; }
set { factory.GlobalThreshold = value; }
}
/// <summary>
/// Gets or sets the default culture to use.
/// </summary>
[Obsolete("Use Configuration.DefaultCultureInfo property instead")]
public static GetCultureInfo DefaultCultureInfo
{
get { return () => factory.DefaultCultureInfo ?? CultureInfo.CurrentCulture; }
set { throw new NotSupportedException("Setting the DefaultCultureInfo delegate is no longer supported. Use the Configuration.DefaultCultureInfo property to change the default CultureInfo."); }
}
/// <summary>
/// Gets the logger with the name of the current class.
/// </summary>
/// <returns>The logger.</returns>
/// <remarks>This is a slow-running method.
/// Make sure you're not doing this in a loop.</remarks>
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.NoInlining)]
public static Logger GetCurrentClassLogger()
{
return factory.GetLogger(GetClassFullName());
}
internal static bool IsHiddenAssembly(Assembly assembly)
{
return _hiddenAssemblies != null && _hiddenAssemblies.Contains(assembly);
}
/// <summary>
/// Adds the given assembly which will be skipped
/// when NLog is trying to find the calling method on stack trace.
/// </summary>
/// <param name="assembly">The assembly to skip.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
public static void AddHiddenAssembly(Assembly assembly)
{
lock (lockObject)
{
if (_hiddenAssemblies != null && _hiddenAssemblies.Contains(assembly))
return;
_hiddenAssemblies = new HashSet<Assembly>(_hiddenAssemblies ?? Enumerable.Empty<Assembly>())
{
assembly
};
}
}
/// <summary>
/// Gets a custom logger with the name of the current class. Use <paramref name="loggerType"/> to pass the type of the needed Logger.
/// </summary>
/// <param name="loggerType">The logger class. The class must inherit from <see cref="Logger" />.</param>
/// <returns>The logger of type <paramref name="loggerType"/>.</returns>
/// <remarks>This is a slow-running method.
/// Make sure you're not doing this in a loop.</remarks>
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.NoInlining)]
public static Logger GetCurrentClassLogger(Type loggerType)
{
return factory.GetLogger(GetClassFullName(), loggerType);
}
/// <summary>
/// Creates a logger that discards all log messages.
/// </summary>
/// <returns>Null logger which discards all log messages.</returns>
[CLSCompliant(false)]
public static Logger CreateNullLogger()
{
return factory.CreateNullLogger();
}
/// <summary>
/// Gets the specified named logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <returns>The logger reference. Multiple calls to <c>GetLogger</c> with the same argument aren't guaranteed to return the same logger reference.</returns>
[CLSCompliant(false)]
public static Logger GetLogger(string name)
{
return factory.GetLogger(name);
}
/// <summary>
/// Gets the specified named custom logger. Use <paramref name="loggerType"/> to pass the type of the needed Logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <param name="loggerType">The logger class. The class must inherit from <see cref="Logger" />.</param>
/// <returns>The logger of type <paramref name="loggerType"/>. Multiple calls to <c>GetLogger</c> with the same argument aren't guaranteed to return the same logger reference.</returns>
/// <remarks>The generic way for this method is <see cref="NLog.LogFactory{loggerType}.GetLogger(string)"/></remarks>
[CLSCompliant(false)]
public static Logger GetLogger(string name, Type loggerType)
{
return factory.GetLogger(name, loggerType);
}
/// <summary>
/// Loops through all loggers previously returned by GetLogger.
/// and recalculates their target and filter list. Useful after modifying the configuration programmatically
/// to ensure that all loggers have been properly configured.
/// </summary>
public static void ReconfigExistingLoggers()
{
factory.ReconfigExistingLoggers();
}
#if !SILVERLIGHT
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
public static void Flush()
{
factory.Flush();
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(TimeSpan timeout)
{
factory.Flush(timeout);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(int timeoutMilliseconds)
{
factory.Flush(timeoutMilliseconds);
}
#endif
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
public static void Flush(AsyncContinuation asyncContinuation)
{
factory.Flush(asyncContinuation);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(AsyncContinuation asyncContinuation, TimeSpan timeout)
{
factory.Flush(asyncContinuation, timeout);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(AsyncContinuation asyncContinuation, int timeoutMilliseconds)
{
factory.Flush(asyncContinuation, timeoutMilliseconds);
}
/// <summary>
/// Decreases the log enable counter and if it reaches -1 the logs are disabled.
/// </summary>
/// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater
/// than or equal to <see cref="DisableLogging"/> calls.</remarks>
/// <returns>An object that implements IDisposable whose Dispose() method reenables logging.
/// To be used with C# <c>using ()</c> statement.</returns>
public static IDisposable DisableLogging()
{
return factory.SuspendLogging();
}
/// <summary>
/// Increases the log enable counter and if it reaches 0 the logs are disabled.
/// </summary>
/// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater
/// than or equal to <see cref="DisableLogging"/> calls.</remarks>
public static void EnableLogging()
{
factory.ResumeLogging();
}
/// <summary>
/// Checks if logging is currently enabled.
/// </summary>
/// <returns><see langword="true" /> if logging is currently enabled, <see langword="false"/>
/// otherwise.</returns>
/// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater
/// than or equal to <see cref="DisableLogging"/> calls.</remarks>
public static bool IsLoggingEnabled()
{
return factory.IsLoggingEnabled();
}
/// <summary>
/// Dispose all targets, and shutdown logging.
/// </summary>
public static void Shutdown()
{
if (Configuration != null && Configuration.AllTargets != null)
{
foreach (var target in Configuration.AllTargets)
{
if (target != null) target.Dispose();
}
}
if (Configuration != null && Configuration.PoolFactory != null)
{
Configuration.PoolFactory.Dispose();
}
}
#if !SILVERLIGHT && !MONO
private static void SetupTerminationEvents()
{
try
{
CurrentAppDomain.ProcessExit += TurnOffLogging;
CurrentAppDomain.DomainUnload += TurnOffLogging;
}
catch (Exception exception)
{
InternalLogger.Warn(exception, "Error setting up termination events.");
if (exception.MustBeRethrown())
{
throw;
}
}
}
#endif
/// <summary>
/// Gets the fully qualified name of the class invoking the LogManager, including the
/// namespace but not the assembly.
/// </summary>
private static string GetClassFullName()
{
string className;
Type declaringType;
int framesToSkip = 2;
do
{
#if SILVERLIGHT
StackFrame frame = new StackTrace().GetFrame(framesToSkip);
#else
StackFrame frame = new StackFrame(framesToSkip, false);
#endif
MethodBase method = frame.GetMethod();
declaringType = method.DeclaringType;
if (declaringType == null)
{
className = method.Name;
break;
}
framesToSkip++;
className = declaringType.FullName;
} while (declaringType.Module.Name.Equals("mscorlib.dll", StringComparison.OrdinalIgnoreCase));
return className;
}
private static void TurnOffLogging(object sender, EventArgs args)
{
// Reset logging configuration to null; this causes old configuration (if any) to be
// closed.
InternalLogger.Info("Shutting down logging...");
Configuration = null;
InternalLogger.Info("Logger has been shut down.");
}
}
}
| |
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using TestHelper;
using CommandLine;
using CommandLine.Analyzer;
namespace CommandLine.Test
{
[TestClass]
public class UnitTest : DiagnosticVerifier
{
[TestCategory("Analyzer")]
[TestMethod]
public void NoErrorExpectedForNoCode()
{
var test = @"";
VerifyCommandLineDiagnostic(test);
}
[TestMethod]
[TestCategory("Samples")]
public void NoErrorExpectedForSample_Simple()
{
var test = @"
using CommandLine.Attributes;
class Options
{
[RequiredArgument(0,""dir"",""Directory"")]
public string Directory { get; set; }
[OptionalArgument(""*.*"", ""pattern"", ""Search pattern"")]
public string SearchPattern { get; set; }
}
";
VerifyCommandLineDiagnostic(test);
}
[TestMethod]
[TestCategory("Samples")]
public void NoErrorExpectedForSample_Advanced()
{
var test = @"
using CommandLine.Attributes;
using CommandLine.Attributes.Advanced;
internal enum CommandLineActionGroup { add, remove }
internal class CommandLineOptions
{
[ActionArgument]
public CommandLineActionGroup Action { get; set; }
[CommonArgument]
[RequiredArgumentAttribute(0, ""host"", ""The name of the host"")]
public string Host { get; set; }
#region Add-host Action
[RequiredArgument(1, ""mac"", ""The MAC address of the host"")]
[ArgumentGroup(nameof(CommandLineActionGroup.add))]
public string MAC { get; set; }
#endregion
}
";
VerifyCommandLineDiagnostic(test);
}
[TestCategory("Analyzer")]
[TestMethod]
public void TwoPropertiesOnTheSamePosition()
{
var test = @"
using CommandLine.Attributes;
class Options
{
[RequiredArgument(0, ""dir"", ""Directory"")]
public string Directory { get; set; }
[RequiredArgument(0, ""bar"", ""Directory2"")]
public string Directory2 { get; set; }
}";
var expected1 = new DiagnosticResult
{
Id = "CMDNET01",
Message = "The class defines two required properties on the same position ('0').",
Severity = DiagnosticSeverity.Error,
Locations =
new[] {
new DiagnosticResultLocation("Test0.cs", 9, 19)
}
};
var expected2 = new DiagnosticResult
{
Id = "CMDNET07",
Message = "The type declares '2' properties as required. The property positions are 0-based. Could not find required argument at position '1'.",
Severity = DiagnosticSeverity.Error,
Locations =
new[] {
new DiagnosticResultLocation("Test0.cs", 3, 7)
}
};
VerifyCommandLineDiagnostic(test, expected2, expected1);
}
[TestCategory("Analyzer")]
[TestMethod]
public void TwoPropertiesWithTheSameName_BothRequired()
{
var test = @"
using CommandLine.Attributes;
class Options
{
[RequiredArgument(0, ""dir"", ""Directory"")]
public string Directory { get; set; }
[RequiredArgument(1, ""dir"", ""Directory2"")]
public string Directory2 { get; set; }
}";
var expected = new DiagnosticResult
{
Id = "CMDNET02",
Message = "The class defines two propeties with the same name ('dir').",
Severity = DiagnosticSeverity.Error,
Locations =
new[] {
new DiagnosticResultLocation("Test0.cs", 9, 19)
}
};
VerifyCommandLineDiagnostic(test, expected);
}
[TestCategory("Analyzer")]
[TestMethod]
public void TwoPropertiesWithTheSameName_BothOptional()
{
var test = @"
using CommandLine.Attributes;
class Options
{
[OptionalArgument(""0"", ""dir"", ""Directory"")]
public string Directory { get; set; }
[OptionalArgument(""1"", ""dir"", ""Directory2"")]
public string Directory2 { get; set; }
}";
var expected = new DiagnosticResult
{
Id = "CMDNET02",
Message = "The class defines two propeties with the same name ('dir').",
Severity = DiagnosticSeverity.Error,
Locations =
new[] {
new DiagnosticResultLocation("Test0.cs", 9, 19)
}
};
VerifyCommandLineDiagnostic(test, expected);
}
[TestCategory("Analyzer")]
[TestMethod]
public void TwoPropertiesWithTheSameName_RequiredAndOptional()
{
var test = @"
using CommandLine.Attributes;
class Options
{
[RequiredArgument(0, ""dir"", ""Directory"")]
public string Directory { get; set; }
[OptionalArgument(""1"", ""dir"", ""Directory2"")]
public string Directory2 { get; set; }
}";
var expected = new DiagnosticResult
{
Id = "CMDNET02",
Message = "The class defines two propeties with the same name ('dir').",
Severity = DiagnosticSeverity.Error,
Locations =
new[] {
new DiagnosticResultLocation("Test0.cs", 9, 19)
}
};
VerifyCommandLineDiagnostic(test, expected);
}
[TestCategory("Analyzer")]
[TestMethod]
public void RequiredAndOptionalArgumentOnProperty()
{
var test = @"
using CommandLine.Attributes;
class Options
{
[OptionalArgument(""aa"", ""dir"", ""Directory"")]
[RequiredArgument(0, ""dir"", ""Directory"")]
public string Directory { get; set; }
}";
var expected = new DiagnosticResult
{
Id = "CMDNET06",
Message = "The property cannot be both required and optional.",
Severity = DiagnosticSeverity.Error,
Locations =
new[] {
new DiagnosticResultLocation("Test0.cs", 7, 19)
}
};
VerifyCommandLineDiagnostic(test, expected);
}
[TestCategory("Analyzer")]
[TestMethod]
public void MultipleActionArgumentsOnType()
{
var test = @"
using CommandLine.Attributes;
using CommandLine.Attributes.Advanced;
class Options
{
[ActionArgument]
public string Action1 { get; set; }
[ActionArgument]
public string Action2 { get; set; }
[ArgumentGroup(""test"")]
[OptionalArgument(""1"", ""dir"", ""Directory2"")]
public string Directory { get; set; }
}";
var expected = new DiagnosticResult
{
Id = "CMDNET05",
Message = "The type can only define one action argument.",
Severity = DiagnosticSeverity.Error,
Locations =
new[] {
new DiagnosticResultLocation("Test0.cs", 10, 19)
}
};
VerifyCommandLineDiagnostic(test, expected);
}
[TestCategory("Analyzer")]
[TestMethod]
public void ArgumentGroupSpecifiedOnNonProperty()
{
var test = @"
using CommandLine.Attributes;
using CommandLine.Attributes.Advanced;
class Options
{
[ActionArgument]
public string Action1 { get; set; }
//ERROR here!
[ArgumentGroup(""test"")]
public string Directory { get; set; }
[ArgumentGroup(""test"")]
[OptionalArgument(""1"", ""dir"", ""Directory2"")]
public string Directory2 { get; set; }
}";
var expected = new DiagnosticResult
{
Id = "CMDNET03",
Message = "The CommonArgumentAttribute/ArgumentGroupAttribute can only be applied to properties that already have the [RequiredArgument] or [OptionalArgument] attribute.",
Severity = DiagnosticSeverity.Error,
Locations =
new[] {
new DiagnosticResultLocation("Test0.cs", 11, 19)
}
};
VerifyCommandLineDiagnostic(test, expected);
}
[TestCategory("Analyzer")]
[TestMethod]
public void CommonArgumentSpecifiedOnStringActionField()
{
var test = @"
using CommandLine.Attributes;
using CommandLine.Attributes.Advanced;
class Options
{
[ActionArgument]
public string Action1 { get; set; }
[CommonArgument]
[OptionalArgument(""1"", ""dir"", ""Directory2"")]
public string Directory2 { get; set; }
}";
var expected = new[] {
new DiagnosticResult
{
Id = "CMDNET11",
Message = "The class defines a property as an action but there are no action specific properties defined.",
Severity = DiagnosticSeverity.Warning,
Locations =
new[] {
new DiagnosticResultLocation("Test0.cs", 7, 19)
}
},
new DiagnosticResult
{
Id = "CMDNET04",
Message = "The CommonArgumentAttribute can only used when the action argument has a known, finite set of item, ie. an Enum.",
Severity = DiagnosticSeverity.Error,
Locations =
new[] {
new DiagnosticResultLocation("Test0.cs", 11, 19)
}
}
}
;
VerifyCommandLineDiagnostic(test, expected);
}
[TestCategory("Analyzer")]
[TestMethod]
public void RequiredPropertyNotStartingAtPositionZero()
{
var test = @"
using CommandLine.Attributes;
class Options
{
[RequiredArgument(1, ""dir"", ""Directory"")]
public string Directory { get; set; }
}";
var expected = new DiagnosticResult
{
Id = "CMDNET07",
Message = "The type declares '1' properties as required. The property positions are 0-based. Could not find required argument at position '0'.",
Severity = DiagnosticSeverity.Error,
Locations =
new[] {
new DiagnosticResultLocation("Test0.cs", 3, 7)
}
};
VerifyCommandLineDiagnostic(test, expected);
}
[TestCategory("Analyzer")]
[TestMethod]
public void PropertiesWithMultipledPositionalRequiredArgsInGroups()
{
var test = @"
using CommandLine.Attributes;
using CommandLine.Attributes.Advanced;
internal enum CommandLineActionGroup { add, remove }
internal class CommandLineOptions
{
[ActionArgument]
public CommandLineActionGroup Action { get; set; }
[CommonArgument]
[RequiredArgumentAttribute(0, ""host"", ""The name of the host"")]
public string Host { get; set; }
#region Add-host Action
[RequiredArgument(1, ""mac1"", ""The MAC address of the host"")]
[ArgumentGroup(nameof(CommandLineActionGroup.add))]
public string MAC { get; set; }
[RequiredArgument(2, ""mac2"", ""The MAC address of the host"")]
[ArgumentGroup(nameof(CommandLineActionGroup.add))]
public string MAC2 { get; set; }
[RequiredArgument(3, ""mac3"", ""The MAC address of the host"")]
[ArgumentGroup(nameof(CommandLineActionGroup.add))]
public string MAC3 { get; set; }
#endregion
#region remove-host Action
[RequiredArgument(1, ""mac1"", ""The MAC address of the host"")]
[ArgumentGroup(nameof(CommandLineActionGroup.remove))]
public string MAC_r { get; set; }
[RequiredArgument(2, ""mac2"", ""The MAC address of the host"")]
[ArgumentGroup(nameof(CommandLineActionGroup.remove))]
public string MAC2_r { get; set; }
[RequiredArgument(3, ""mac3"", ""The MAC address of the host"")]
[ArgumentGroup(nameof(CommandLineActionGroup.remove))]
public string MAC3_r { get; set; }
#endregion
}
";
VerifyCommandLineDiagnostic(test);
}
[TestCategory("Analyzer")]
[TestMethod]
public void PropertiesWithMultipledPositionalRequiredArgsInGroups2()
{
var test = @"
using CommandLine.Attributes;
using CommandLine.Attributes.Advanced;
internal enum CommandLineActionGroup { add, remove }
internal class CommandLineOptions
{
[ActionArgument]
public CommandLineActionGroup Action { get; set; }
[CommonArgument]
[RequiredArgumentAttribute(0, ""host"", ""The name of the host"")]
public string Host { get; set; }
[CommonArgument]
[RequiredArgumentAttribute(2, ""host2"", ""The name of the host"")]
public string Host2 { get; set; }
#region Add-host Action
[RequiredArgument(1, ""mac1"", ""The MAC address of the host"")]
[ArgumentGroup(nameof(CommandLineActionGroup.add))]
public string MAC { get; set; }
#endregion
#region remove-host Action
[RequiredArgument(1, ""mac1"", ""The MAC address of the host"")]
[ArgumentGroup(nameof(CommandLineActionGroup.remove))]
public string MAC_r { get; set; }
#endregion
}
";
VerifyCommandLineDiagnostic(test);
}
[TestCategory("Analyzer")]
[TestMethod]
public void InvalidPropertiesWithMultipledPositionalRequiredArgsInGroups()
{
var test = @"
using CommandLine.Attributes;
using CommandLine.Attributes.Advanced;
internal enum CommandLineActionGroup { add, remove }
internal class CommandLineOptions
{
[ActionArgument]
public CommandLineActionGroup Action { get; set; }
[CommonArgument]
[RequiredArgumentAttribute(0, ""host"", ""The name of the host"")]
public string Host { get; set; }
#region Add-host Action
[RequiredArgument(1, ""mac1"", ""The MAC address of the host"")]
[ArgumentGroup(nameof(CommandLineActionGroup.add))]
public string MAC { get; set; }
[RequiredArgument(2, ""mac2"", ""The MAC address of the host"")]
[ArgumentGroup(nameof(CommandLineActionGroup.add))]
public string MAC2 { get; set; }
[RequiredArgument(3, ""mac3"", ""The MAC address of the host"")]
[ArgumentGroup(nameof(CommandLineActionGroup.add))]
public string MAC3 { get; set; }
#endregion
#region remove-host Action
[RequiredArgument(1, ""mac1"", ""The MAC address of the host"")]
[ArgumentGroup(nameof(CommandLineActionGroup.remove))]
public string MAC_r { get; set; }
[RequiredArgument(3, ""mac2"", ""The MAC address of the host"")]
[ArgumentGroup(nameof(CommandLineActionGroup.remove))]
public string MAC2_r { get; set; }
#endregion
}
";
var expected = new DiagnosticResult
{
Id = "CMDNET07",
Message = "The type declares '3' properties as required. The property positions are 0-based. Could not find required argument at position '2'.",
Severity = DiagnosticSeverity.Error,
Locations =
new[] {
new DiagnosticResultLocation("Test0.cs", 6, 16)
}
};
VerifyCommandLineDiagnostic(test, expected);
}
[TestCategory("Analyzer")]
[TestMethod]
public void RequiredCollectionArgShouldBeTheOnlyOne()
{
var test = @"
using CommandLine.Attributes;
using CommandLine.Attributes.Advanced;
internal class CmdLineArgs
{
[ActionArgument]
public Action Action { get; set; }
[ArgumentGroup(nameof(Action.Create))]
[RequiredArgument(0, ""milestoneInputFile"", ""The file containing the list of milestones to create."")]
public string MilestoneFile { get; set; }
[ArgumentGroup(nameof(Action.List), overrideRequiredPosition: 0)]
[ArgumentGroup(nameof(Action.Create))]
[RequiredArgument(1, ""repos"", ""The list of repositories where to add the milestones to. The format is: owner\\repoName."", true)]
public List<string> Repositories { get; set; }
[ArgumentGroup(nameof(Action.List))]
[RequiredArgument(1, ""repos2"", ""The list of repositories where to add the milestones to. The format is: owner\\repoName."", true)]
public List<string> Repositories2 { get; set; }
}
public enum Action
{
Create,
List
}
";
var expected = new DiagnosticResult
{
Id = "CMDNET09",
Message = "Both arguments 'repos' and 'repos2' are marked as required collection arguments. Only one can be required. The other should be changed to optional.",
Severity = DiagnosticSeverity.Error,
Locations =
new[] {
new DiagnosticResultLocation("Test0.cs", 21, 29)
}
};
VerifyCommandLineDiagnostic(test,expected);
}
[TestCategory("Analyzer")]
[TestMethod]
public void RequiredArgumentShouldBeLast()
{
var test = @"
using CommandLine.Attributes;
using CommandLine.Attributes.Advanced;
internal class CmdLineArgs
{
[RequiredArgument(1, ""milestoneInputFile"", ""The file containing the list of milestones to create."")]
public string MilestoneFile { get; set; }
[RequiredArgument(0, ""repos"", ""The list of repositories where to add the milestones to. The format is: owner\\repoName."", true)]
public List<string> Repositories { get; set; }
}
public enum Action
{
Create,
List
}
";
var expected = new DiagnosticResult
{
Id = "CMDNET08",
Message = "The collection argument 'repos' needs to be the last argument in the list. Otherwise, it will not be possible to parse it at runtime.",
Severity = DiagnosticSeverity.Error,
Locations =
new[] {
new DiagnosticResultLocation("Test0.cs", 11, 29)
}
};
VerifyCommandLineDiagnostic(test, expected);
}
[TestCategory("Analyzer")]
[TestMethod]
public void InvalidCode1()
{
var test = @"
using CommandLine.Attributes;
using CommandLine.Attributes.Advanced;
class Options
{
[Action
public string Action1 { get; set; }
[ActionArgument]
public string Action2 { get; set; }
[ArgumentGroup(""test"")]
[OptionalArgument(""1"", ""dir"", ""Directory2"")]
public string Directory { get; set; }
}";
VerifyCommandLineDiagnostic(test);
}
[TestCategory("Analyzer")]
[TestMethod]
public void InvalidCode2()
{
var test = @"
using CommandLine.Attributes;
using CommandLine.Attributes.Advanced;
class Options
{
[]
public string Action1 { get; set; }
[ActionArgument]
public string Action2 { get; set; }
[ArgumentGroup(""test"")]
[OptionalArgument(""1"", ""dir"", ""Directory2"")]
public string Directory { get; set; }
}";
VerifyCommandLineDiagnostic(test);
}
[TestCategory("Analyzer")]
[TestMethod]
public void InvalidCode3()
{
var test = @"
using CommandLine.Attributes;
using CommandLine.Attributes.Advanced;
class Options
{
[]
public string Action1
[ActionArgument]
public string Action2 { get; set; }
[ArgumentGroup(""test"")]
[OptionalArgument(""1"", ""dir"", ""Directory2"")]
public string Directory { get; set; }
}";
VerifyCommandLineDiagnostic(test);
}
[TestCategory("Analyzer")]
[TestMethod]
public void InvalidCode4()
{
var test = @"
using CommandLine.Attributes;
using CommandLine.Attributes.Advanced;
class Options
{
[OptionalArgument(""1"", ""dir"")]
public string Directory { get; set; }
}";
VerifyCommandLineDiagnostic(test);
}
[TestCategory("Analyzer")]
[TestMethod]
public void ArgumentWithNoArgs()
{
var test = @"
using CommandLine.Attributes;
using CommandLine.Attributes.Advanced;
namespace DotNetVersions.Console
{
class Options
{
[ArgumentGroup(nameof(Action.search))]
[RequiredArgument(0, ""version"", ""The file version you are interested in"")]
public string Version { get; set; }
[ActionArgument]
public Action Action { get; set; }
}
enum Action
{
list,
search
}
}
";
VerifyCommandLineDiagnostic(test);
}
[TestCategory("Analyzer")]
[TestMethod]
public void TwoRequiredCollectionProperties()
{
var test = @"
using CommandLine.Attributes;
using CommandLine.Attributes.Advanced;
using System;
using System.Collections.Generic;
using System.Linq;
namespace CommandLine.Tests.TestObjects
{
class ComplexType2
{
[RequiredArgument(0, ""repos"", ""The list of repositories where to add the milestones to."", true)]
public List<string> Repositories { get; set; }
[RequiredArgument(1, ""list"", ""Another list"", true)]
public List<string> List { get; set; }
}
}";
var expected = new DiagnosticResult
{
Id = "CMDNET09",
Message = "Both arguments 'repos' and 'list' are marked as required collection arguments. Only one can be required. The other should be changed to optional.",
Severity = DiagnosticSeverity.Error,
Locations =
new[] {
new DiagnosticResultLocation("Test0.cs", 16, 29)
}
};
VerifyCommandLineDiagnostic(test, expected);
}
[TestCategory("Analyzer")]
[TestMethod]
public void TwoCollectionPropertiesOnArgumentGroup()
{
var test = @"
using CommandLine.Attributes;
using CommandLine.Attributes.Advanced;
internal class CmdLineArgs
{
[ActionArgument]
public Action Action { get; set; }
[ArgumentGroup(nameof(Action.Create))]
[RequiredArgument(0, ""milestoneInputFile"", ""The file containing the list of milestones to create."")]
public string MilestoneFile { get; set; }
[ArgumentGroup(nameof(Action.Create))]
[RequiredArgument(1, ""repos"", ""The list of repositories where to add the milestones to. The format is: owner\\repoName."", true)]
public List<string> Repositories { get; set; }
[ArgumentGroup(nameof(Action.Create))]
[RequiredArgument(2, ""repos2"", ""The list of repositories where to add the milestones to. The format is: owner\\repoName."", true)]
public List<string> Repositories2 { get; set; }
}
public enum Action
{
Create,
List
}
";
var expected = new DiagnosticResult
{
Id = "CMDNET09",
Message = "Both arguments 'repos' and 'repos2' are marked as required collection arguments. Only one can be required. The other should be changed to optional.",
Severity = DiagnosticSeverity.Error,
Locations =
new[] {
new DiagnosticResultLocation("Test0.cs", 20, 29)
}
};
VerifyCommandLineDiagnostic(test, expected);
}
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new CommandLineAnalyzer();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace Cleangorod.Web.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V10.Resources
{
/// <summary>Resource name for the <c>CustomerExtensionSetting</c> resource.</summary>
public sealed partial class CustomerExtensionSettingName : gax::IResourceName, sys::IEquatable<CustomerExtensionSettingName>
{
/// <summary>The possible contents of <see cref="CustomerExtensionSettingName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/customerExtensionSettings/{extension_type}</c>.
/// </summary>
CustomerExtensionType = 1,
}
private static gax::PathTemplate s_customerExtensionType = new gax::PathTemplate("customers/{customer_id}/customerExtensionSettings/{extension_type}");
/// <summary>
/// Creates a <see cref="CustomerExtensionSettingName"/> containing an unparsed resource name.
/// </summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="CustomerExtensionSettingName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static CustomerExtensionSettingName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new CustomerExtensionSettingName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="CustomerExtensionSettingName"/> with the pattern
/// <c>customers/{customer_id}/customerExtensionSettings/{extension_type}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="extensionTypeId">The <c>ExtensionType</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// A new instance of <see cref="CustomerExtensionSettingName"/> constructed from the provided ids.
/// </returns>
public static CustomerExtensionSettingName FromCustomerExtensionType(string customerId, string extensionTypeId) =>
new CustomerExtensionSettingName(ResourceNameType.CustomerExtensionType, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), extensionTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(extensionTypeId, nameof(extensionTypeId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CustomerExtensionSettingName"/> with
/// pattern <c>customers/{customer_id}/customerExtensionSettings/{extension_type}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="extensionTypeId">The <c>ExtensionType</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CustomerExtensionSettingName"/> with pattern
/// <c>customers/{customer_id}/customerExtensionSettings/{extension_type}</c>.
/// </returns>
public static string Format(string customerId, string extensionTypeId) =>
FormatCustomerExtensionType(customerId, extensionTypeId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CustomerExtensionSettingName"/> with
/// pattern <c>customers/{customer_id}/customerExtensionSettings/{extension_type}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="extensionTypeId">The <c>ExtensionType</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CustomerExtensionSettingName"/> with pattern
/// <c>customers/{customer_id}/customerExtensionSettings/{extension_type}</c>.
/// </returns>
public static string FormatCustomerExtensionType(string customerId, string extensionTypeId) =>
s_customerExtensionType.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(extensionTypeId, nameof(extensionTypeId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="CustomerExtensionSettingName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/customerExtensionSettings/{extension_type}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="customerExtensionSettingName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <returns>The parsed <see cref="CustomerExtensionSettingName"/> if successful.</returns>
public static CustomerExtensionSettingName Parse(string customerExtensionSettingName) =>
Parse(customerExtensionSettingName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="CustomerExtensionSettingName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/customerExtensionSettings/{extension_type}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="customerExtensionSettingName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="CustomerExtensionSettingName"/> if successful.</returns>
public static CustomerExtensionSettingName Parse(string customerExtensionSettingName, bool allowUnparsed) =>
TryParse(customerExtensionSettingName, allowUnparsed, out CustomerExtensionSettingName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CustomerExtensionSettingName"/>
/// instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/customerExtensionSettings/{extension_type}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="customerExtensionSettingName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CustomerExtensionSettingName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string customerExtensionSettingName, out CustomerExtensionSettingName result) =>
TryParse(customerExtensionSettingName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CustomerExtensionSettingName"/>
/// instance; optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/customerExtensionSettings/{extension_type}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="customerExtensionSettingName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CustomerExtensionSettingName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string customerExtensionSettingName, bool allowUnparsed, out CustomerExtensionSettingName result)
{
gax::GaxPreconditions.CheckNotNull(customerExtensionSettingName, nameof(customerExtensionSettingName));
gax::TemplatedResourceName resourceName;
if (s_customerExtensionType.TryParseName(customerExtensionSettingName, out resourceName))
{
result = FromCustomerExtensionType(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(customerExtensionSettingName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private CustomerExtensionSettingName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string extensionTypeId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomerId = customerId;
ExtensionTypeId = extensionTypeId;
}
/// <summary>
/// Constructs a new instance of a <see cref="CustomerExtensionSettingName"/> class from the component parts of
/// pattern <c>customers/{customer_id}/customerExtensionSettings/{extension_type}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="extensionTypeId">The <c>ExtensionType</c> ID. Must not be <c>null</c> or empty.</param>
public CustomerExtensionSettingName(string customerId, string extensionTypeId) : this(ResourceNameType.CustomerExtensionType, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), extensionTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(extensionTypeId, nameof(extensionTypeId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>ExtensionType</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string ExtensionTypeId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerExtensionType: return s_customerExtensionType.Expand(CustomerId, ExtensionTypeId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as CustomerExtensionSettingName);
/// <inheritdoc/>
public bool Equals(CustomerExtensionSettingName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(CustomerExtensionSettingName a, CustomerExtensionSettingName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(CustomerExtensionSettingName a, CustomerExtensionSettingName b) => !(a == b);
}
public partial class CustomerExtensionSetting
{
/// <summary>
/// <see cref="CustomerExtensionSettingName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal CustomerExtensionSettingName ResourceNameAsCustomerExtensionSettingName
{
get => string.IsNullOrEmpty(ResourceName) ? null : CustomerExtensionSettingName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="ExtensionFeedItemName"/>-typed view over the <see cref="ExtensionFeedItems"/> resource name
/// property.
/// </summary>
internal gax::ResourceNameList<ExtensionFeedItemName> ExtensionFeedItemsAsExtensionFeedItemNames
{
get => new gax::ResourceNameList<ExtensionFeedItemName>(ExtensionFeedItems, s => string.IsNullOrEmpty(s) ? null : ExtensionFeedItemName.Parse(s, allowUnparsed: true));
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="BasicTests.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>no summary</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using Csla.TestHelpers;
#if !NUNIT
using Microsoft.VisualStudio.TestTools.UnitTesting;
#else
using NUnit.Framework;
using TestClass = NUnit.Framework.TestFixtureAttribute;
using TestInitialize = NUnit.Framework.SetUpAttribute;
using TestCleanup = NUnit.Framework.TearDownAttribute;
using TestMethod = NUnit.Framework.TestAttribute;
#endif
namespace Csla.Test.Basic
{
[TestClass]
public class BasicTests
{
private static TestDIContext _testDIContext;
[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
_testDIContext = TestDIContextFactory.CreateDefaultContext();
}
[TestMethod]
public void TestNotUndoableField()
{
IDataPortal<DataBinding.ParentEntity> dataPortal = _testDIContext.CreateDataPortal<DataBinding.ParentEntity>();
TestResults.Reinitialise();
Csla.Test.DataBinding.ParentEntity p = DataBinding.ParentEntity.NewParentEntity(dataPortal);
p.NotUndoable = "something";
p.Data = "data";
p.BeginEdit();
p.NotUndoable = "something else";
p.Data = "new data";
p.CancelEdit();
//NotUndoable property points to a private field marked with [NotUndoable()]
//so its state is never copied when BeginEdit() is called
Assert.AreEqual("something else", p.NotUndoable);
//the Data property points to a field that is undoable, so it reverts
Assert.AreEqual("data", p.Data);
}
[TestMethod]
public void TestReadOnlyList()
{
//ReadOnlyList list = ReadOnlyList.GetReadOnlyList();
//Assert.AreEqual("Fetched", TestResults.GetResult("ReadOnlyList"));
}
[TestMethod]
public void TestNameValueList()
{
IDataPortal<NameValueListObj> dataPortal = _testDIContext.CreateDataPortal<NameValueListObj>();
NameValueListObj nvList = dataPortal.Fetch();
Assert.AreEqual("Fetched", TestResults.GetResult("NameValueListObj"));
Assert.AreEqual("element_1", nvList[1].Value);
//won't work, because IsReadOnly is set to true after object is populated in the for
//loop in DataPortal_Fetch
//NameValueListObj.NameValuePair newPair = new NameValueListObj.NameValuePair(45, "something");
//nvList.Add(newPair);
//Assert.AreEqual("something", nvList[45].Value);
}
[TestMethod]
public void TestCommandBase()
{
IDataPortal<CommandObject> dataPortal = _testDIContext.CreateDataPortal<CommandObject>();
TestResults.Reinitialise();
CommandObject obj = new CommandObject();
obj = dataPortal.Execute(obj);
Assert.AreEqual("Executed", obj.AProperty);
}
[TestMethod]
public void CreateGenRoot()
{
TestResults.Reinitialise();
GenRoot root;
root = NewGenRoot();
Assert.IsNotNull(root);
Assert.AreEqual("<new>", root.Data);
Assert.AreEqual("Created", TestResults.GetResult("GenRoot"));
Assert.AreEqual(true, root.IsNew);
Assert.AreEqual(false, root.IsDeleted);
Assert.AreEqual(true, root.IsDirty);
}
[TestMethod]
public void InheritanceUndo()
{
TestResults.Reinitialise();
GenRoot root;
root = NewGenRoot();
root.BeginEdit();
root.Data = "abc";
root.CancelEdit();
TestResults.Reinitialise();
root = NewGenRoot();
root.BeginEdit();
root.Data = "abc";
root.ApplyEdit();
}
[TestMethod]
public void CreateRoot()
{
TestResults.Reinitialise();
Root root;
root = NewRoot();
Assert.IsNotNull(root);
Assert.AreEqual("<new>", root.Data);
Assert.AreEqual("Created", TestResults.GetResult("Root"));
Assert.AreEqual(true, root.IsNew);
Assert.AreEqual(false, root.IsDeleted);
Assert.AreEqual(true, root.IsDirty);
}
[TestMethod]
public void AddChild()
{
IDataPortal<Child> childDataPortal = _testDIContext.CreateDataPortal<Child>();
TestResults.Reinitialise();
Root root = NewRoot();
root.Children.Add(childDataPortal, "1");
Assert.AreEqual(1, root.Children.Count);
Assert.AreEqual("1", root.Children[0].Data);
}
[TestMethod]
public void AddRemoveChild()
{
IDataPortal<Child> childDataPortal = _testDIContext.CreateDataPortal<Child>();
TestResults.Reinitialise();
Root root = NewRoot();
root.Children.Add(childDataPortal, "1");
root.Children.Remove(root.Children[0]);
Assert.AreEqual(0, root.Children.Count);
}
[TestMethod]
public void AddRemoveAddChild()
{
IDataPortal<Child> childDataPortal = _testDIContext.CreateDataPortal<Child>();
TestResults.Reinitialise();
Root root = NewRoot();
root.Children.Add(childDataPortal, "1");
root.BeginEdit();
root.Children.Remove(root.Children[0]);
root.Children.Add(childDataPortal, "2");
root.CancelEdit();
Assert.AreEqual(1, root.Children.Count);
Assert.AreEqual("1", root.Children[0].Data);
}
[TestMethod]
public void AddGrandChild()
{
IDataPortal<Child> childDataPortal = _testDIContext.CreateDataPortal<Child>();
TestResults.Reinitialise();
Root root = NewRoot();
root.Children.Add(childDataPortal, "1");
Child child = root.Children[0];
child.GrandChildren.Add("1");
Assert.AreEqual(1, child.GrandChildren.Count);
Assert.AreEqual("1", child.GrandChildren[0].Data);
}
[TestMethod]
public void AddRemoveGrandChild()
{
IDataPortal<Child> childDataPortal = _testDIContext.CreateDataPortal<Child>();
TestResults.Reinitialise();
Root root = NewRoot();
root.Children.Add(childDataPortal, "1");
Child child = root.Children[0];
child.GrandChildren.Add("1");
child.GrandChildren.Remove(child.GrandChildren[0]);
Assert.AreEqual(0, child.GrandChildren.Count);
}
///<remarks>"the non-generic method AreEqual cannot be used with type arguments" - though
///it is used with type arguments in BasicTests.vb
///</remarks>
//[TestMethod]
//public void CloneGraph()
//{
// TestResults.Reinitialise();
// Root root = NewRoot();
// FormSimulator form = new FormSimulator(root);
// SerializableListener listener = new SerializableListener(root);
// root.Children.Add("1");
// Child child = root.Children[0];
// Child.GrandChildren.Add("1");
// Assert.AreEqual<int>(1, child.GrandChildren.Count);
// Assert.AreEqual<string>("1", child.GrandChildren[0].Data);
// Root clone = ((Root)(root.Clone()));
// child = clone.Children[0];
// Assert.AreEqual<int>(1, child.GrandChildren.Count);
// Assert.AreEqual<string>("1", child.GrandChildren[0].Data);
// Assert.AreEqual<string>("root Deserialized", ((string)(TestResults.GetResult("Deserialized"))));
// Assert.AreEqual<string>("GC Deserialized", ((string)(TestResults.GetResult("GCDeserialized"))));
//}
[TestMethod]
public void ClearChildList()
{
IDataPortal<Child> childDataPortal = _testDIContext.CreateDataPortal<Child>();
TestResults.Reinitialise();
Root root = NewRoot();
root.Children.Add(childDataPortal, "A");
root.Children.Add(childDataPortal, "B");
root.Children.Add(childDataPortal, "C");
root.Children.Clear();
Assert.AreEqual(0, root.Children.Count, "Count should be 0");
Assert.AreEqual(3, root.Children.DeletedCount, "Deleted count should be 3");
}
[TestMethod]
public void NestedAddAcceptchild()
{
IDataPortal<Child> childDataPortal = _testDIContext.CreateDataPortal<Child>();
TestResults.Reinitialise();
Root root = NewRoot();
root.BeginEdit();
root.Children.Add(childDataPortal, "A");
root.BeginEdit();
root.Children.Add(childDataPortal, "B");
root.BeginEdit();
root.Children.Add(childDataPortal, "C");
root.ApplyEdit();
root.ApplyEdit();
root.ApplyEdit();
Assert.AreEqual(3, root.Children.Count);
}
[TestMethod]
public void NestedAddDeleteAcceptChild()
{
IDataPortal<Child> childDataPortal = _testDIContext.CreateDataPortal<Child>();
TestResults.Reinitialise();
Root root = NewRoot();
root.BeginEdit();
root.Children.Add(childDataPortal, "A");
root.BeginEdit();
root.Children.Add(childDataPortal, "B");
root.BeginEdit();
root.Children.Add(childDataPortal, "C");
Child childC = root.Children[2];
Assert.AreEqual(true, root.Children.Contains(childC), "Child should be in collection");
root.Children.Remove(root.Children[0]);
root.Children.Remove(root.Children[0]);
root.Children.Remove(root.Children[0]);
Assert.AreEqual(false, root.Children.Contains(childC), "Child should not be in collection");
Assert.AreEqual(true, root.Children.ContainsDeleted(childC), "Deleted child should be in deleted collection");
root.ApplyEdit();
Assert.AreEqual(false, root.Children.ContainsDeleted(childC), "Deleted child should not be in deleted collection after first applyedit");
root.ApplyEdit();
Assert.AreEqual(false, root.Children.ContainsDeleted(childC), "Deleted child should not be in deleted collection after ApplyEdit");
root.ApplyEdit();
Assert.AreEqual(0, root.Children.Count, "No children should remain");
Assert.AreEqual(false, root.Children.ContainsDeleted(childC), "Deleted child should not be in deleted collection after third applyedit");
}
[TestMethod]
public void BasicEquality()
{
TestResults.Reinitialise();
Root r1 = NewRoot();
r1.Data = "abc";
Assert.AreEqual(true, r1.Equals(r1), "objects should be equal on instance compare");
Assert.AreEqual(true, Equals(r1, r1), "objects should be equal on static compare");
TestResults.Reinitialise();
Root r2 = NewRoot();
r2.Data = "xyz";
Assert.AreEqual(false, r1.Equals(r2), "objects should not be equal");
Assert.AreEqual(false, Equals(r1, r2), "objects should not be equal");
Assert.AreEqual(false, r1.Equals(null), "Objects should not be equal");
Assert.AreEqual(false, Equals(r1, null), "Objects should not be equal");
Assert.AreEqual(false, Equals(null, r2), "Objects should not be equal");
}
[TestMethod]
public void ChildEquality()
{
IDataPortal<Child> childDataPortal = _testDIContext.CreateDataPortal<Child>();
TestResults.Reinitialise();
Root root = NewRoot();
root.Children.Add(childDataPortal, "abc");
root.Children.Add(childDataPortal, "xyz");
root.Children.Add(childDataPortal, "123");
Child c1 = root.Children[0];
Child c2 = root.Children[1];
Child c3 = root.Children[2];
root.Children.Remove(c3);
Assert.AreEqual(true, c1.Equals(c1), "objects should be equal");
Assert.AreEqual(true, Equals(c1, c1), "objects should be equal");
Assert.AreEqual(false, c1.Equals(c2), "objects should not be equal");
Assert.AreEqual(false, Equals(c1, c2), "objects should not be equal");
Assert.AreEqual(false, c1.Equals(null), "objects should not be equal");
Assert.AreEqual(false, Equals(c1, null), "objects should not be equal");
Assert.AreEqual(false, Equals(null, c2), "objects should not be equal");
Assert.AreEqual(true, root.Children.Contains(c1), "Collection should contain c1");
Assert.AreEqual(true, root.Children.Contains(c2), "collection should contain c2");
Assert.AreEqual(false, root.Children.Contains(c3), "collection should not contain c3");
Assert.AreEqual(true, root.Children.ContainsDeleted(c3), "Deleted collection should contain c3");
}
[TestMethod]
public void DeletedListTest()
{
IDataPortal<Child> childDataPortal = _testDIContext.CreateDataPortal<Child>();
TestResults.Reinitialise();
Root root = NewRoot();
root.Children.Add(childDataPortal, "1");
root.Children.Add(childDataPortal, "2");
root.Children.Add(childDataPortal, "3");
root.BeginEdit();
root.Children.Remove(root.Children[0]);
root.Children.Remove(root.Children[0]);
root.ApplyEdit();
Root copy = root.Clone();
var deleted = (List<Child>)(root.Children.GetType().GetProperty("DeletedList", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy | System.Reflection.BindingFlags.IgnoreCase).GetValue(copy.Children, null));
Assert.AreEqual(2, deleted.Count);
Assert.AreEqual("1", deleted[0].Data);
Assert.AreEqual("2", deleted[1].Data);
Assert.AreEqual(1, root.Children.Count);
}
[TestMethod]
public void DeletedListTestWithCancel()
{
IDataPortal<Child> childDataPortal = _testDIContext.CreateDataPortal<Child>();
TestResults.Reinitialise();
Root root = NewRoot();
root.Children.Add(childDataPortal, "1");
root.Children.Add(childDataPortal, "2");
root.Children.Add(childDataPortal, "3");
root.BeginEdit();
root.Children.Remove(root.Children[0]);
root.Children.Remove(root.Children[0]);
Root copy = root.Clone();
List<Child> deleted = (List<Child>)(root.Children.GetType().GetProperty("DeletedList", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy | System.Reflection.BindingFlags.IgnoreCase).GetValue(copy.Children, null));
Assert.AreEqual(2, deleted.Count);
Assert.AreEqual("1", deleted[0].Data);
Assert.AreEqual("2", deleted[1].Data);
Assert.AreEqual(1, root.Children.Count);
root.CancelEdit();
deleted = (List<Child>)(root.Children.GetType().GetProperty("DeletedList", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy | System.Reflection.BindingFlags.IgnoreCase).GetValue(root.Children, null));
Assert.AreEqual(0, deleted.Count);
Assert.AreEqual(3, root.Children.Count);
}
[TestMethod]
public void SuppressListChangedEventsDoNotRaiseCollectionChanged()
{
bool changed = false;
var obj = new RootList();
obj.ListChanged += (o, e) =>
{
changed = true;
};
var child = new RootListChild(); // object is marked as child
Assert.IsTrue(obj.RaiseListChangedEvents);
using (obj.SuppressListChangedEvents)
{
Assert.IsFalse(obj.RaiseListChangedEvents);
obj.Add(child);
}
Assert.IsFalse(changed, "Should not raise ListChanged event");
Assert.IsTrue(obj.RaiseListChangedEvents);
Assert.AreEqual(child, obj[0]);
}
[TestCleanup]
public void ClearContextsAfterEachTest()
{
TestResults.Reinitialise();
}
private Root NewRoot()
{
IDataPortal<Root> dataPortal = _testDIContext.CreateDataPortal<Root>();
return dataPortal.Create(new Root.Criteria());
}
private GenRoot NewGenRoot()
{
IDataPortal<GenRoot> dataPortal = _testDIContext.CreateDataPortal<GenRoot>();
return dataPortal.Create(new GenRoot.Criteria());
}
}
public class FormSimulator
{
private Core.BusinessBase _obj;
public FormSimulator(Core.BusinessBase obj)
{
this._obj.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(obj_IsDirtyChanged);
this._obj = obj;
}
private void obj_IsDirtyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{ }
}
[Serializable()]
public class SerializableListener
{
private Core.BusinessBase _obj;
public SerializableListener(Core.BusinessBase obj)
{
this._obj.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(obj_IsDirtyChanged);
this._obj = obj;
}
public void obj_IsDirtyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{ }
}
}
| |
namespace SimpleECS
{
using System;
using System.Collections;
using System.Collections.Generic;
using Internal;
/// <summary>
/// Aggregates types into a unique signature
/// </summary>
public sealed class TypeSignature : IEquatable<TypeSignature>, IReadOnlyList<Type>
{
int[] type_ids;
int type_count;
TypeSignature(int capacity = 4)
{
type_ids = new int[capacity];
}
/// <summary>
/// number of types that make up the signature
/// </summary>
public int Count => type_count;
/// <summary>
/// Creates a new type signature using the supplied types
/// </summary>
public TypeSignature(IEnumerable<Type> types)
{
type_ids = new int[4];
foreach (var type in types)
Add(type);
}
/// <summary>
/// Creates a new type signature that matches the supplied type signature
/// </summary>
/// <param name="signature"></param>
public TypeSignature(TypeSignature signature)
{
type_count = signature.type_count;
type_ids = new int[type_count + 1];
for (int i = 0; i < type_count; ++i)
{
type_ids[i] = signature.type_ids[i];
}
}
/// <summary>
/// Creates a new type signature with the supplied types
/// </summary>
/// <param name="types"></param>
public TypeSignature(params Type[] types)
{
this.type_ids = new int[types.Length];
foreach (var type in types)
Add(type);
}
/// <summary>
/// Create a new type signature with the same signature as the supplied archetype
/// </summary>
/// <param name="archetype"></param>
public TypeSignature(Archetype archetype)
{
if (archetype.IsValid())
{
var signature = archetype.GetTypeSignature();
type_ids = new int[signature.type_count + 1];
this.Copy(signature);
}
else type_ids = new int[2];
}
/// <summary>
/// Clears signature to be an empty type
/// </summary>
public TypeSignature Clear()
{
type_count = 0;
return this;
}
public TypeSignature Add(params Type[] types)
{
foreach (var type in types)
if (type != null)
Add(TypeID.Get(type));
return this;
}
internal TypeSignature Add(int type_id)
{
for (int i = 0; i < type_count; ++i)
{
if (type_ids[i] == type_id) // if same exit
return this;
if (type_id > type_ids[i]) // since the hash is generated from this, ordering is important
{
var stored_id = type_ids[i];
type_ids[i] = type_id;
type_id = stored_id;
}
}
if (type_count++ == type_ids.Length)
Array.Resize(ref type_ids, type_count + 4);
type_ids[type_count - 1] = type_id;
return this;
}
public TypeSignature Remove(params Type[] types)
{
foreach (var type in types)
if (type != null)
Remove(TypeID.Get(type));
return this;
}
internal TypeSignature Remove(int type_id)
{
bool swap = type_ids[0] == type_id;
for (int i = 1; i < type_count; ++i)
{
if (swap)
type_ids[i - 1] = type_ids[i];
else
swap = type_ids[i] == type_id;
}
if (swap)
type_count--;
return this;
}
/// <summary>
/// Makes this signature an exact copy of other signature
/// </summary>
public TypeSignature Copy(TypeSignature signature)
{
if (type_ids.Length < signature.type_count)
Array.Resize(ref type_ids, signature.type_count + 1);
for (int i = 0; i < signature.type_count; ++i)
type_ids[i] = signature.type_ids[i];
type_count = signature.type_count;
return this;
}
/// <summary>
/// Makes this type signature the same as the archetype's type signature
/// </summary>
public TypeSignature Copy(Archetype archetype)
=> this.Copy(archetype.GetTypeSignature());
/// <summary>
/// Adds type to the signature
/// </summary>
public TypeSignature Add(Type type)
=> Add(TypeID.Get(type));
/// <summary>
/// Adds type to the signature
/// </summary>
public TypeSignature Add<T>()
=> Add(TypeID<T>.Value);
/// <summary>
/// Removes type from signature
/// </summary>
public TypeSignature Remove(Type type)
=> Remove(TypeID.Get(type));
/// <summary>
/// Removes type from signature
/// </summary>
public TypeSignature Remove<T>()
=> Remove(TypeID<T>.Value);
/// <summary>
/// Returns true if signature has type
/// </summary>
public bool Has<T>() => Has(TypeID<T>.Value);
/// <summary>
/// Returns true if signature has type
/// </summary>
public bool Has(Type type) => Has(TypeID.Get(type));
internal bool Has(int typeid)
{
for (int i = 0; i < type_count; ++i)
if (type_ids[i] == typeid)
return true;
return false;
}
/// <summary>
/// Returns true if signatures have any types in common
/// </summary>
public bool HasAny(TypeSignature other)
{
for (int a = 0; a < type_count; ++a)
{
for (int b = 0; b < other.type_count; ++b)
{
if (type_ids[a] == other.type_ids[b])
return true;
}
}
return false;
}
/// <summary>
/// Returns true if this signature has all types contained in the other signature
/// </summary>
/// <returns></returns>
public bool HasAll(TypeSignature other)
{
for (int a = 0; a < other.type_count; ++a)
{
for (int b = 0; b < type_count; ++b)
{
if (other.type_ids[a] == type_ids[b])
goto next;
}
return false;
next:
continue;
}
return true;
}
#pragma warning disable
public override int GetHashCode()
{
int prime = 53;
int power = 1;
int hashval = 0;
unchecked
{
for (int i = 0; i < type_count; ++i)
{
power *= prime;
hashval = (hashval + type_ids[i] * power);
}
}
return hashval;
}
public bool Equals(TypeSignature other)
{
if (type_count != other.type_count)
return false;
for (int i = 0; i < type_count; ++i)
{
if (type_ids[i] != other.type_ids[i])
return false;
}
return true;
}
public override bool Equals(object obj)
=> obj is TypeSignature sig ? sig.Equals(this) : false;
public override string ToString()
{
string sig = "Type Signature [";
for (int i = 0; i < type_count; ++i)
{
var type = TypeID.Get(type_ids[i]);
sig += $" {type.Name}";
}
sig += "]";
return sig;
}
public string TypesToString()
{
string sig = "[";
for (int i = 0; i < type_count; ++i)
{
var type = TypeID.Get(type_ids[i]);
sig += $" {type.Name}";
}
sig += "]";
return sig;
}
/// <summary>
/// All types that currently make up this signature
/// </summary>
public IReadOnlyList<Type> Types => this;
Type IReadOnlyList<Type>.this[int index] => TypeID.Get(type_ids[index]);
IEnumerator<Type> IEnumerable<Type>.GetEnumerator()
{
for (int i = 0; i < type_count; ++i)
yield return TypeID.Get(type_ids[i]);
}
IEnumerator IEnumerable.GetEnumerator()
{
for (int i = 0; i < type_count; ++i)
yield return TypeID.Get(type_ids[i]);
}
int IReadOnlyCollection<Type>.Count => type_count;
}
}
namespace SimpleECS.Internal
{
using System;
using System.Collections.Generic;
/// <summary>
/// assigns ids to types
/// </summary>
public static class TypeID<T>
{
public static readonly int Value = TypeID.Get(typeof(T));
}
/// <summary>
/// assigns ids to types
/// </summary>
public static class TypeID // class to map types to ids
{
static Dictionary<Type, int> newIDs = new Dictionary<Type, int>();
static Type[] id_to_type = new Type[64];
public static Type Get(int type_id) => id_to_type[type_id];
public static int Get(Type type)
{
if (!newIDs.TryGetValue(type, out var id))
{
newIDs[type] = id = newIDs.Count + 1;
if (id == id_to_type.Length)
Array.Resize(ref id_to_type, id_to_type.Length * 2);
id_to_type[id] = type;
}
return id;
}
public static List<Type> GetAssignedTypes()
{
var list = new List<Type>();
foreach (var type in newIDs)
list.Add(type.Key);
return list;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Xml;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Xml.Serialization;
using System.Security;
using System.Security.Policy;
using System.Security.Permissions;
using Microsoft.Build.Framework;
using Microsoft.Build.BuildEngine.Shared;
namespace Microsoft.Build.BuildEngine
{
/// <summary>
/// This class contains utility methods for the MSBuild engine.
/// </summary>
/// <owner>RGoel</owner>
static public class Utilities
{
private readonly static Regex singlePropertyRegex = new Regex(@"^\$\(([^\$\(\)]*)\)$");
/// <summary>
/// Update our table which keeps track of all the properties that are referenced
/// inside of a condition and the string values that they are being tested against.
/// So, for example, if the condition was " '$(Configuration)' == 'Debug' ", we
/// would get passed in leftValue="$(Configuration)" and rightValueExpanded="Debug".
/// This call would add the string "Debug" to the list of possible values for the
/// "Configuration" property.
///
/// This method also handles the case when two or more properties are being
/// concatenated together with a vertical bar, as in '
/// $(Configuration)|$(Platform)' == 'Debug|x86'
/// </summary>
/// <param name="conditionedPropertiesTable"></param>
/// <param name="leftValue"></param>
/// <param name="rightValueExpanded"></param>
/// <owner>rgoel</owner>
internal static void UpdateConditionedPropertiesTable
(
Hashtable conditionedPropertiesTable, // Hash table containing a StringCollection
// of possible values, keyed by property name.
string leftValue, // The raw value on the left side of the operator
string rightValueExpanded // The fully expanded value on the right side
// of the operator.
)
{
if ((conditionedPropertiesTable != null) && (rightValueExpanded.Length > 0))
{
// The left side should be exactly "$(propertyname)" or "$(propertyname1)|$(propertyname2)"
// or "$(propertyname1)|$(propertyname2)|$(propertyname3)", etc. Anything else,
// and we don't touch the table.
// Split up the leftValue into pieces based on the vertical bar character.
string[] leftValuePieces = leftValue.Split(new char[]{'|'});
// Loop through each of the pieces.
for (int i = 0 ; i < leftValuePieces.Length ; i++)
{
Match singlePropertyMatch = singlePropertyRegex.Match(leftValuePieces[i]);
if (singlePropertyMatch.Success)
{
// Find the first vertical bar on the right-hand-side expression.
int indexOfVerticalBar = rightValueExpanded.IndexOf('|');
string rightValueExpandedPiece;
// If there was no vertical bar, then just use the remainder of the right-hand-side
// expression as the value of the property, and terminate the loop after this iteration.
// Also, if we're on the last segment of the left-hand-side, then use the remainder
// of the right-hand-side expression as the value of the property.
if ((indexOfVerticalBar == -1) || (i == (leftValuePieces.Length - 1)))
{
rightValueExpandedPiece = rightValueExpanded;
i = leftValuePieces.Length;
}
else
{
// If we found a vertical bar, then the portion before the vertical bar is the
// property value which we will store in our table. Then remove that portion
// from the original string so that the next iteration of the loop can easily search
// for the first vertical bar again.
rightValueExpandedPiece = rightValueExpanded.Substring(0, indexOfVerticalBar);
rightValueExpanded = rightValueExpanded.Substring(indexOfVerticalBar + 1);
}
// Capture the property name out of the regular expression.
string propertyName = singlePropertyMatch.Groups[1].ToString();
// Get the string collection for this property name, if one already exists.
StringCollection conditionedPropertyValues =
(StringCollection) conditionedPropertiesTable[propertyName];
// If this property is not already represented in the table, add a new entry
// for it.
if (conditionedPropertyValues == null)
{
conditionedPropertyValues = new StringCollection();
conditionedPropertiesTable[propertyName] = conditionedPropertyValues;
}
// If the "rightValueExpanded" is not already in the string collection
// for this property name, add it now.
if (!conditionedPropertyValues.Contains(rightValueExpandedPiece))
{
conditionedPropertyValues.Add(rightValueExpandedPiece);
}
}
}
}
}
/*
* Method: GatherReferencedPropertyNames
* Owner: DavidLe
*
* Find and record all of the properties that are referenced in the given
* condition.
*
* FUTURE: it is unfortunate that we have to completely parse+evaluate the expression
*/
internal static void GatherReferencedPropertyNames
(
string condition, // Can be null
XmlAttribute conditionAttribute, // XML attribute on which the condition is evaluated
Expander expander, // The set of properties to use for expansion
Hashtable conditionedPropertiesTable // Can be null
)
{
EvaluateCondition(condition, conditionAttribute, expander, conditionedPropertiesTable, ParserOptions.AllowProperties | ParserOptions.AllowItemLists, null, null);
}
// An array of hashtables with cached expression trees for all the combinations of condition strings
// and parser options
private static volatile Hashtable[] cachedExpressionTrees = new Hashtable[8 /* == ParserOptions.AllowAll*/]
{
new Hashtable(StringComparer.OrdinalIgnoreCase), new Hashtable(StringComparer.OrdinalIgnoreCase),
new Hashtable(StringComparer.OrdinalIgnoreCase), new Hashtable(StringComparer.OrdinalIgnoreCase),
new Hashtable(StringComparer.OrdinalIgnoreCase), new Hashtable(StringComparer.OrdinalIgnoreCase),
new Hashtable(StringComparer.OrdinalIgnoreCase), new Hashtable(StringComparer.OrdinalIgnoreCase)
};
/// <summary>
/// Evaluates a string representing a condition from a "condition" attribute.
/// If the condition is a malformed string, it throws an InvalidProjectFileException.
/// This method uses cached expression trees to avoid generating them from scratch every time it's called.
/// This method is thread safe and is called from engine and task execution module threads
/// </summary>
/// <param name="condition">Can be null</param>
/// <param name="conditionAttribute">XML attribute on which the condition is evaluated</param>
/// <param name="expander">All the data available for expanding embedded properties, metadata, and items</param>
/// <param name="itemListOptions"></param>
/// <returns>true, if the expression evaluates to true, otherwise false</returns>
internal static bool EvaluateCondition
(
string condition,
XmlAttribute conditionAttribute,
Expander expander,
ParserOptions itemListOptions,
Project parentProject
)
{
return EvaluateCondition(condition,
conditionAttribute,
expander,
parentProject.ConditionedProperties,
itemListOptions,
parentProject.ParentEngine.LoggingServices,
parentProject.ProjectBuildEventContext);
}
/// <summary>
/// Evaluates a string representing a condition from a "condition" attribute.
/// If the condition is a malformed string, it throws an InvalidProjectFileException.
/// This method uses cached expression trees to avoid generating them from scratch every time it's called.
/// This method is thread safe and is called from engine and task execution module threads
/// </summary>
/// <param name="condition">Can be null</param>
/// <param name="conditionAttribute">XML attribute on which the condition is evaluated</param>
/// <param name="expander">All the data available for expanding embedded properties, metadata, and items</param>
/// <param name="itemListOptions"></param>
/// <param name="loggingServices">Can be null</param>
/// <param name="eventContext"> contains contextual information for logging events</param>
/// <returns>true, if the expression evaluates to true, otherwise false</returns>
internal static bool EvaluateCondition
(
string condition,
XmlAttribute conditionAttribute,
Expander expander,
ParserOptions itemListOptions,
EngineLoggingServices loggingServices,
BuildEventContext buildEventContext
)
{
return EvaluateCondition(condition,
conditionAttribute,
expander,
null,
itemListOptions,
loggingServices,
buildEventContext);
}
/// <summary>
/// Evaluates a string representing a condition from a "condition" attribute.
/// If the condition is a malformed string, it throws an InvalidProjectFileException.
/// This method uses cached expression trees to avoid generating them from scratch every time it's called.
/// This method is thread safe and is called from engine and task execution module threads
/// </summary>
/// <param name="condition">Can be null</param>
/// <param name="conditionAttribute">XML attribute on which the condition is evaluated</param>
/// <param name="expander">All the data available for expanding embedded properties, metadata, and items</param>
/// <param name="conditionedPropertiesTable">Can be null</param>
/// <param name="itemListOptions"></param>
/// <param name="loggingServices">Can be null</param>
/// <param name="buildEventContext"> contains contextual information for logging events</param>
/// <returns>true, if the expression evaluates to true, otherwise false</returns>
internal static bool EvaluateCondition
(
string condition,
XmlAttribute conditionAttribute,
Expander expander,
Hashtable conditionedPropertiesTable,
ParserOptions itemListOptions,
EngineLoggingServices loggingServices,
BuildEventContext buildEventContext
)
{
ErrorUtilities.VerifyThrow((conditionAttribute != null) || (string.IsNullOrEmpty(condition)),
"If condition is non-empty, you must provide the XML node representing the condition.");
// An empty condition is equivalent to a "true" condition.
if (string.IsNullOrEmpty(condition))
{
return true;
}
Hashtable cachedExpressionTreesForCurrentOptions = cachedExpressionTrees[(int)itemListOptions];
// Try and see if we have an expression tree for this condition already
GenericExpressionNode parsedExpression = (GenericExpressionNode) cachedExpressionTreesForCurrentOptions[condition];
if (parsedExpression == null)
{
Parser conditionParser = new Parser();
#region REMOVE_COMPAT_WARNING
conditionParser.LoggingServices = loggingServices;
conditionParser.LogBuildEventContext = buildEventContext;
#endregion
parsedExpression = conditionParser.Parse(condition, conditionAttribute, itemListOptions);
// It's possible two threads will add a different tree to the same entry in the hashtable,
// but it should be rare and it's not a problem - the previous entry will be thrown away.
// We could ensure no dupes with double check locking but it's not really necessary here.
// Also, we don't want to lock on every read.
lock (cachedExpressionTreesForCurrentOptions)
{
cachedExpressionTreesForCurrentOptions[condition] = parsedExpression;
}
}
ConditionEvaluationState state = new ConditionEvaluationState(conditionAttribute, expander, conditionedPropertiesTable, condition);
bool result;
// We are evaluating this expression now and it can cache some state for the duration,
// so we don't want multiple threads working on the same expression
lock (parsedExpression)
{
result = parsedExpression.Evaluate(state);
parsedExpression.ResetState();
}
return result;
}
/// <summary>
/// Sets the inner XML/text of the given XML node, escaping as necessary.
/// </summary>
/// <owner>SumedhK</owner>
/// <param name="node"></param>
/// <param name="s">Can be empty string, but not null.</param>
internal static void SetXmlNodeInnerContents(XmlNode node, string s)
{
ErrorUtilities.VerifyThrow(s != null, "Need value to set.");
if (s.IndexOf('<') != -1)
{
// If the value looks like it probably contains XML markup ...
try
{
// Attempt to store it verbatim as XML.
node.InnerXml = s;
return;
}
catch (XmlException)
{
// But that may fail, in the event that "s" is not really well-formed
// XML. Eat the exception and fall through below ...
}
}
// The value does not contain valid XML markup. Store it as text, so it gets
// escaped properly.
node.InnerText = s;
}
/// <summary>
/// Extracts the inner XML/text of the given XML node, unescaping as necessary.
/// </summary>
/// <owner>SumedhK</owner>
/// <param name="node"></param>
/// <returns>Inner XML/text of specified node.</returns>
internal static string GetXmlNodeInnerContents(XmlNode node)
{
// XmlNode.InnerXml gives back a string that consists of the set of characters
// in between the opening and closing elements of the XML node, without doing any
// unescaping. Any "strange" character sequences (like "<![CDATA[...]]>" will remain
// exactly so and will not be translated or interpreted. The only modification that
// .InnerXml will do is that it will normalize any Xml contained within. This means
// normalizing whitespace between XML attributes and quote characters that surround XML
// attributes. If PreserveWhitespace is false, then it will also normalize whitespace
// between elements.
//
// XmlNode.InnerText strips out any Xml contained within, and then unescapes the rest
// of the text. So if the remaining text contains certain character sequences such as
// "&" or "<![CDATA[...]]>", these will be translated into their equivalent representations.
//
// It's hard to explain, but much easier to demonstrate with examples:
//
// Original XML XmlNode.InnerText XmlNode.InnerXml
// =========================== ============================== ======================================
//
// <a><![CDATA[whatever]]></a> whatever <![CDATA[whatever]]>
//
// <a>123<MyNode/>456</a> 123456 123<MyNode />456
//
// <a>123456</a> 123456 123456
//
// <a>123<MyNode b='<'/>456</a> 123456 123<MyNode b="<" />456
//
// <a>123&456</a> 123&456 123&456
// So the trick for MSBuild when interpreting a property value is to know which one to
// use ... InnerXml or InnerText. There are two basic scenarios we care about.
//
// 1.) The first scenario is that the user is trying to create a property whose
// contents are actually XML. That is to say that the contents may be written
// to a XML file, or may be passed in as a string to XmlDocument.LoadXml.
// In this case, we would want to use XmlNode.InnerXml, because we DO NOT want
// character sequences to be unescaped. If we did unescape them, then whatever
// XML parser tried to read in the stream as XML later on would totally barf.
//
// 2.) The second scenario is the the user is trying to create a property that
// is just intended to be treated as a string. That string may be very large
// and could contain all sorts of whitespace, carriage returns, special characters,
// etc. But in the end, it's just a big string. In this case, whatever
// task is actually processing this string ... it's not going to know anything
// about character sequences such as & and <. These character sequences
// are specific to XML markup. So, here we want to use XmlNode.InnerText so that
// the character sequences get unescaped into their actual character before
// the string is passed to the task (or wherever else the property is used).
// Of course, if the string value of the property needs to contain characters
// like <, >, &, etc., then the user must XML escape these characters otherwise
// the XML parser reading the project file will croak. Or if the user doesn't
// want to escape every instance of these characters, he can surround the whole
// thing with a CDATA tag. Again, if he does this, we don't want the task to
// receive the C, D, A, T, A as part of the string ... this should be stripped off.
// Again, using XmlNode.InnerText takes care of this.
//
// 2b.) A variation of the second scenario is that the user is trying to create a property
// that is just intended to be a string, but wants to comment out part of the string.
// For example, it's a semicolon separated list that's going ultimately to end up in a list.
// eg. (DDB #56841)
//
// <BuildDirectories>
// <!--
// env\TestTools\tshell\pkg;
// -->
// ndp\fx\src\VSIP\FrameWork;
// ndp\fx\src\xmlTools;
// ddsuites\src\vs\xmlTools;
// </BuildDirectories>
//
// In this case, we want to treat the string as text, so that we don't retrieve the comment.
// We only want to retrieve the comment if there's some other XML in there. The
// mere presence of an XML comment shouldn't make us think the value is XML.
//
// Given these two scenarios, how do we know whether the user intended to treat
// a property value as XML or text? We use a simple heuristic which is that if
// XmlNode.InnerXml contains any "<" characters, then there pretty much has to be
// XML in there, so we'll just use XmlNode.InnerXml. If there are no "<" characters that aren't merely comments,
// then we assume it's to be treated as text and we use XmlNode.InnerText. Also, if
// it looks like the whole thing is one big CDATA block, then we also use XmlNode.InnerText.
// XmlNode.InnerXml is much more expensive than InnerText. Don't use it for trivial cases.
// (single child node with a trivial value or no child nodes)
if (!node.HasChildNodes)
{
return string.Empty;
}
if (node.ChildNodes.Count == 1 && (node.FirstChild.NodeType == XmlNodeType.Text || node.FirstChild.NodeType == XmlNodeType.CDATA))
{
return node.InnerText;
}
string innerXml = node.InnerXml;
// If there is no markup under the XML node (detected by the presence
// of a '<' sign
int firstLessThan = innerXml.IndexOf('<');
if (firstLessThan == -1)
{
// return the inner text so it gets properly unescaped
return node.InnerText;
}
bool containsNoTagsOtherThanComments = ContainsNoTagsOtherThanComments(innerXml, firstLessThan);
// ... or if the only XML is comments,
if (containsNoTagsOtherThanComments)
{
// return the inner text so the comments are stripped
// (this is how one might comment out part of a list in a property value)
return node.InnerText;
}
// ...or it looks like the whole thing is a big CDATA tag ...
bool startsWithCData = (innerXml.IndexOf("<![CDATA[", StringComparison.Ordinal) == 0);
if (startsWithCData)
{
// return the inner text so it gets properly extracted from the CDATA
return node.InnerText;
}
// otherwise, it looks like genuine XML; return the inner XML so that
// tags and comments are preserved and any XML escaping is preserved
return innerXml;
}
/// <summary>
/// Figure out whether there are any XML tags, other than comment tags,
/// in the string.
/// </summary>
/// <remarks>
/// We know the string coming in is a valid XML fragment. (The project loaded after all.)
/// So for example we can ignore an open comment tag without a matching closing comment tag.
/// </remarks>
private static bool ContainsNoTagsOtherThanComments(string innerXml, int firstLessThan)
{
bool insideComment = false;
for (int i = firstLessThan; i < innerXml.Length; i++)
{
if (!insideComment)
{
// XML comments start with exactly "<!--"
if (i < innerXml.Length - 3
&& innerXml[i] == '<'
&& innerXml[i + 1] == '!'
&& innerXml[i + 2] == '-'
&& innerXml[i + 3] == '-')
{
// Found the start of a comment
insideComment = true;
i = i + 3;
continue;
}
}
if (!insideComment)
{
if (innerXml[i] == '<')
{
// Found a tag!
return false;
}
}
if (insideComment)
{
// XML comments end with exactly "-->"
if (i < innerXml.Length - 2
&& innerXml[i] == '-'
&& innerXml[i + 1] == '-'
&& innerXml[i + 2] == '>')
{
// Found the end of a comment
insideComment = false;
i = i + 2;
continue;
}
}
}
// Didn't find any tags, except possibly comments
return true;
}
// used to find the xmlns attribute
private static readonly Regex xmlnsPattern = new Regex("xmlns=\"[^\"]*\"\\s*");
/// <summary>
/// Removes the xmlns attribute from an XML string.
/// </summary>
/// <owner>SumedhK</owner>
/// <param name="xml">XML string to process.</param>
/// <returns>The modified XML string.</returns>
internal static string RemoveXmlNamespace(string xml)
{
return xmlnsPattern.Replace(xml, String.Empty);
}
/// <summary>
/// Escapes given string, that is replaces special characters with escape sequences that allow MSBuild hosts
/// to treat MSBuild-interpreted characters literally (';' becomes "%3b" and so on).
/// </summary>
/// <param name="unescapedExpression">string to escape</param>
/// <returns>escaped string</returns>
public static string Escape(string unescapedExpression)
{
return EscapingUtilities.Escape(unescapedExpression);
}
/// <summary>
/// Instantiates a new BuildEventFileInfo object using an XML node (presumably from the project
/// file). The reason this isn't just another constructor on BuildEventFileInfo is because
/// BuildEventFileInfo.cs gets compiled into multiple assemblies (Engine and Conversion, at least),
/// and not all of those assemblies have the code for XmlUtilities.
/// </summary>
/// <param name="xmlNode"></param>
/// <param name="defaultFile"></param>
/// <returns></returns>
/// <owner>RGoel</owner>
internal static BuildEventFileInfo CreateBuildEventFileInfo(XmlNode xmlNode, string defaultFile)
{
ErrorUtilities.VerifyThrow(xmlNode != null, "Need Xml node.");
// Get the file path out of the Xml node.
int line = 0;
int column = 0;
string file = XmlUtilities.GetXmlNodeFile(xmlNode, String.Empty);
if (file.Length == 0)
{
file = defaultFile;
}
else
{
// Compute the line number and column number of the XML node.
XmlSearcher.GetLineColumnByNode(xmlNode, out line, out column);
}
return new BuildEventFileInfo(file, line, column);
}
/// <summary>
/// Helper useful for lazy table creation
/// </summary>
internal static Hashtable CreateTableIfNecessary(Hashtable table)
{
if (table == null)
{
return new Hashtable(StringComparer.OrdinalIgnoreCase);
}
return table;
}
/// <summary>
/// Helper useful for lazy table creation
/// </summary>
internal static Dictionary<string, V> CreateTableIfNecessary<V>(Dictionary<string, V> table)
{
if (table == null)
{
return new Dictionary<string, V>(StringComparer.OrdinalIgnoreCase);
}
return table;
}
}
}
| |
// 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 NUnit.Framework;
using osu.Framework.Bindables;
namespace osu.Framework.Tests.Bindables
{
[TestFixture]
public class BindableLeasingTest
{
private Bindable<int> original;
[SetUp]
public void SetUp()
{
original = new Bindable<int>(1);
}
[TestCase(false)]
[TestCase(true)]
public void TestLeaseAndReturn(bool revert)
{
var leased = original.BeginLease(revert);
Assert.AreEqual(original.Value, leased.Value);
leased.Value = 2;
Assert.AreEqual(original.Value, 2);
Assert.AreEqual(original.Value, leased.Value);
leased.Return();
Assert.AreEqual(original.Value, revert ? 1 : 2);
}
[TestCase(false)]
[TestCase(true)]
public void TestLeaseReturnedOnUnbindAll(bool revert)
{
var leased = original.BeginLease(revert);
Assert.AreEqual(original.Value, leased.Value);
leased.Value = 2;
Assert.AreEqual(original.Value, 2);
Assert.AreEqual(original.Value, leased.Value);
original.UnbindAll();
Assert.AreEqual(original.Value, revert ? 1 : 2);
}
[Test]
public void TestConsecutiveLeases()
{
var leased1 = original.BeginLease(false);
leased1.Return();
var leased2 = original.BeginLease(false);
leased2.Return();
}
[Test]
public void TestModifyAfterReturnFail()
{
var leased1 = original.BeginLease(false);
leased1.Return();
Assert.Throws<InvalidOperationException>(() => leased1.Value = 2);
Assert.Throws<InvalidOperationException>(() => leased1.Disabled = true);
Assert.Throws<InvalidOperationException>(() => leased1.Return());
}
[Test]
public void TestDoubleLeaseFails()
{
original.BeginLease(false);
Assert.Throws<InvalidOperationException>(() => original.BeginLease(false));
}
[Test]
public void TestIncorrectEndLease()
{
// end a lease when no lease exists.
Assert.Throws<InvalidOperationException>(() => original.EndLease(null));
// end a lease with an incorrect bindable
original.BeginLease(true);
Assert.Throws<InvalidOperationException>(() => original.EndLease(new Bindable<int>().BeginLease(true)));
}
[Test]
public void TestDisabledStateDuringLease()
{
Assert.IsFalse(original.Disabled);
var leased = original.BeginLease(true);
Assert.IsTrue(original.Disabled);
Assert.IsTrue(leased.Disabled); // during lease, the leased bindable is also set to a disabled state (but is always bypassed when setting the value via it directly).
// you can't change the disabled state of the original during a lease...
Assert.Throws<InvalidOperationException>(() => original.Disabled = false);
// ..but you can change it from the leased instance..
leased.Disabled = false;
Assert.IsFalse(leased.Disabled);
Assert.IsFalse(original.Disabled);
// ..allowing modification of the original during lease.
original.Value = 2;
// even if not disabled, you still cannot change disabled from the original during a lease.
Assert.Throws<InvalidOperationException>(() => original.Disabled = true);
Assert.IsFalse(original.Disabled);
Assert.IsFalse(leased.Disabled);
// you must use the leased instance.
leased.Disabled = true;
Assert.IsTrue(original.Disabled);
Assert.IsTrue(leased.Disabled);
leased.Return();
Assert.IsFalse(original.Disabled);
}
[Test]
public void TestDisabledChangeViaBindings()
{
original.BeginLease(true);
// ensure we can't change original's disabled via a bound bindable.
var bound = original.GetBoundCopy();
Assert.Throws<InvalidOperationException>(() => bound.Disabled = false);
Assert.IsTrue(original.Disabled);
}
[Test]
public void TestDisabledChangeViaBindingToLeased()
{
bool? changedState = null;
original.DisabledChanged += d => changedState = d;
var leased = original.BeginLease(true);
var bound = leased.GetBoundCopy();
bound.Disabled = false;
Assert.AreEqual(changedState, false);
Assert.IsFalse(original.Disabled);
}
[Test]
public void TestValueChangeViaBindings()
{
original.BeginLease(true);
// ensure we can't change original's disabled via a bound bindable.
var bound = original.GetBoundCopy();
Assert.Throws<InvalidOperationException>(() => bound.Value = 2);
Assert.AreEqual(original.Value, 1);
}
[TestCase(false)]
[TestCase(true)]
public void TestDisabledRevertedAfterLease(bool revert)
{
bool? changedState = null;
original.Disabled = true;
original.DisabledChanged += d => changedState = d;
var leased = original.BeginLease(revert);
leased.Return();
// regardless of revert specification, disabled should always be reverted to the original value.
Assert.IsTrue(original.Disabled);
Assert.IsFalse(changedState.HasValue);
}
[Test]
public void TestLeaseFromBoundBindable()
{
var copy = original.GetBoundCopy();
var leased = copy.BeginLease(true);
// can't take a second lease from the original.
Assert.Throws<InvalidOperationException>(() => original.BeginLease(false));
// can't take a second lease from the copy.
Assert.Throws<InvalidOperationException>(() => copy.BeginLease(false));
leased.Value = 2;
// value propagates everywhere
Assert.AreEqual(original.Value, 2);
Assert.AreEqual(original.Value, copy.Value);
Assert.AreEqual(original.Value, leased.Value);
// bound copies of the lease still allow setting value / disabled.
var leasedCopy = leased.GetBoundCopy();
leasedCopy.Value = 3;
Assert.AreEqual(original.Value, 3);
Assert.AreEqual(original.Value, copy.Value);
Assert.AreEqual(original.Value, leased.Value);
Assert.AreEqual(original.Value, leasedCopy.Value);
leasedCopy.Disabled = false;
leasedCopy.Disabled = true;
leased.Return();
original.Value = 1;
Assert.AreEqual(original.Value, 1);
Assert.AreEqual(original.Value, copy.Value);
Assert.IsFalse(original.Disabled);
}
[Test]
public void TestCantLeaseFromLease()
{
var leased = original.BeginLease(false);
Assert.Throws<InvalidOperationException>(() => leased.BeginLease(false));
}
[Test]
public void TestCantLeaseFromBindingChain()
{
var bound1 = original.GetBoundCopy();
var bound2 = bound1.GetBoundCopy();
original.BeginLease(false);
Assert.Throws<InvalidOperationException>(() => bound2.BeginLease(false));
}
[Test]
public void TestReturnFromBoundCopyOfLeaseFails()
{
var leased = original.BeginLease(true);
var copy = leased.GetBoundCopy();
Assert.Throws<InvalidOperationException>(() => ((LeasedBindable<int>)copy).Return());
}
[Test]
public void TestUnbindAllReturnsLease()
{
var leased = original.BeginLease(true);
leased.UnbindAll();
leased.UnbindAll();
}
[Test]
public void TestLeasedBoundToMultiple()
{
var leased = original.BeginLease(false);
var another = new Bindable<int>();
leased.BindTo(another);
another.Value = 3;
Assert.AreEqual(another.Value, 3);
Assert.AreEqual(another.Value, leased.Value);
leased.Value = 4;
Assert.AreEqual(original.Value, 4);
Assert.AreEqual(another.Value, 4);
Assert.AreEqual(original.Value, leased.Value);
}
}
}
| |
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using OrchardCore.Admin;
using OrchardCore.ContentManagement;
using OrchardCore.ContentManagement.Display.ContentDisplay;
using OrchardCore.Data.Migration;
using OrchardCore.DisplayManagement;
using OrchardCore.Entities;
using OrchardCore.Modules;
using OrchardCore.Mvc.Core.Utilities;
using OrchardCore.Navigation;
using OrchardCore.Routing;
using OrchardCore.Security.Permissions;
using OrchardCore.Sitemaps.Builders;
using OrchardCore.Sitemaps.Cache;
using OrchardCore.Sitemaps.Controllers;
using OrchardCore.Sitemaps.Drivers;
using OrchardCore.Sitemaps.Handlers;
using OrchardCore.Sitemaps.Models;
using OrchardCore.Sitemaps.Routing;
using OrchardCore.Sitemaps.Services;
namespace OrchardCore.Sitemaps
{
public class Startup : StartupBase
{
private readonly AdminOptions _adminOptions;
public Startup(IOptions<AdminOptions> adminOptions)
{
_adminOptions = adminOptions.Value;
}
public override void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IDataMigration, Migrations>();
services.AddScoped<INavigationProvider, AdminMenu>();
services.AddScoped<IPermissionProvider, Permissions>();
services.AddIdGeneration();
services.Configure<SitemapsOptions>(options =>
{
if (options.GlobalRouteValues.Count == 0)
{
options.GlobalRouteValues = new RouteValueDictionary
{
{"Area", "OrchardCore.Sitemaps"},
{"Controller", "Sitemap"},
{"Action", "Index"}
};
options.SitemapIdKey = "sitemapId";
}
});
services.AddSingleton<IShellRouteValuesAddressScheme, SitemapValuesAddressScheme>();
services.AddSingleton<SitemapsTransformer>();
services.AddSingleton<SitemapEntries>();
services.AddScoped<ISitemapIdGenerator, SitemapIdGenerator>();
services.AddScoped<IPermissionProvider, Permissions>();
services.AddScoped<ISitemapManager, SitemapManager>();
services.AddScoped<ISitemapHelperService, SitemapHelperService>();
services.AddScoped<IDisplayManager<SitemapSource>, DisplayManager<SitemapSource>>();
services.AddScoped<ISitemapBuilder, DefaultSitemapBuilder>();
services.AddScoped<ISitemapTypeBuilder, SitemapTypeBuilder>();
services.AddScoped<ISitemapCacheProvider, DefaultSitemapCacheProvider>();
services.AddScoped<ISitemapCacheManager, DefaultSitemapCacheManager>();
services.AddScoped<ISitemapTypeCacheManager, SitemapTypeCacheManager>();
services.AddScoped<ISitemapTypeBuilder, SitemapIndexTypeBuilder>();
services.AddScoped<ISitemapTypeCacheManager, SitemapIndexTypeCacheManager>();
services.AddScoped<ISitemapModifiedDateProvider, DefaultSitemapModifiedDateProvider>();
services.AddScoped<IRouteableContentTypeCoordinator, DefaultRouteableContentTypeCoordinator>();
services.AddScoped<ISitemapPartContentItemValidationProvider, SitemapPartContentItemValidationProvider>();
services.AddScoped<ISitemapContentItemValidationProvider>(serviceProvider =>
serviceProvider.GetRequiredService<ISitemapPartContentItemValidationProvider>());
// Sitemap Part.
services.AddContentPart<SitemapPart>()
.UseDisplayDriver<SitemapPartDisplay>()
.AddHandler<SitemapPartHandler>();
}
public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider)
{
var adminControllerName = typeof(AdminController).ControllerName();
routes.MapAreaControllerRoute(
name: "SitemapsList",
areaName: "OrchardCore.Sitemaps",
pattern: _adminOptions.AdminUrlPrefix + "/Sitemaps/List",
defaults: new { controller = adminControllerName, action = nameof(AdminController.List) }
);
routes.MapAreaControllerRoute(
name: "SitemapsDisplay",
areaName: "OrchardCore.Sitemaps",
pattern: _adminOptions.AdminUrlPrefix + "/Sitemaps/Display/{id}",
defaults: new { controller = adminControllerName, action = nameof(AdminController.Display) }
);
routes.MapAreaControllerRoute(
name: "SitemapsCreate",
areaName: "OrchardCore.Sitemaps",
pattern: _adminOptions.AdminUrlPrefix + "/Sitemaps/Create",
defaults: new { controller = adminControllerName, action = nameof(AdminController.Create) }
);
routes.MapAreaControllerRoute(
name: "SitemapsEdit",
areaName: "OrchardCore.Sitemaps",
pattern: _adminOptions.AdminUrlPrefix + "/Sitemaps/Edit/{sitemapId}",
defaults: new { controller = adminControllerName, action = nameof(AdminController.Edit) }
);
routes.MapAreaControllerRoute(
name: "SitemapsDelete",
areaName: "OrchardCore.Sitemaps",
pattern: _adminOptions.AdminUrlPrefix + "/Sitemaps/Delete/{sitemapId}",
defaults: new { controller = adminControllerName, action = nameof(AdminController.Delete) }
);
routes.MapAreaControllerRoute(
name: "SitemapsToggle",
areaName: "OrchardCore.Sitemaps",
pattern: _adminOptions.AdminUrlPrefix + "/Sitemaps/Toggle/{sitemapId}",
defaults: new { controller = adminControllerName, action = nameof(AdminController.Toggle) }
);
var sitemapIndexController = typeof(SitemapIndexController).ControllerName();
routes.MapAreaControllerRoute(
name: "SitemapIndexesList",
areaName: "OrchardCore.Sitemaps",
pattern: _adminOptions.AdminUrlPrefix + "/SitemapIndexes/List",
defaults: new { controller = sitemapIndexController, action = nameof(SitemapIndexController.List) }
);
routes.MapAreaControllerRoute(
name: "SitemapIndexesCreate",
areaName: "OrchardCore.Sitemaps",
pattern: _adminOptions.AdminUrlPrefix + "/SitemapIndexes/Create",
defaults: new { controller = sitemapIndexController, action = nameof(SitemapIndexController.Create) }
);
routes.MapAreaControllerRoute(
name: "SitemapIndexesEdit",
areaName: "OrchardCore.Sitemaps",
pattern: _adminOptions.AdminUrlPrefix + "/SitemapIndexes/Edit/{sitemapId}",
defaults: new { controller = sitemapIndexController, action = nameof(SitemapIndexController.Edit) }
);
routes.MapAreaControllerRoute(
name: "SitemapIndexesDelete",
areaName: "OrchardCore.Sitemaps",
pattern: _adminOptions.AdminUrlPrefix + "/SitemapIndexes/Delete/{sitemapId}",
defaults: new { controller = sitemapIndexController, action = nameof(SitemapIndexController.Delete) }
);
routes.MapAreaControllerRoute(
name: "SitemapIndexesToggle",
areaName: "OrchardCore.Sitemaps",
pattern: _adminOptions.AdminUrlPrefix + "/SitemapIndexes/Toggle/{sitemapId}",
defaults: new { controller = sitemapIndexController, action = nameof(SitemapIndexController.Toggle) }
);
var sourceController = typeof(SourceController).ControllerName();
routes.MapAreaControllerRoute(
name: "SitemapsSourceCreate",
areaName: "OrchardCore.Sitemaps",
pattern: _adminOptions.AdminUrlPrefix + "/SitemapSource/Create/{sitemapId}/{sourceType}",
defaults: new { controller = sourceController, action = nameof(SourceController.Create) }
);
routes.MapAreaControllerRoute(
name: "SitemapsSourceEdit",
areaName: "OrchardCore.Sitemaps",
pattern: _adminOptions.AdminUrlPrefix + "/SitemapSource/Edit/{sitemapId}/{sourceId}",
defaults: new { controller = sourceController, action = nameof(SourceController.Edit) }
);
routes.MapAreaControllerRoute(
name: "SitemapsSourceDelete",
areaName: "OrchardCore.Sitemaps",
pattern: _adminOptions.AdminUrlPrefix + "/SitemapSource/Delete/{sitemapId}/{sourceId}",
defaults: new { controller = sourceController, action = nameof(SourceController.Delete) }
);
var sitemapCacheController = typeof(SitemapCacheController).ControllerName();
routes.MapAreaControllerRoute(
name: "SitemapsCacheList",
areaName: "OrchardCore.Sitemaps",
pattern: _adminOptions.AdminUrlPrefix + "/SitemapsCache/List",
defaults: new { controller = sitemapCacheController, action = nameof(SitemapCacheController.List) }
);
routes.MapAreaControllerRoute(
name: "SitemapsCachePurgeAll",
areaName: "OrchardCore.Sitemaps",
pattern: _adminOptions.AdminUrlPrefix + "/SitemapsCache/PurgeAll",
defaults: new { controller = sitemapCacheController, action = nameof(SitemapCacheController.PurgeAll) }
);
routes.MapAreaControllerRoute(
name: "SitemapsCachePurge",
areaName: "OrchardCore.Sitemaps",
pattern: _adminOptions.AdminUrlPrefix + "/SitemapsCache/Purge/{cacheFileName}",
defaults: new { controller = sitemapCacheController, action = nameof(SitemapCacheController.Purge) }
);
routes.MapDynamicControllerRoute<SitemapsTransformer>("/{**sitemap}");
var sitemapManager = serviceProvider.GetService<ISitemapManager>();
sitemapManager.BuildAllSitemapRouteEntriesAsync().GetAwaiter().GetResult();
}
}
[Feature("OrchardCore.Sitemaps.RazorPages")]
public class SitemapsRazorPagesStartup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddOptions<SitemapsRazorPagesOptions>();
services.AddScoped<IRouteableContentTypeProvider, RazorPagesContentTypeProvider>();
}
}
}
| |
using System;
using System.Collections.Generic;
using Oracle.DataAccess.Client;
using spinat.dotnetplsql;
using NUnit.Framework;
namespace spinat.dotnetplsqltests
{
[TestFixture]
public class FuncTest
{
public FuncTest()
{
}
//@BeforeClass
//public static void setUpClass() {
//}
//@AfterClass
//public static void tearDownClass() {
//}
OracleConnection connection;
[OneTimeSetUp]
public void setUp()
{
var b = new OracleConnectionStringBuilder();
b.UserID = "roland";
b.Password = "roland";
b.DataSource = "ltrav01";
var c = new OracleConnection();
c.ConnectionString = b.ConnectionString;
c.Open();
this.connection = c;
Dictionary<String, String> a = TestUtil.LoadSnippets("snippets.txt");
Ddl.call(connection, a["p1_spec"]);
Ddl.call(connection, a["p1_body"]);
Ddl.call(connection, a["proc1"]);
Ddl.createType(connection, "create type number_array as table of number;");
Ddl.createType(connection, "create type varchar2_array as table of varchar2(32767);");
Ddl.createType(connection, "create type date_array as table of date;");
Ddl.createType(connection, "create type raw_array as table of raw(32767);");
}
//@After
//public void tearDown() {
//}
[Test]
public void t1()
{
var ar = new Dictionary<String, Object>();
ar["XI"] = 12;
ar["YI"] = "x";
ar["ZI"] = DateTime.Now;
var res = new ProcedureCaller(connection).Call("P1.P", ar);
System.Console.WriteLine(res);
Assert.True(res["XO"].Equals(new Decimal(13)) && res["YO"].Equals("xx"));
}
[Test]
public void t1p()
{
ProcedureCaller p = new ProcedureCaller(connection);
var xo = new Box();
var yo = new Box();
var zo = new Box();
p.CallPositional("P1.P", 12, "x", DateTime.Now, xo, yo, zo);
Assert.AreEqual(xo.Value, new decimal(13));
Assert.AreEqual(yo.Value, "xx");
}
[Test]
public void test2()
{
Dictionary<String, Object> ar = new Dictionary<String, Object>();
var a = new Dictionary<String, Object>();
a["X"] = 12;
a["Y"] = "x";
a["Z"] = DateTime.Now;
ar["A"] = a;
Dictionary<String, Object> res = new ProcedureCaller(connection).Call("P1.P2", ar);
Console.WriteLine(res);
Dictionary<String, Object> m = (Dictionary<String, Object>)res["B"];
Assert.True(m["X"].Equals(new Decimal(13)) && m["Y"].Equals("xx"));
}
[Test]
public void test2p()
{
var a = new Dictionary<String, Object>();
a["X"] = 12;
a["Y"] = "x";
a["Z"] = DateTime.Now;
ProcedureCaller p = new ProcedureCaller(connection);
Box b = new Box();
p.CallPositional("P1.P2", a, b);
Dictionary<String, Object> m = (Dictionary<String, Object>)b.Value;
Assert.AreEqual(m["X"], new Decimal(13));
Assert.AreEqual(m["Y"], "xx");
}
public void test3Base(int size)
{
Dictionary<String, Object> ar = new Dictionary<String, Object>();
List<Dictionary<String, Object>> l = new List<Dictionary<String, Object>>();
for (int i = 0; i < size; i++)
{
var a = new Dictionary<String, Object>();
a["X"] = new Decimal(i);
a["Y"] = "x" + i;
a["Z"] = DateTime.Now;
l.Add(a);
}
ar["A"] = l;
Dictionary<String, Object> res = new ProcedureCaller(connection).Call("P1.P3", ar);
var l2 = (System.Collections.IList)res["B"];
for (int i = 0; i < l.Count; i++)
{
Dictionary<String, Object> m = l[i];
Dictionary<String, Object> m2 = (Dictionary<String, Object>)l2[i];
Assert.True(m2["X"].Equals(((Decimal)m["X"]) + new Decimal(1)));
Assert.True(m2["Y"].Equals("" + m["Y"] + m["Y"]));
}
}
[Test]
public void test3()
{
test3Base(10);
}
[Test]
public void test4()
{
var ar = new Dictionary<String, Object>();
var l0 = new List<Object>();
for (int j = 0; j < 3; j++)
{
var l = new List<Dictionary<String, Object>>();
for (int i = 0; i < 2; i++)
{
var a = new Dictionary<String, Object>();
a["X"] = new Decimal(i);
a["Y"] = "x" + i;
a["Z"] = new DateTime(2013, 5, 1);
l.Add(a);
}
l0.Add(l);
}
ar["A"] = l0;
Dictionary<String, Object> res = new ProcedureCaller(connection).Call("P1.P4", ar);
System.Console.WriteLine(res);
var l2 = (System.Collections.IList)res["A"];
for (int i = 0; i < l2.Count; i++)
{
var x = (System.Collections.IList)l2[i];
var y = (System.Collections.IList)l0[i];
for (int j = 0; j < x.Count; j++)
{
var m1 = (Dictionary<String, Object>)x[j];
var m2 = (Dictionary<String, Object>)y[j];
Assert.True(m1["X"].Equals(m2["X"]));
Assert.True(m1["Y"].Equals(m2["Y"]));
Assert.True(m1["Z"].Equals(m2["Z"]));
}
}
}
[Test]
public void test5()
{
var ar = new Dictionary<String, Object>();
var a = new Dictionary<String, Object>();
a["X"] = null;
a["Y"] = null;
a["Z"] = null;
ar["A"] = a;
var res = new ProcedureCaller(connection).Call("P1.P2", ar);
System.Console.WriteLine(res);
var m = (Dictionary<String, Object>)res["B"];
Assert.True(m["X"] == null);
Assert.True(m["Y"] == null);
Assert.True(m["Z"] != null);
}
[Test]
public void test5p()
{
var a = new Dictionary<String, Object>();
a["X"] = null;
a["Y"] = null;
a["Z"] = null;
Box b = new Box();
new ProcedureCaller(connection).CallPositional("P1.P2", a, b);
var m = (Dictionary<String, Object>)b.Value;
Assert.IsNull(m["X"]);
Assert.IsNull(m["Y"]);
}
[Test]
public void test6()
{
var ar = new Dictionary<String, Object>();
var l0 = new List<Object>();
for (int j = 0; j < 3; j++)
{
l0.Add(null);
}
ar["A"] = l0;
var res = new ProcedureCaller(connection).Call("P1.P4", ar);
Console.WriteLine(res);
var l2 = (System.Collections.IList)res["A"];
for (int i = 0; i < l2.Count; i++)
{
Assert.True(l2[i] == null);
}
}
[Test]
public void test7()
{
var a = new Dictionary<String, Object>();
a["X"] = 23;
a["Y"] = "roland";
a["Z"] = DateTime.Now;
var m = new ProcedureCaller(connection).Call("proc1", a);
}
[Test]
public void test8()
{
var a = new Dictionary<String, Object>();
var m = new ProcedureCaller(connection).Call("p1.p6", a);
}
[Test]
public void test9()
{
var a = new Dictionary<String, Object>();
a["A"] = -123;
a["B"] = "rote gruetze";
var dat = new DateTime(2014, 12, 3, 23, 45, 1, 0);
a["C"] = dat;
var m = new ProcedureCaller(connection).Call("p1.f7", a);
var r = (Dictionary<String, Object>)m["RETURN"];
Assert.True(r["X"].Equals(new Decimal(-123)));
Assert.True(r["Y"].Equals("rote gruetze"));
Assert.True(r["Z"].Equals(dat));
}
[Test]
public void test10()
{
var a = new Dictionary<String, Object>();
{
a["X"] = true;
var m = new ProcedureCaller(connection).Call("p1.p8", a);
var y = (bool)(m["Y"]);
Assert.True(!y);
}
{
a["X"] = false;
var m = new ProcedureCaller(connection).Call("p1.p8", a);
var y = (bool)(m["Y"]);
Assert.True(y);
}
{
a["X"] = null;
var m = new ProcedureCaller(connection).Call("p1.p8", a);
var y = (bool?)(m["Y"]);
Assert.True(!y.HasValue);
}
}
[Test]
public void test11()
{
var a = new Dictionary<String, Object>();
{
a["X1"] = 1;
a["X2"] = 19;
var m = new ProcedureCaller(connection).Call("p1.p9", a);
var y1 = (Decimal)m["Y1"];
Assert.True(y1.Equals(new Decimal(-1)));
var y2 = (Decimal)m["Y2"];
Assert.True(y2.Equals(new Decimal(29)));
}
}
// procedure p5 takes a table is argument and return it in its
// out argument
[Test]
public void testTableNull()
{
Box b = new Box();
ProcedureCaller p = new ProcedureCaller(connection);
p.CallPositional("p1.p5", null, b);
Assert.Null(b.Value);
List<String> l = new List<String>();
p.CallPositional("p1.p5", l, b);
Assert.NotNull(b.Value);
Assert.AreEqual(0, ((List<Object>)b.Value).Count);
}
// test various methods to write a strored procedure
[Test]
public void testName1()
{
var a = new Dictionary<String, Object>();
ProcedureCaller p = new ProcedureCaller(connection);
Dictionary<String, Object> res;
res = p.Call("p1.no_args", a);
res = p.Call("\"P1\".no_args", a);
res = p.Call("\"P1\".\"NO_ARGS\"", a);
res = p.Call("p1.\"NO_ARGS\"", a);
res = p.Call("p1.\"NO_ARGS\"", a);
}
[Test]
public void testName2()
{
var a = new Dictionary<String, Object>();
ProcedureCaller p = new ProcedureCaller(connection);
Dictionary<String, Object> res;
Exception ex = null;
try
{
res = p.Call("p1.this_proc_does_not_exist", a);
}
catch (Exception exe)
{
ex = exe;
}
Assert.NotNull(ex);
Assert.True(ex is ApplicationException);
Assert.True(ex.Message.Contains("procedure in package does not exist or object is not valid"));
}
[Test]
public void TestSysRefCursor()
{
ProcedureCaller p = new ProcedureCaller(connection);
Box b = new Box();
var dat = new DateTime(2001, 12, 1);
var bytes = new byte[] { 1, 2, 0, 4, 5, 255 };
p.CallPositional("p1.pcursor1", 17, "xyz", dat, bytes, b);
var l = (List<Dictionary<String, Object>>)b.Value;
Assert.AreEqual(l.Count, 2);
var r2 = l[1];
Assert.AreEqual(r2["A"], "xyz");
Assert.AreEqual(r2["B"], new decimal(17));
Assert.AreEqual(r2["C"], dat);
Assert.AreEqual(bytes,r2["D"]);
}
[Test]
public void TestRefCursor()
{
ProcedureCaller p = new ProcedureCaller(connection);
Box b = new Box();
DateTime dat = new DateTime(2001, 12, 1);
var bytes = new byte[] { 1, 2, 0, 4, 5, 255 };
p.CallPositional("p1.pcursor2", 17, "xyz", dat,bytes, b);
var l = (List<Dictionary<String, Object>>)b.Value;
Assert.AreEqual(l.Count, 2);
var r2 = l[1];
Assert.AreEqual(r2["V"], "xyz");
Assert.AreEqual(r2["N"], new Decimal(17));
Assert.AreEqual(r2["D"], dat);
Assert.AreEqual(r2["R"], bytes);
}
[Test]
public void TestRefCursor3()
{
ProcedureCaller p = new ProcedureCaller(connection);
Box b = new Box();
Exception ex = null;
try
{
p.CallPositional("p1.pcursor3", b);
}
catch (Exception exe)
{
ex = exe;
}
Assert.True(ex != null && ex is ApplicationException);
Assert.True(ex.Message.Contains("%rowtype"));
}
[Test]
public void TestIndexBy()
{
int n = 20;
ProcedureCaller p = new ProcedureCaller(connection);
var args = new Dictionary<String, Object>();
var ai = new SortedDictionary<String, Object>();
for (int i = 0; i < n; i++)
{
ai["k" + i] = "v" + i;
}
args["AI"] = ai;
var bi = new SortedDictionary<int, Object>();
for (int i = 0; i < n; i++)
{
bi[i] = "v" + i;
}
args["BI"] = bi;
var res = p.Call("p1.pindex_tab", args);
var ao = (SortedDictionary<String, Object>)res["AO"];
var bo = (SortedDictionary<int, Object>)res["BO"];
Assert.AreEqual(ao.Count, n);
for (int i = 0; i < n; i++)
{
Assert.IsTrue(ao["xk" + i].Equals(ai["k" + i] + "y"));
}
Assert.AreEqual(bo.Count, n);
for (int i = 0; i < n; i++)
{
Assert.True(bo[2 * i].Equals(bi[i] + "y"));
}
}
[Test]
public void TestIndexBy2()
{
int n = 10;
ProcedureCaller p = new ProcedureCaller(connection);
var args = new Dictionary<String, Object>();
var tm = new SortedDictionary<String, Object>();
args["X"] = tm;
for (int i = 0; i < n; i++)
{
var h = new SortedDictionary<String, Object>();
for (int j = 0; j < n; j++)
{
h["" + j + "," + i] = "v" + j + "," + i;
}
tm["a" + i] = h;
}
Dictionary<String, Object> res = p.Call("p1.pindex_tab2", args);
var tm2 = (SortedDictionary<String, Object>)res["X"];
Assert.True(tm2.Count == tm.Count);
foreach (String k in tm.Keys)
{
var h1 = (SortedDictionary<String, Object>)tm[k];
var h2 = (SortedDictionary<String, Object>)tm2[k];
Assert.True(h1.Count == h2.Count);
foreach (String kk in h1.Keys)
{
Assert.True(h2[kk].Equals(h1[kk]));
}
}
}
[Test]
public void testRaw()
{
ProcedureCaller p = new ProcedureCaller(connection);
var args = new Dictionary<String, Object>();
byte[] b = new byte[] { 1, 2, 3, 4, 76, 97 };
args["X"] = b;
args["SIZEE"] = b.Length;
var res = p.Call("p1.praw", args);
byte[] b2 = (byte[])res["Y"];
Assert.True(b2.Length == b.Length);
for (int i = 0; i < b2.Length; i++)
{
Assert.True(b[i] == b2[i]);
}
}
[Test]
public void testRaw2()
{
ProcedureCaller p = new ProcedureCaller(connection);
var args = new Dictionary<String, Object>();
byte[] b = new byte[0];
args["X"] = b;
args["SIZEE"] = b.Length;
var res = p.Call("p1.praw", args);
byte[] b2 = (byte[])res["Y"];
Assert.True(b2 == null);
//
args["X"] = null;
args["SIZEE"] = null;
var res2 = p.Call("p1.praw", args);
byte[] b22 = (byte[])res["Y"];
Assert.True(b22 == null);
}
[Test]
public void testRawBig()
{
int n = 32767;
ProcedureCaller p = new ProcedureCaller(connection);
var args = new Dictionary<String, Object>();
byte[] b = new byte[n];
for (int i = 0; i < b.Length; i++)
{
b[i] = (byte)(i * 7 & 255);
}
args["X"] = b;
args["SIZEE"] = b.Length;
var res = p.Call("p1.praw", args);
byte[] b2 = (byte[])res["Y"];
Assert.AreEqual(b2.Length, b.Length);
for (int i = 0; i < b2.Length; i++)
{
Assert.True(b[i] == b2[i]);
}
}
[Test]
public void testVarcharBig()
{
int n = 32767;
ProcedureCaller p = new ProcedureCaller(connection);
var args = new Dictionary<String, Object>();
char[] b = new char[n];
for (int i = 0; i < b.Length; i++)
{
b[i] = (char)(i * 7 +1& 127);
if (b[i] == 0)
{
b[i] = (char)1;
}
}
String s = new String(b);
args["X"] = s;
args["SIZEE"] = s.Length;
var res = p.Call("p1.pvarchar2", args);
var s2 = (string)res["Y"];
Assert.AreEqual(s.Length, s2.Length);
for (int i = 0; i < s2.Length; i++)
{
Assert.True(s[i] == s2[i]);
}
}
public void testVarcharBig2()
{
ProcedureCaller p = new ProcedureCaller(connection);
var args = new Dictionary<String, Object>();
String s = "roland";
args["X"] = s;
args["SIZEE"] = s.Length;
var res = p.Call("p1.pvarchar2", args);
var s2 = (string)res["Y"];
Assert.AreEqual(s.Length, s2.Length);
for (int i = 0; i < s2.Length; i++)
{
Assert.True(s[i] == s2[i]);
}
}
[Test]
public void testVarcharout()
{
ProcedureCaller p = new ProcedureCaller(connection);
var box = new Box();
p.CallPositional("p1.varchar2_out",new Object[]{box});
// we get "" instead of null! Thr eturn value is chr(0)||'roland'
// and the oci code cuts this off c strings?
Assert.AreEqual("", (string)box.Value);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Xunit;
namespace System.Collections.ObjectModel.Tests
{
/// <summary>
/// Tests the public properties and constructor in ObservableCollection<T>.
/// </summary>
public class ReadOnlyObservableCollectionTests
{
[Fact]
public static void Ctor_Tests()
{
string[] anArray = new string[] { "one", "two", "three", "four", "five" };
ReadOnlyObservableCollection<string> readOnlyCol =
new ReadOnlyObservableCollection<string>(new ObservableCollection<string>(anArray));
IReadOnlyList_T_Test<string> helper = new IReadOnlyList_T_Test<string>(readOnlyCol, anArray);
helper.InitialItems_Tests();
IList<string> readOnlyColAsIList = readOnlyCol;
Assert.True(readOnlyColAsIList.IsReadOnly, "ReadOnlyObservableCollection should be readOnly.");
}
[Fact]
public static void Ctor_Tests_Negative()
{
AssertExtensions.Throws<ArgumentNullException>("list", () => new ReadOnlyObservableCollection<string>(null));
}
[Fact]
public static void GetItemTests()
{
string[] anArray = new string[] { "one", "two", "three", "four", "five" };
ReadOnlyObservableCollection<string> readOnlyCol =
new ReadOnlyObservableCollection<string>(new ObservableCollection<string>(anArray));
IReadOnlyList_T_Test<string> helper = new IReadOnlyList_T_Test<string>(readOnlyCol, anArray);
helper.Item_get_Tests();
}
[Fact]
public static void GetItemTests_Negative()
{
string[] anArray = new string[] { "one", "two", "three", "four", "five" };
ReadOnlyObservableCollection<string> readOnlyCol =
new ReadOnlyObservableCollection<string>(new ObservableCollection<string>(anArray));
IReadOnlyList_T_Test<string> helper = new IReadOnlyList_T_Test<string>(readOnlyCol, anArray);
helper.Item_get_Tests_Negative();
}
/// <summary>
/// Tests that contains returns true when the item is in the collection
/// and false otherwise.
/// </summary>
[Fact]
public static void ContainsTests()
{
string[] anArray = new string[] { "one", "two", "three", "four", "five" };
ReadOnlyObservableCollection<string> readOnlyCol =
new ReadOnlyObservableCollection<string>(new ObservableCollection<string>(anArray));
for (int i = 0; i < anArray.Length; i++)
{
string item = anArray[i];
Assert.True(readOnlyCol.Contains(item), "ReadOnlyCol did not contain item: " + anArray[i] + " at index: " + i);
}
Assert.False(readOnlyCol.Contains("randomItem"), "ReadOnlyCol should not have contained non-existent item");
Assert.False(readOnlyCol.Contains(null), "ReadOnlyCol should not have contained null");
}
/// <summary>
/// Tests that the collection can be copied into a destination array.
/// </summary>
[Fact]
public static void CopyToTest()
{
string[] anArray = new string[] { "one", "two", "three", "four" };
ReadOnlyObservableCollection<string> readOnlyCol =
new ReadOnlyObservableCollection<string>(new ObservableCollection<string>(anArray));
string[] aCopy = new string[anArray.Length];
readOnlyCol.CopyTo(aCopy, 0);
for (int i = 0; i < anArray.Length; ++i)
Assert.Equal(anArray[i], aCopy[i]);
// copy observable collection starting in middle, where array is larger than source.
aCopy = new string[anArray.Length + 2];
int offsetIndex = 1;
readOnlyCol.CopyTo(aCopy, offsetIndex);
for (int i = 0; i < aCopy.Length; i++)
{
string value = aCopy[i];
if (i == 0)
Assert.True(null == value, "Should not have a value since we did not start copying there.");
else if (i == (aCopy.Length - 1))
Assert.True(null == value, "Should not have a value since the collection is shorter than the copy array..");
else
{
int indexInCollection = i - offsetIndex;
Assert.Equal(readOnlyCol[indexInCollection], aCopy[i]);
}
}
}
/// <summary>
/// Tests that:
/// ArgumentOutOfRangeException is thrown when the Index is >= collection.Count
/// or Index < 0.
/// ArgumentException when the destination array does not have enough space to
/// contain the source Collection.
/// ArgumentNullException when the destination array is null.
/// </summary>
[Fact]
public static void CopyToTest_Negative()
{
string[] anArray = new string[] { "one", "two", "three", "four" };
ReadOnlyObservableCollection<string> readOnlyCol =
new ReadOnlyObservableCollection<string>(new ObservableCollection<string>(anArray));
int[] iArrInvalidValues = new int[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, int.MinValue };
foreach (var index in iArrInvalidValues)
{
string[] aCopy = new string[anArray.Length];
AssertExtensions.Throws<ArgumentOutOfRangeException>("destinationIndex", "dstIndex", () => readOnlyCol.CopyTo(aCopy, index));
}
int[] iArrLargeValues = new int[] { anArray.Length, int.MaxValue, int.MaxValue / 2, int.MaxValue / 10 };
foreach (var index in iArrLargeValues)
{
string[] aCopy = new string[anArray.Length];
AssertExtensions.Throws<ArgumentException>("destinationArray", null, () => readOnlyCol.CopyTo(aCopy, index));
}
AssertExtensions.Throws<ArgumentNullException>("destinationArray", "dest", () => readOnlyCol.CopyTo(null, 1));
string[] copy = new string[anArray.Length - 1];
AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => readOnlyCol.CopyTo(copy, 0));
copy = new string[0];
AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => readOnlyCol.CopyTo(copy, 0));
}
/// <summary>
/// Tests that the index of an item can be retrieved when the item is
/// in the collection and -1 otherwise.
/// </summary>
[Fact]
public static void IndexOfTest()
{
string[] anArray = new string[] { "one", "two", "three", "four" };
ReadOnlyObservableCollection<string> readOnlyCollection =
new ReadOnlyObservableCollection<string>(new ObservableCollection<string>(anArray));
for (int i = 0; i < anArray.Length; ++i)
Assert.Equal(i, readOnlyCollection.IndexOf(anArray[i]));
Assert.Equal(-1, readOnlyCollection.IndexOf("seven"));
Assert.Equal(-1, readOnlyCollection.IndexOf(null));
// testing that the first occurrence is the index returned.
ObservableCollection<int> intCol = new ObservableCollection<int>();
for (int i = 0; i < 4; ++i)
intCol.Add(i % 2);
ReadOnlyObservableCollection<int> intReadOnlyCol = new ReadOnlyObservableCollection<int>(intCol);
Assert.Equal(0, intReadOnlyCol.IndexOf(0));
Assert.Equal(1, intReadOnlyCol.IndexOf(1));
IList colAsIList = (IList)intReadOnlyCol;
var index = colAsIList.IndexOf("stringObj");
Assert.Equal(-1, index);
}
/// <summary>
/// Tests that a ReadOnlyDictionary cannot be modified. That is, that
/// Add, Remove, Clear does not work.
/// </summary>
[Fact]
public static void CannotModifyDictionaryTests_Negative()
{
string[] anArray = new string[] { "one", "two", "three", "four", "five" };
ReadOnlyObservableCollection<string> readOnlyCol =
new ReadOnlyObservableCollection<string>(new ObservableCollection<string>(anArray));
IReadOnlyList_T_Test<string> helper = new IReadOnlyList_T_Test<string>();
IList<string> readOnlyColAsIList = readOnlyCol;
Assert.Throws<NotSupportedException>(() => readOnlyColAsIList.Add("seven"));
Assert.Throws<NotSupportedException>(() => readOnlyColAsIList.Insert(0, "nine"));
Assert.Throws<NotSupportedException>(() => readOnlyColAsIList.Remove("one"));
Assert.Throws<NotSupportedException>(() => readOnlyColAsIList.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => readOnlyColAsIList.Clear());
helper.VerifyReadOnlyCollection(readOnlyCol, anArray);
}
[Fact]
public static void DebuggerAttribute_Tests()
{
ReadOnlyObservableCollection<int> col = new ReadOnlyObservableCollection<int>(new ObservableCollection<int>(new[] {1, 2, 3, 4}));
DebuggerAttributes.ValidateDebuggerDisplayReferences(col);
DebuggerAttributeInfo info = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(col);
PropertyInfo itemProperty = info.Properties.Single(pr => pr.GetCustomAttribute<DebuggerBrowsableAttribute>().State == DebuggerBrowsableState.RootHidden);
int[] items = itemProperty.GetValue(info.Instance) as int[];
Assert.Equal(col, items);
}
[Fact]
public static void DebuggerAttribute_NullCollection_ThrowsArgumentNullException()
{
TargetInvocationException ex = Assert.Throws<TargetInvocationException>(() => DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(ReadOnlyObservableCollection<int>), null));
ArgumentNullException argumentNullException = Assert.IsType<ArgumentNullException>(ex.InnerException);
}
}
internal class IReadOnlyList_T_Test<T>
{
private readonly IReadOnlyList<T> _collection;
private readonly T[] _expectedItems;
/// <summary>
/// Initializes a new instance of the IReadOnlyList_T_Test.
/// </summary>
/// <param name="collection">The collection to run the tests on.</param>
/// <param name="expectedItems">The items expected to be in the collection.</param>
public IReadOnlyList_T_Test(IReadOnlyList<T> collection, T[] expectedItems)
{
_collection = collection;
_expectedItems = expectedItems;
}
public IReadOnlyList_T_Test()
{
}
/// <summary>
/// This verifies that the collection contains the expected items.
/// </summary>
public void InitialItems_Tests()
{
// Verify Count returns the expected value
Assert.Equal(_expectedItems.Length, _collection.Count);
// Verify the initial items in the collection
VerifyReadOnlyCollection(_collection, _expectedItems);
}
/// <summary>
/// Runs all of the valid tests on get Item.
/// </summary>
public void Item_get_Tests()
{
// Verify get_Item with valid item on Collection
Verify_get(_collection, _expectedItems);
}
/// <summary>
/// Runs all of the argument checking(invalid) tests on get Item.
/// </summary>
public void Item_get_Tests_Negative()
{
// Verify get_Item with index=Int32.MinValue
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => _collection[int.MinValue]);
// Verify that the collection was not mutated
VerifyReadOnlyCollection(_collection, _expectedItems);
// Verify get_Item with index=-1
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => _collection[-1]);
// Verify that the collection was not mutated
VerifyReadOnlyCollection(_collection, _expectedItems);
if (_expectedItems.Length == 0)
{
// Verify get_Item with index=0 on Empty collection
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => _collection[0]);
// Verify that the collection was not mutated
VerifyReadOnlyCollection(_collection, _expectedItems);
}
else
{
// Verify get_Item with index=Count on Empty collection
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => _collection[_expectedItems.Length]);
// Verify that the collection was not mutated
VerifyReadOnlyCollection(_collection, _expectedItems);
}
}
#region Helper Methods
/// <summary>
/// Verifies that the items in the collection match the expected items.
/// </summary>
internal void VerifyReadOnlyCollection(IReadOnlyList<T> collection, T[] items)
{
Verify_get(collection, items);
VerifyGenericEnumerator(collection, items);
VerifyEnumerator(collection, items);
}
/// <summary>
/// Verifies that you can get all items that should be in the collection.
/// </summary>
private void Verify_get(IReadOnlyList<T> collection, T[] items)
{
Assert.Equal(items.Length, collection.Count);
for (int i = 0; i < items.Length; i++)
{
int itemsIndex = i;
Assert.Equal(items[itemsIndex], collection[i]);
}
}
/// <summary>
/// Verifies that the generic enumerator retrieves the correct items.
/// </summary>
private void VerifyGenericEnumerator(IReadOnlyList<T> collection, T[] expectedItems)
{
IEnumerator<T> enumerator = collection.GetEnumerator();
int iterations = 0;
int expectedCount = expectedItems.Length;
// There is a sequential order to the collection, so we're testing for that.
while ((iterations < expectedCount) && enumerator.MoveNext())
{
T currentItem = enumerator.Current;
T tempItem;
// Verify we have not gotten more items then we expected
Assert.True(iterations < expectedCount,
"Err_9844awpa More items have been returned from the enumerator(" + iterations + " items) than are in the expectedElements(" + expectedCount + " items)");
// Verify Current returned the correct value
Assert.Equal(currentItem, expectedItems[iterations]);
// Verify Current always returns the same value every time it is called
for (int i = 0; i < 3; i++)
{
tempItem = enumerator.Current;
Assert.Equal(currentItem, tempItem);
}
iterations++;
}
Assert.Equal(expectedCount, iterations);
for (int i = 0; i < 3; i++)
{
Assert.False(enumerator.MoveNext(), "Err_2929ahiea Expected MoveNext to return false after" + iterations + " iterations");
}
enumerator.Dispose();
}
/// <summary>
/// Verifies that the non-generic enumerator retrieves the correct items.
/// </summary>
private void VerifyEnumerator(IReadOnlyList<T> collection, T[] expectedItems)
{
IEnumerator enumerator = collection.GetEnumerator();
int iterations = 0;
int expectedCount = expectedItems.Length;
// There is no sequential order to the collection, so we're testing that all the items
// in the readonlydictionary exist in the array.
bool[] itemsVisited = new bool[expectedCount];
bool itemFound;
while ((iterations < expectedCount) && enumerator.MoveNext())
{
object currentItem = enumerator.Current;
object tempItem;
// Verify we have not gotten more items then we expected
Assert.True(iterations < expectedCount,
"Err_9844awpa More items have been returned from the enumerator(" + iterations + " items) then are in the expectedElements(" + expectedCount + " items)");
// Verify Current returned the correct value
itemFound = false;
for (int i = 0; i < itemsVisited.Length; ++i)
{
if (!itemsVisited[i] && expectedItems[i].Equals(currentItem))
{
itemsVisited[i] = true;
itemFound = true;
break;
}
}
Assert.True(itemFound, "Err_1432pauy Current returned unexpected value=" + currentItem);
// Verify Current always returns the same value every time it is called
for (int i = 0; i < 3; i++)
{
tempItem = enumerator.Current;
Assert.Equal(currentItem, tempItem);
}
iterations++;
}
for (int i = 0; i < expectedCount; ++i)
{
Assert.True(itemsVisited[i], "Err_052848ahiedoi Expected Current to return true for item: " + expectedItems[i] + "index: " + i);
}
Assert.Equal(expectedCount, iterations);
for (int i = 0; i < 3; i++)
{
Assert.False(enumerator.MoveNext(), "Err_2929ahiea Expected MoveNext to return false after" + iterations + " iterations");
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
using Microsoft.Graphics.Canvas;
using Microsoft.Graphics.Canvas.Effects;
using Microsoft.Graphics.Canvas.UI;
using Microsoft.Graphics.Canvas.UI.Xaml;
using System;
using System.Collections.Generic;
using System.Numerics;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
namespace ExampleGallery
{
// Implements Conway's Game of Life using GPU image effects.
public sealed partial class GameOfLife : UserControl
{
const int simulationW = 128;
const int simulationH = 128;
// The simulation is updated by swapping back and forth between two surfaces,
// repeatedly drawing the contents of one onto the other using an image effect
// that implements the rules of the cellular automaton.
CanvasRenderTarget currentSurface, nextSurface;
static TimeSpan normalTargetElapsedTime = TimeSpan.FromSeconds(1.0 / 30.0);
static TimeSpan slowTargetElapsedTime = TimeSpan.FromSeconds(0.25);
public bool Slow
{
get
{
return canvas.TargetElapsedTime != normalTargetElapsedTime;
}
set
{
if (value)
canvas.TargetElapsedTime = slowTargetElapsedTime;
else
canvas.TargetElapsedTime = normalTargetElapsedTime;
}
}
public bool Paused
{
get
{
return canvas.Paused;
}
set
{
canvas.Paused = value;
}
}
bool isPointerDown;
int lastPointerX, lastPointerY;
struct IntPoint
{
public int X;
public int Y;
public IntPoint(int x, int y)
{
X = x;
Y = y;
}
}
List<IntPoint> hitPoints = new List<IntPoint>();
ConvolveMatrixEffect countNeighborsEffect;
DiscreteTransferEffect liveOrDieEffect;
LinearTransferEffect invertEffect;
Transform2DEffect transformEffect;
public GameOfLife()
{
this.InitializeComponent();
canvas.TargetElapsedTime = normalTargetElapsedTime;
}
void Canvas_CreateResources(CanvasAnimatedControl sender, CanvasCreateResourcesEventArgs args)
{
const float defaultDpi = 96;
currentSurface = new CanvasRenderTarget(sender, simulationW, simulationH, defaultDpi);
nextSurface = new CanvasRenderTarget(sender, simulationW, simulationH, defaultDpi);
CreateEffects();
// Initialize cells to random values.
RandomizeSimulation(null, null);
}
void Canvas_Update(ICanvasAnimatedControl sender, CanvasAnimatedUpdateEventArgs args)
{
// Use the current surface as input.
countNeighborsEffect.Source = currentSurface;
// Draw it onto the next surface, using an image effect that implements the Game of Life cellular automaton.
using (var ds = nextSurface.CreateDrawingSession())
{
ds.DrawImage(liveOrDieEffect);
}
// Swap the current and next surfaces.
var tmp = currentSurface;
currentSurface = nextSurface;
nextSurface = tmp;
}
void Canvas_Draw(ICanvasAnimatedControl sender, CanvasAnimatedDrawEventArgs args)
{
ApplyHitPoints();
// Display the current surface.
invertEffect.Source = currentSurface;
transformEffect.TransformMatrix = GetDisplayTransform(sender);
args.DrawingSession.DrawImage(transformEffect);
}
void CreateEffects()
{
// The Game of Life is a cellular automaton with very simple rules.
// Each cell (pixel) can be either alive (white) or dead (black).
// The state is updated by:
//
// - for each cell, count how many of its 8 neighbors are alive
// - if less than two, the cell dies from loneliness
// - if exactly two, the cell keeps its current state
// - if exactly three, the cell become alive
// - if more than three, the cell dies from overcrowding
// Step 1: use a convolve matrix to count how many neighbors are alive. This filter
// also includes the state of the current cell, but with a lower weighting. The result
// is an arithmetic encoding where (value / 2) indicates how many neighbors are alive,
// and (value % 2) is the state of the cell itself. This is divided by 18 to make it
// fit within 0-1 color range.
countNeighborsEffect = new ConvolveMatrixEffect
{
KernelMatrix = new float[]
{
2, 2, 2,
2, 1, 2,
2, 2, 2
},
Divisor = 18,
BorderMode = EffectBorderMode.Hard,
};
// Step 2: use a color transfer table to map the different states produced by the
// convolve matrix to whether the cell should live or die. Each pair of entries in
// this table corresponds to a certain number of live neighbors. The first of the
// pair is the result if the current cell is dead, or the second if it is alive.
float[] transferTable =
{
0, 0, // 0 live neighbors -> dead cell
0, 0, // 1 live neighbors -> dead cell
0, 1, // 2 live neighbors -> cell keeps its current state
1, 1, // 3 live neighbors -> live cell
0, 0, // 4 live neighbors -> dead cell
0, 0, // 5 live neighbors -> dead cell
0, 0, // 6 live neighbors -> dead cell
0, 0, // 7 live neighbors -> dead cell
0, 0, // 8 live neighbors -> dead cell
};
liveOrDieEffect = new DiscreteTransferEffect
{
Source = countNeighborsEffect,
RedTable = transferTable,
GreenTable = transferTable,
BlueTable = transferTable,
};
// Step 3: the algorithm is implemented in terms of white = live,
// black = dead, but we invert these colors before displaying the
// result, just 'cause I think it looks better that way.
invertEffect = new LinearTransferEffect
{
RedSlope = -1,
RedOffset = 1,
GreenSlope = -1,
GreenOffset = 1,
BlueSlope = -1,
BlueOffset = 1,
};
// Step 4: insert our own DPI compensation effect to stop the system trying to
// automatically convert DPI for us. The Game of Life simulation always works
// in pixels (96 DPI) regardless of display DPI. Normally, the system would
// handle this mismatch automatically and scale the image up as needed to fit
// higher DPI displays. We don't want that behavior here, because it would use
// a linear filter while we want nearest neighbor. So we insert a no-op DPI
// converter of our own. This overrides the default adjustment by telling the
// system the source image is already the same DPI as the destination canvas
// (even though it really isn't). We'll handle any necessary scaling later
// ourselves, using Transform2DEffect to control the interpolation mode.
var dpiCompensationEffect = new DpiCompensationEffect
{
Source = invertEffect,
SourceDpi = new Vector2(canvas.Dpi),
};
// Step 5: a transform matrix scales up the simulation rendertarget and moves
// it to the right part of the screen. This uses nearest neighbor filtering
// to avoid unwanted blurring of the cell shapes.
transformEffect = new Transform2DEffect
{
Source = dpiCompensationEffect,
InterpolationMode = CanvasImageInterpolation.NearestNeighbor,
};
}
// Initializes the simulation to a random state.
void RandomizeSimulation(object sender, RoutedEventArgs e)
{
var action = canvas.RunOnGameLoopThreadAsync(() =>
{
Random random = new Random();
var colors = new Color[simulationW * simulationH];
for (int i = 0; i < colors.Length; i++)
{
colors[i] = (random.NextDouble() < 0.25) ? Colors.White : Colors.Black;
}
currentSurface.SetPixelColors(colors);
canvas.Invalidate();
});
}
// Clears the simulation state.
void ClearSimulation(object sender, RoutedEventArgs e)
{
var action = canvas.RunOnGameLoopThreadAsync(() =>
{
using (var ds = currentSurface.CreateDrawingSession())
{
ds.Clear(Colors.Black);
}
canvas.Invalidate();
});
}
void Canvas_PointerPressed(object sender, PointerRoutedEventArgs e)
{
lock (hitPoints)
{
isPointerDown = true;
lastPointerX = lastPointerY = int.MaxValue;
ProcessPointerInput(e);
}
}
void Canvas_PointerReleased(object sender, PointerRoutedEventArgs e)
{
lock (hitPoints)
{
isPointerDown = false;
}
}
void Canvas_PointerMoved(object sender, PointerRoutedEventArgs e)
{
lock (hitPoints)
{
ProcessPointerInput(e);
}
}
// Toggles the color of cells when they are clicked on.
private void ProcessPointerInput(PointerRoutedEventArgs e)
{
if (!isPointerDown)
return;
// Invert the display transform, to convert pointer positions into simulation rendertarget space.
Matrix3x2 transform;
Matrix3x2.Invert(GetDisplayTransform(canvas), out transform);
foreach (var point in e.GetIntermediatePoints(canvas))
{
if (!point.IsInContact)
continue;
var pos = Vector2.Transform(point.Position.ToVector2(), transform);
var x = canvas.ConvertDipsToPixels(pos.X, CanvasDpiRounding.Floor);
var y = canvas.ConvertDipsToPixels(pos.Y, CanvasDpiRounding.Floor);
// If the point is within the bounds of the rendertarget, and not the same as the last point...
if (x >= 0 &&
y >= 0 &&
x < simulationW &&
y < simulationH &&
((x != lastPointerX || y != lastPointerY)))
{
// We avoid manipulating GPU resources from inside an input event handler
// (since we'd need to handle device lost and possible concurrent running with CreateResources).
// Instead, we collect up a list of points and process them from the Draw handler.
hitPoints.Add(new IntPoint(x, y));
lastPointerX = x;
lastPointerY = y;
}
}
canvas.Invalidate();
}
void ApplyHitPoints()
{
lock (hitPoints)
{
foreach (var point in hitPoints)
{
var x = point.X;
var y = point.Y;
// Read the current color.
var cellColor = currentSurface.GetPixelColors(x, y, 1, 1);
// Toggle the value.
cellColor[0] = cellColor[0].R > 0 ? Colors.Black : Colors.White;
// Set the new color.
currentSurface.SetPixelColors(cellColor, x, y, 1, 1);
}
hitPoints.Clear();
}
}
static Matrix3x2 GetDisplayTransform(ICanvasAnimatedControl canvas)
{
var outputSize = canvas.Size.ToVector2();
var sourceSize = new Vector2(canvas.ConvertPixelsToDips(simulationW), canvas.ConvertPixelsToDips(simulationH));
return Utils.GetDisplayTransform(outputSize, sourceSize);
}
private void control_Unloaded(object sender, RoutedEventArgs e)
{
// Explicitly remove references to allow the Win2D controls to get garbage collected
canvas.RemoveFromVisualTree();
canvas = null;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Reflection;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using PermissionMask = OpenSim.Framework.PermissionMask;
namespace OpenSim.Region.CoreModules.Agent.AssetTransaction
{
public class AssetXferUploader
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Upload state.
/// </summary>
/// <remarks>
/// New -> Uploading -> Complete
/// </remarks>
private enum UploadState
{
New,
Uploading,
Complete
}
/// <summary>
/// Reference to the object that holds this uploader. Used to remove ourselves from it's list if we
/// are performing a delayed update.
/// </summary>
AgentAssetTransactions m_transactions;
private UploadState m_uploadState = UploadState.New;
private AssetBase m_asset;
private UUID InventFolder = UUID.Zero;
private sbyte invType = 0;
private bool m_createItem;
private uint m_createItemCallback;
private bool m_updateItem;
private InventoryItemBase m_updateItemData;
private bool m_updateTaskItem;
private TaskInventoryItem m_updateTaskItemData;
private string m_description = String.Empty;
private bool m_dumpAssetToFile;
private string m_name = String.Empty;
// private bool m_storeLocal;
private uint nextPerm = 0;
private IClientAPI ourClient;
private UUID m_transactionID;
private sbyte type = 0;
private byte wearableType = 0;
public ulong XferID;
private Scene m_Scene;
/// <summary>
/// AssetXferUploader constructor
/// </summary>
/// <param name='transactions'>/param>
/// <param name='scene'></param>
/// <param name='transactionID'></param>
/// <param name='dumpAssetToFile'>
/// If true then when the asset is uploaded it is dumped to a file with the format
/// String.Format("{6}_{7}_{0:d2}{1:d2}{2:d2}_{3:d2}{4:d2}{5:d2}.dat",
/// now.Year, now.Month, now.Day, now.Hour, now.Minute,
/// now.Second, m_asset.Name, m_asset.Type);
/// for debugging purposes.
/// </param>
public AssetXferUploader(
AgentAssetTransactions transactions, Scene scene, UUID transactionID, bool dumpAssetToFile)
{
m_asset = new AssetBase();
m_transactions = transactions;
m_transactionID = transactionID;
m_Scene = scene;
m_dumpAssetToFile = dumpAssetToFile;
}
/// <summary>
/// Process transfer data received from the client.
/// </summary>
/// <param name="xferID"></param>
/// <param name="packetID"></param>
/// <param name="data"></param>
/// <returns>True if the transfer is complete, false otherwise or if the xferID was not valid</returns>
public bool HandleXferPacket(ulong xferID, uint packetID, byte[] data)
{
// m_log.DebugFormat(
// "[ASSET XFER UPLOADER]: Received packet {0} for xfer {1} (data length {2})",
// packetID, xferID, data.Length);
if (XferID == xferID)
{
if (m_asset.Data.Length > 1)
{
byte[] destinationArray = new byte[m_asset.Data.Length + data.Length];
Array.Copy(m_asset.Data, 0, destinationArray, 0, m_asset.Data.Length);
Array.Copy(data, 0, destinationArray, m_asset.Data.Length, data.Length);
m_asset.Data = destinationArray;
}
else
{
byte[] buffer2 = new byte[data.Length - 4];
Array.Copy(data, 4, buffer2, 0, data.Length - 4);
m_asset.Data = buffer2;
}
ourClient.SendConfirmXfer(xferID, packetID);
if ((packetID & 0x80000000) != 0)
{
SendCompleteMessage();
return true;
}
}
return false;
}
/// <summary>
/// Start asset transfer from the client
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="assetID"></param>
/// <param name="transaction"></param>
/// <param name="type"></param>
/// <param name="data">
/// Optional data. If present then the asset is created immediately with this data
/// rather than requesting an upload from the client. The data must be longer than 2 bytes.
/// </param>
/// <param name="storeLocal"></param>
/// <param name="tempFile"></param>
public void StartUpload(
IClientAPI remoteClient, UUID assetID, UUID transaction, sbyte type, byte[] data, bool storeLocal,
bool tempFile)
{
// m_log.DebugFormat(
// "[ASSET XFER UPLOADER]: Initialised xfer from {0}, asset {1}, transaction {2}, type {3}, storeLocal {4}, tempFile {5}, already received data length {6}",
// remoteClient.Name, assetID, transaction, type, storeLocal, tempFile, data.Length);
lock (this)
{
if (m_uploadState != UploadState.New)
{
m_log.WarnFormat(
"[ASSET XFER UPLOADER]: Tried to start upload of asset {0}, transaction {1} for {2} but this is already in state {3}. Aborting.",
assetID, transaction, remoteClient.Name, m_uploadState);
return;
}
m_uploadState = UploadState.Uploading;
}
ourClient = remoteClient;
m_asset.FullID = assetID;
m_asset.Type = type;
m_asset.CreatorID = remoteClient.AgentId.ToString();
m_asset.Data = data;
m_asset.Local = storeLocal;
m_asset.Temporary = tempFile;
// m_storeLocal = storeLocal;
if (m_asset.Data.Length > 2)
{
SendCompleteMessage();
}
else
{
RequestStartXfer();
}
}
protected void RequestStartXfer()
{
XferID = Util.GetNextXferID();
// m_log.DebugFormat(
// "[ASSET XFER UPLOADER]: Requesting Xfer of asset {0}, type {1}, transfer id {2} from {3}",
// m_asset.FullID, m_asset.Type, XferID, ourClient.Name);
ourClient.SendXferRequest(XferID, m_asset.Type, m_asset.FullID, 0, new byte[0]);
}
protected void SendCompleteMessage()
{
// We must lock in order to avoid a race with a separate thread dealing with an inventory item or create
// message from other client UDP.
lock (this)
{
m_uploadState = UploadState.Complete;
ourClient.SendAssetUploadCompleteMessage(m_asset.Type, true, m_asset.FullID);
if (m_createItem)
{
CompleteCreateItem(m_createItemCallback);
}
else if (m_updateItem)
{
CompleteItemUpdate(m_updateItemData);
}
else if (m_updateTaskItem)
{
CompleteTaskItemUpdate(m_updateTaskItemData);
}
// else if (m_storeLocal)
// {
// m_Scene.AssetService.Store(m_asset);
// }
}
m_log.DebugFormat(
"[ASSET XFER UPLOADER]: Uploaded asset {0} for transaction {1}",
m_asset.FullID, m_transactionID);
if (m_dumpAssetToFile)
{
DateTime now = DateTime.Now;
string filename =
String.Format("{6}_{7}_{0:d2}{1:d2}{2:d2}_{3:d2}{4:d2}{5:d2}.dat",
now.Year, now.Month, now.Day, now.Hour, now.Minute,
now.Second, m_asset.Name, m_asset.Type);
SaveAssetToFile(filename, m_asset.Data);
}
}
private void SaveAssetToFile(string filename, byte[] data)
{
string assetPath = "UserAssets";
if (!Directory.Exists(assetPath))
{
Directory.CreateDirectory(assetPath);
}
FileStream fs = File.Create(Path.Combine(assetPath, filename));
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(data);
bw.Close();
fs.Close();
}
public void RequestCreateInventoryItem(IClientAPI remoteClient,
UUID folderID, uint callbackID,
string description, string name, sbyte invType,
sbyte type, byte wearableType, uint nextOwnerMask)
{
InventFolder = folderID;
m_name = name;
m_description = description;
this.type = type;
this.invType = invType;
this.wearableType = wearableType;
nextPerm = nextOwnerMask;
m_asset.Name = name;
m_asset.Description = description;
m_asset.Type = type;
// We must lock to avoid a race with a separate thread uploading the asset.
lock (this)
{
if (m_uploadState == UploadState.Complete)
{
CompleteCreateItem(callbackID);
}
else
{
m_createItem = true; //set flag so the inventory item is created when upload is complete
m_createItemCallback = callbackID;
}
}
}
public void RequestUpdateInventoryItem(IClientAPI remoteClient, InventoryItemBase item)
{
// We must lock to avoid a race with a separate thread uploading the asset.
lock (this)
{
m_asset.Name = item.Name;
m_asset.Description = item.Description;
m_asset.Type = (sbyte)item.AssetType;
// We must always store the item at this point even if the asset hasn't finished uploading, in order
// to avoid a race condition when the appearance module retrieves the item to set the asset id in
// the AvatarAppearance structure.
item.AssetID = m_asset.FullID;
if (item.AssetID != UUID.Zero)
m_Scene.InventoryService.UpdateItem(item);
if (m_uploadState == UploadState.Complete)
{
CompleteItemUpdate(item);
}
else
{
// m_log.DebugFormat(
// "[ASSET XFER UPLOADER]: Holding update inventory item request {0} for {1} pending completion of asset xfer for transaction {2}",
// item.Name, remoteClient.Name, transactionID);
m_updateItem = true;
m_updateItemData = item;
}
}
}
public void RequestUpdateTaskInventoryItem(IClientAPI remoteClient, TaskInventoryItem taskItem)
{
// We must lock to avoid a race with a separate thread uploading the asset.
lock (this)
{
m_asset.Name = taskItem.Name;
m_asset.Description = taskItem.Description;
m_asset.Type = (sbyte)taskItem.Type;
taskItem.AssetID = m_asset.FullID;
if (m_uploadState == UploadState.Complete)
{
CompleteTaskItemUpdate(taskItem);
}
else
{
m_updateTaskItem = true;
m_updateTaskItemData = taskItem;
}
}
}
/// <summary>
/// Store the asset for the given item when it has been uploaded.
/// </summary>
/// <param name="item"></param>
private void CompleteItemUpdate(InventoryItemBase item)
{
// m_log.DebugFormat(
// "[ASSET XFER UPLOADER]: Storing asset {0} for earlier item update for {1} for {2}",
// m_asset.FullID, item.Name, ourClient.Name);
m_Scene.AssetService.Store(m_asset);
m_transactions.RemoveXferUploader(m_transactionID);
}
/// <summary>
/// Store the asset for the given task item when it has been uploaded.
/// </summary>
/// <param name="taskItem"></param>
private void CompleteTaskItemUpdate(TaskInventoryItem taskItem)
{
// m_log.DebugFormat(
// "[ASSET XFER UPLOADER]: Storing asset {0} for earlier task item update for {1} for {2}",
// m_asset.FullID, taskItem.Name, ourClient.Name);
m_Scene.AssetService.Store(m_asset);
m_transactions.RemoveXferUploader(m_transactionID);
}
private void CompleteCreateItem(uint callbackID)
{
m_Scene.AssetService.Store(m_asset);
InventoryItemBase item = new InventoryItemBase();
item.Owner = ourClient.AgentId;
item.CreatorId = ourClient.AgentId.ToString();
item.ID = UUID.Random();
item.AssetID = m_asset.FullID;
item.Description = m_description;
item.Name = m_name;
item.AssetType = type;
item.InvType = invType;
item.Folder = InventFolder;
item.BasePermissions = (uint)(PermissionMask.All | PermissionMask.Export);
item.CurrentPermissions = item.BasePermissions;
item.GroupPermissions=0;
item.EveryOnePermissions=0;
item.NextPermissions = nextPerm;
item.Flags = (uint) wearableType;
item.CreationDate = Util.UnixTimeSinceEpoch();
if (m_Scene.AddInventoryItem(item))
ourClient.SendInventoryItemCreateUpdate(item, callbackID);
else
ourClient.SendAlertMessage("Unable to create inventory item");
m_transactions.RemoveXferUploader(m_transactionID);
}
}
}
| |
//
// ComboBoxBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using Gtk;
#if XWT_GTK3
using TreeModel = Gtk.ITreeModel;
#endif
namespace Xwt.GtkBackend
{
public class ComboBoxBackend: WidgetBackend, IComboBoxBackend, ICellRendererTarget
{
public ComboBoxBackend ()
{
}
public override void Initialize ()
{
//NeedsEventBox = false; // TODO: needs fix: no events with or without event box
Widget = (Gtk.ComboBox) CreateWidget ();
if (Widget.Cells.Length == 0) {
var cr = new Gtk.CellRendererText ();
Widget.PackStart (cr, false);
Widget.AddAttribute (cr, "text", 0);
}
Widget.Show ();
Widget.RowSeparatorFunc = IsRowSeparator;
}
protected virtual Gtk.Widget CreateWidget ()
{
return new Gtk.ComboBox ();
}
protected new Gtk.ComboBox Widget {
get { return (Gtk.ComboBox)base.Widget; }
set { base.Widget = value; }
}
protected new IComboBoxEventSink EventSink {
get { return (IComboBoxEventSink)base.EventSink; }
}
bool IsRowSeparator (TreeModel model, Gtk.TreeIter iter)
{
Gtk.TreePath path = model.GetPath (iter);
bool res = false;
ApplicationContext.InvokeUserCode (delegate {
res = EventSink.RowIsSeparator (path.Indices[0]);
});
return res;
}
public override void EnableEvent (object eventId)
{
base.EnableEvent (eventId);
if (eventId is ComboBoxEvent) {
if ((ComboBoxEvent)eventId == ComboBoxEvent.SelectionChanged)
Widget.Changed += HandleChanged;
}
}
public override void DisableEvent (object eventId)
{
base.DisableEvent (eventId);
if (eventId is ComboBoxEvent) {
if ((ComboBoxEvent)eventId == ComboBoxEvent.SelectionChanged)
Widget.Changed -= HandleChanged;
}
}
void HandleChanged (object sender, EventArgs e)
{
ApplicationContext.InvokeUserCode (EventSink.OnSelectionChanged);
}
#region IComboBoxBackend implementation
public void SetViews (CellViewCollection views)
{
Widget.Clear ();
foreach (var v in views)
CellUtil.CreateCellRenderer (ApplicationContext, Frontend, this, null, v);
}
public void SetSource (IListDataSource source, IBackend sourceBackend)
{
ListStoreBackend b = sourceBackend as ListStoreBackend;
if (b == null) {
CustomListModel model = new CustomListModel (source, Widget);
Widget.Model = model.Store;
} else
Widget.Model = b.Store;
OnSourceSet ();
}
public int SelectedRow {
get {
return Widget.Active;
}
set {
Widget.Active = value;
}
}
#endregion
protected virtual void OnSourceSet () { }
#region ICellRendererTarget implementation
public void PackStart (object target, Gtk.CellRenderer cr, bool expand)
{
Widget.PackStart (cr, expand);
}
public void PackEnd (object target, Gtk.CellRenderer cr, bool expand)
{
Widget.PackEnd (cr, expand);
}
public void AddAttribute (object target, Gtk.CellRenderer cr, string field, int column)
{
Widget.AddAttribute (cr, field, column);
}
public void SetCellDataFunc (object target, Gtk.CellRenderer cr, Gtk.CellLayoutDataFunc dataFunc)
{
Widget.SetCellDataFunc (cr, dataFunc);
}
Rectangle ICellRendererTarget.GetCellBounds (object target, Gtk.CellRenderer cr, Gtk.TreeIter iter)
{
return new Rectangle ();
}
Rectangle ICellRendererTarget.GetCellBackgroundBounds (object target, Gtk.CellRenderer cr, Gtk.TreeIter iter)
{
return new Rectangle ();
}
public virtual void SetCurrentEventRow (string path)
{
}
Gtk.Widget ICellRendererTarget.EventRootWidget {
get { return Widget; }
}
TreeModel ICellRendererTarget.Model {
get { return Widget.Model; }
}
Gtk.TreeIter ICellRendererTarget.PressedIter { get; set; }
CellViewBackend ICellRendererTarget.PressedCell { get; set; }
public bool GetCellPosition (Gtk.CellRenderer r, int ex, int ey, out int cx, out int cy, out Gtk.TreeIter it)
{
cx = cy = 0;
it = Gtk.TreeIter.Zero;
return false;
}
public void QueueDraw (object target, Gtk.TreeIter iter)
{
}
public void QueueResize (object target, Gtk.TreeIter iter)
{
}
bool disposed;
protected override void Dispose(bool disposing)
{
if (disposing && !disposed)
Widget.RowSeparatorFunc = null;
disposed = true;
base.Dispose(disposing);
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="WmlRadioButtonAdapter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
#if WMLSUPPORT
namespace System.Web.UI.WebControls.Adapters {
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Globalization;
using System.Web;
using System.Web.UI;
using System.Web.UI.Adapters;
using System.Web.Util;
public class WmlRadioButtonAdapter : WmlCheckBoxAdapter, IPostBackDataHandler {
private const String _groupPrefix = "__rb_";
protected new RadioButton Control {
get {
return (RadioButton)base.Control;
}
}
protected string GroupFormVariable {
get {
return _groupPrefix + Control.UniqueGroupName;
}
}
private void DetermineGroup(RadioButton r) {
if (RadioButtonGroups[r.UniqueGroupName] == null) {
RadioButtonGroups[r.UniqueGroupName] = RenderAsGroup(r);
}
}
private RadioButtonGroup GetGroupByName(string groupName) {
Debug.Assert(RadioButtonGroups.Contains(groupName), "Attemping to get group name without procesing group");
return RadioButtonGroups[groupName] as RadioButtonGroup;
}
// Returns a textual representation of a textbox.
protected override string InputElementText {
get {
return Control.Checked ? RadioButtonAdapter.AltSelectedText : RadioButtonAdapter.AltUnselectedText;
}
}
private bool IsWhiteSpace(string s) {
for (int i = 0; i < s.Length; i++) {
if (!Char.IsWhiteSpace(s, i)) return false;
}
return true;
}
private IDictionary RadioButtonGroups {
get {
if (Control.Page != null && Control.Page.Items[this.GetType()] == null) {
Control.Page.Items[this.GetType()] = new HybridDictionary();
}
return (HybridDictionary)Control.Page.Items[this.GetType()];
}
}
// Renders the control.
protected internal override void Render(HtmlTextWriter markupWriter) {
WmlTextWriter writer = (WmlTextWriter)markupWriter;
DetermineGroup(Control);
RadioButtonGroup group = GetGroupByName(Control.UniqueGroupName);
if (group != null) {
if (!group.RegisteredGroup) {
// GroupFormVariable is passed as the name & value becuase it is both the key
// for the postback data, and the WML client side var used to
// select an item in the list.
((WmlPageAdapter)PageAdapter).RegisterPostField(writer, GroupFormVariable, GroupFormVariable, true /*dynamic field*/, false /*random*/);
group.RegisteredGroup = true;
}
if (group.RenderAsGroup) {
// Render opening select if not already opened
if (!group.RenderedSelect) {
if (group.SelectedButton != null) {
((WmlPageAdapter)PageAdapter).AddFormVariable(writer, GroupFormVariable, group.SelectedButton, false /*random*/);
}
writer.WriteBeginSelect(GroupFormVariable, group.SelectedButton, null /*iname */,
null /*ivalue*/, Control.ToolTip, false /*multiple */);
if (!writer.AnalyzeMode) {
group.RenderedSelect = true;
}
}
// Render option
// We don't do autopostback if the radio button has been selected.
// This is to make it consistent that it only posts back if its
// state has been changed. Also, it avoids the problem of missing
// validation since the data changed event would not be fired if the
// selected radio button was posting back.
if (Control.AutoPostBack && !Control.Checked) {
((WmlPageAdapter)PageAdapter).RenderSelectOptionAsAutoPostBack(writer, Control.Text, Control.UniqueID);
}
else {
((WmlPageAdapter)PageAdapter).RenderSelectOption(writer, Control.Text, Control.UniqueID);
}
// Close, if list is finished
if (!writer.AnalyzeMode && --group.ButtonsInGroup == 0) {
writer.WriteEndSelect();
}
}
// must render as autopostback, radio buttons not in consecutive group.
else {
if (!Control.Enabled) {
RenderDisabled(writer);
return;
}
string iname = Control.Checked ? Control.ClientID : null;
string ivalue = Control.Checked ? "1" : null;
if (ivalue != null) {
((WmlPageAdapter)PageAdapter).AddFormVariable(writer, iname, ivalue, false /*random*/);
}
writer.WriteBeginSelect(null, null, iname, ivalue, Control.ToolTip, true /*multiple*/);
if (!Control.Checked) {
((WmlPageAdapter)PageAdapter).RenderSelectOptionAsAutoPostBack(writer, Control.Text, GroupFormVariable, Control.UniqueID);
}
else {
((WmlPageAdapter)PageAdapter).RenderSelectOption(writer, Control.Text, Control.UniqueID);
}
writer.WriteEndSelect();
}
}
}
// RenderAsGroup returns a RadioButtonGroup object if the group should be
// rendered in a single <select> statement, or null if autopostback should
// be enabled.
// UNDONE: Check more general case when radiobuttons do not all share the same parent
private RadioButtonGroup RenderAsGroup(RadioButton r) {
bool startedSequence = false;
bool finishedSequence = false;
RadioButtonGroup group = new RadioButtonGroup();
//TODO : Check all controls on page
foreach (Control c in r.Parent.Controls) {
RadioButton radioSibling = c as RadioButton;
LiteralControl literalSibling = c as LiteralControl;
if (radioSibling != null && radioSibling.UniqueGroupName == r.UniqueGroupName) {
startedSequence = true;
group.ButtonsInGroup++;
if (radioSibling.Checked == true) {
group.SelectedButton = radioSibling.UniqueID;
}
if (finishedSequence || !radioSibling.Enabled) {
group.ButtonsInGroup = -1; // can't be rendered in a group
break;
}
}
else if (startedSequence && (literalSibling == null || !IsWhiteSpace(literalSibling.Text))) {
finishedSequence = true;
}
}
return group;
}
/// <internalonly/>
// Implements IPostBackDataHandler.LoadPostData.
protected override bool LoadPostData(String key, NameValueCollection data) {
bool dataChanged = false;
string selButtonID = data[GroupFormVariable];
if (!String.IsNullOrEmpty(selButtonID)) {
// Check if this radio button is now checked
if (StringUtil.EqualsIgnoreCase(selButtonID, Control.UniqueID)) {
if (Control.Checked == false) {
Control.Checked = true;
dataChanged = true;
}
}
else {
// Don't need to check if radiobutton was
// previously checked. We only raise an event
// for the radiobutton that is selected.
// This is how a normal RadioButton behaves.
Control.Checked = false;
}
}
return dataChanged;
}
/// <internalonly/>
// Implements IPostBackDataHandler.RaisePostDataChangedEvent()
protected override void RaisePostDataChangedEvent() {
((IPostBackDataHandler)Control).RaisePostDataChangedEvent();
}
}
internal class RadioButtonGroup {
public int ButtonsInGroup;
public bool RenderedSelect;
public bool RegisteredGroup;
public String SelectedButton;
public bool RenderAsGroup {
get {
if (ButtonsInGroup < 0) {
return false;
}
return true;
}
}
}
}
#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 Xunit;
namespace System.Collections.Tests
{
public class ArrayList_BinarySearchTests : IComparer
{
#region "Test Data - Keep the data close to tests so it can vary independently from other tests"
static string[] strHeroes =
{
"Aquaman",
"Atom",
"Batman",
"Black Canary",
"Captain America",
"Captain Atom",
"Catwoman",
"Cyborg",
"Flash",
"Green Arrow",
"Green Lantern",
"Hawkman",
"Huntress",
"Ironman",
"Nightwing",
"Robin",
"SpiderMan",
"Steel",
"Superman",
"Thor",
"Wildcat",
"Wonder Woman",
};
static string[] strFindHeroes =
{
"Batman",
"Superman",
"SpiderMan",
"Wonder Woman",
"Green Lantern",
"Flash",
"Steel"
};
#endregion
[Fact]
public void TestStandardArrayList()
{
//
// Construct array list.
//
ArrayList list = new ArrayList();
// Add items to the lists.
for (int ii = 0; ii < strHeroes.Length; ++ii)
list.Add(strHeroes[ii]);
// Verify items added to list.
Assert.Equal(strHeroes.Length, list.Count);
//
// [] Use BinarySearch to find selected items.
//
// Search and verify selected items.
for (int ii = 0; ii < strFindHeroes.Length; ++ii)
{
// Locate item.
int ndx = list.BinarySearch(strFindHeroes[ii]);
Assert.True(ndx >= 0);
// Verify item.
Assert.Equal(0, strHeroes[ndx].CompareTo(strFindHeroes[ii]));
}
// Return Value;
// The zero-based index of the value in the sorted ArrayList, if value is found; otherwise, a negative number,
// which is the bitwise complement of the index of the next element.
list = new ArrayList();
for (int i = 0; i < 100; i++)
list.Add(i);
list.Sort();
Assert.Equal(100, ~list.BinarySearch(150));
//[]null - should return -1
Assert.Equal(-1, list.BinarySearch(null));
//[]we can add null as a value and then search it!!!
list.Add(null);
list.Sort();
Assert.Equal(0, list.BinarySearch(null));
//[]duplicate values, always return the first one
list = new ArrayList();
for (int i = 0; i < 100; i++)
list.Add(5);
list.Sort();
//remember this is BinarySeearch
Assert.Equal(49, list.BinarySearch(5));
}
[Fact]
public void TestArrayListWrappers()
{
//
// Construct array list.
//
ArrayList arrList = new ArrayList();
// Add items to the lists.
for (int ii = 0; ii < strHeroes.Length; ++ii)
{
arrList.Add(strHeroes[ii]);
}
// Verify items added to list.
Assert.Equal(strHeroes.Length, arrList.Count);
//Adapter, GetRange, Synchronized, ReadOnly returns a slightly different version of
//BinarySearch, Following variable cotains each one of these types of array lists
ArrayList[] arrayListTypes = {
arrList,
ArrayList.Adapter(arrList),
ArrayList.FixedSize(arrList),
arrList.GetRange(0, arrList.Count),
ArrayList.ReadOnly(arrList),
ArrayList.Synchronized(arrList)};
int ndx = 0;
foreach (ArrayList arrayListType in arrayListTypes)
{
arrList = arrayListType;
//
// [] Use BinarySearch to find selected items.
//
// Search and verify selected items.
for (int ii = 0; ii < strFindHeroes.Length; ++ii)
{
// Locate item.
ndx = arrList.BinarySearch(0, arrList.Count, strFindHeroes[ii], this);
Assert.True(ndx >= 0);
// Verify item.
Assert.Equal(0, strHeroes[ndx].CompareTo(strFindHeroes[ii]));
}
//
// [] Locate item in list using null comparer.
//
ndx = arrList.BinarySearch(0, arrList.Count, "Batman", null);
Assert.Equal(2, ndx);
//
// [] Locate insertion index of new list item.
//
// Append the list.
ndx = arrList.BinarySearch(0, arrList.Count, "Batgirl", this);
Assert.Equal(2, ~ndx);
//
// [] Bogus Arguments
//
Assert.Throws<ArgumentOutOfRangeException>(() => arrList.BinarySearch(-100, 1000, arrList.Count, this));
Assert.Throws<ArgumentOutOfRangeException>(() => arrList.BinarySearch(-100, 1000, "Batman", this));
Assert.Throws<ArgumentOutOfRangeException>(() => arrList.BinarySearch(-1, arrList.Count, "Batman", this));
Assert.Throws<ArgumentOutOfRangeException>(() => arrList.BinarySearch(0, -1, "Batman", this));
Assert.Throws<ArgumentException>(() => arrList.BinarySearch(1, arrList.Count, "Batman", this));
Assert.Throws<ArgumentException>(() => arrList.BinarySearch(3, arrList.Count - 2, "Batman", this));
}
}
[Fact]
public void TestCustomComparer()
{
ArrayList list = null;
list = new ArrayList();
// Add items to the lists.
for (int ii = 0; ii < strHeroes.Length; ++ii)
list.Add(strHeroes[ii]);
// Verify items added to list.
Assert.Equal(strHeroes.Length, list.Count);
//
// [] Use BinarySearch to find selected items.
//
// Search and verify selected items.
for (int ii = 0; ii < strFindHeroes.Length; ++ii)
{
// Locate item.
int ndx = list.BinarySearch(strFindHeroes[ii], new ArrayList_BinarySearchTests());
Assert.True(ndx < strHeroes.Length);
// Verify item.
Assert.Equal(0, strHeroes[ndx].CompareTo(strFindHeroes[ii]));
}
//Return Value;
//The zero-based index of the value in the sorted ArrayList, if value is found; otherwise, a negative number, which is the
//bitwise complement of the index of the next element.
list = new ArrayList();
for (int i = 0; i < 100; i++)
list.Add(i);
list.Sort();
Assert.Equal(100, ~list.BinarySearch(150, new ArrayList_BinarySearchTests()));
//[]null - should return -1
Assert.Equal(-1, list.BinarySearch(null, new ArrayList_BinarySearchTests()));
//[]we can add null as a value and then search it!!!
list.Add(null);
list.Sort();
Assert.Equal(0, list.BinarySearch(null, new CompareWithNullEnabled()));
//[]duplicate values, always return the first one
list = new ArrayList();
for (int i = 0; i < 100; i++)
list.Add(5);
list.Sort();
//remember this is BinarySeearch
Assert.Equal(49, list.BinarySearch(5, new ArrayList_BinarySearchTests()));
//[]IC as null
list = new ArrayList();
for (int i = 0; i < 100; i++)
list.Add(5);
list.Sort();
//remember this is BinarySeearch
Assert.Equal(49, list.BinarySearch(5, null));
}
public virtual int Compare(object x, object y)
{
if (x is string)
{
return ((string)x).CompareTo((string)y);
}
var comparer = new Comparer(System.Globalization.CultureInfo.InvariantCulture);
if (x is int || y is string)
{
return comparer.Compare(x, y);
}
return -1;
}
}
class CompareWithNullEnabled : IComparer
{
public int Compare(Object a, Object b)
{
if (a == b) return 0;
if (a == null) return -1;
if (b == null) return 1;
IComparable ia = a as IComparable;
if (ia != null)
return ia.CompareTo(b);
IComparable ib = b as IComparable;
if (ib != null)
return -ib.CompareTo(a);
throw new ArgumentException("Wrong stuff");
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file=TextTreeTextElementNode.cs company=Microsoft>
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: A TextContainer node representing a TextElement.
//
// History:
// 02/18/2004 : [....] - Created
//
//---------------------------------------------------------------------------
using System;
using MS.Internal;
namespace System.Windows.Documents
{
// Each TextElement inserted though a public API is represented internally
// by a TextTreeTextElementNode.
//
// TextTreeTextElementNodes may contain trees of child nodes, nodes in
// a contained tree are scoped by the element node.
internal class TextTreeTextElementNode : TextTreeNode
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
// Creates a new instance.
internal TextTreeTextElementNode()
{
_symbolOffsetCache = -1;
}
#endregion Constructors
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
#if DEBUG
// Debug-only ToString override.
public override string ToString()
{
return ("TextElementNode Id=" + this.DebugId + " SymbolCount=" + _symbolCount);
}
#endif // DEBUG
#endregion Public Methods
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
// Returns a shallow copy of this node.
internal override TextTreeNode Clone()
{
TextTreeTextElementNode clone;
clone = new TextTreeTextElementNode();
clone._symbolCount = _symbolCount;
clone._imeCharCount = _imeCharCount;
clone._textElement = _textElement;
return clone;
}
// Returns the TextPointerContext of the node.
// Returns ElementStart if direction == Forward, otherwise ElementEnd
// if direction == Backward.
internal override TextPointerContext GetPointerContext(LogicalDirection direction)
{
return (direction == LogicalDirection.Forward) ? TextPointerContext.ElementStart : TextPointerContext.ElementEnd;
}
#endregion Internal methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
// If this node is a local root, then ParentNode contains it.
// Otherwise, this is the node parenting this node within its tree.
internal override SplayTreeNode ParentNode
{
get
{
return _parentNode;
}
set
{
_parentNode = (TextTreeNode)value;
}
}
// Root node of a contained tree, if any.
internal override SplayTreeNode ContainedNode
{
get
{
return _containedNode;
}
set
{
_containedNode = (TextTreeNode)value;
}
}
// Count of symbols of all siblings preceding this node.
internal override int LeftSymbolCount
{
get
{
return _leftSymbolCount;
}
set
{
_leftSymbolCount = value;
}
}
// Count of chars of all siblings preceding this node.
internal override int LeftCharCount
{
get
{
return _leftCharCount;
}
set
{
_leftCharCount = value;
}
}
// Left child node in a sibling tree.
internal override SplayTreeNode LeftChildNode
{
get
{
return _leftChildNode;
}
set
{
_leftChildNode = (TextTreeNode)value;
}
}
// Right child node in a sibling tree.
internal override SplayTreeNode RightChildNode
{
get
{
return _rightChildNode;
}
set
{
_rightChildNode = (TextTreeNode)value;
}
}
// The TextContainer's generation when SymbolOffsetCache was last updated.
// If the current generation doesn't match TextContainer.Generation, then
// SymbolOffsetCache is invalid.
internal override uint Generation
{
get
{
return _generation;
}
set
{
_generation = value;
}
}
// Cached symbol offset.
internal override int SymbolOffsetCache
{
get
{
return _symbolOffsetCache;
}
set
{
_symbolOffsetCache = value;
}
}
// Count of symbols covered by this node and any contained nodes.
// Includes two symbols for this node's start/end edges.
internal override int SymbolCount
{
get
{
return _symbolCount;
}
set
{
_symbolCount = value;
}
}
// Count of chars covered by this node and any contained nodes.
internal override int IMECharCount
{
get
{
return _imeCharCount;
}
set
{
_imeCharCount = value;
}
}
// Count of TextPositions referencing the node's BeforeStart edge.
// Since nodes don't usually have any references, we demand allocate
// storage when needed.
internal override bool BeforeStartReferenceCount
{
get
{
return (_edgeReferenceCounts & ElementEdge.BeforeStart) != 0;
}
set
{
Invariant.Assert(value); // Illegal to clear a set ref count.
_edgeReferenceCounts |= ElementEdge.BeforeStart;
}
}
// Count of TextPositions referencing the node's AfterStart edge.
// Since nodes don't usually have any references, we demand allocate
// storage when needed.
internal override bool AfterStartReferenceCount
{
get
{
return (_edgeReferenceCounts & ElementEdge.AfterStart) != 0;
}
set
{
Invariant.Assert(value); // Illegal to clear a set ref count.
_edgeReferenceCounts |= ElementEdge.AfterStart;
}
}
// Count of TextPositions referencing the node's BeforeEnd edge.
// Since nodes don't usually have any references, we demand allocate
// storage when needed.
internal override bool BeforeEndReferenceCount
{
get
{
return (_edgeReferenceCounts & ElementEdge.BeforeEnd) != 0;
}
set
{
Invariant.Assert(value); // Illegal to clear a set ref count.
_edgeReferenceCounts |= ElementEdge.BeforeEnd;
}
}
// Count of TextPositions referencing the node's AfterEnd edge.
// Since nodes don't usually have any references, we demand allocate
// storage when needed.
internal override bool AfterEndReferenceCount
{
get
{
return (_edgeReferenceCounts & ElementEdge.AfterEnd) != 0;
}
set
{
Invariant.Assert(value); // Illegal to clear a set ref count.
_edgeReferenceCounts |= ElementEdge.AfterEnd;
}
}
// The TextElement associated with this node.
internal TextElement TextElement
{
get
{
return _textElement;
}
set
{
_textElement = value;
}
}
// Plain text character count of this element's start edge.
// This property depends on the current location of the node!
internal int IMELeftEdgeCharCount
{
get
{
return (_textElement == null) ? -1 : _textElement.IMELeftEdgeCharCount;
}
}
// Returns true if this node is the leftmost sibling of its parent.
internal bool IsFirstSibling
{
get
{
Splay();
return (_leftChildNode == null);
}
}
#endregion Internal Properties
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
// Count of symbols of all siblings preceding this node.
private int _leftSymbolCount;
// Count of chars of all siblings preceding this node.
private int _leftCharCount;
// If this node is a local root, then ParentNode contains it.
// Otherwise, this is the node parenting this node within its tree.
private TextTreeNode _parentNode;
// Left child node in a sibling tree.
private TextTreeNode _leftChildNode;
// Right child node in a sibling tree.
private TextTreeNode _rightChildNode;
// Root node of a contained tree, if any.
private TextTreeNode _containedNode;
// The TextContainer's generation when SymbolOffsetCache was last updated.
// If the current generation doesn't match TextContainer.Generation, then
// SymbolOffsetCache is invalid.
private uint _generation;
// Cached symbol offset.
private int _symbolOffsetCache;
// Count of symbols covered by this node and any contained nodes.
// Includes two symbols for this node's start/end edges.
private int _symbolCount;
// Count of chars covered by this node and any contained nodes.
private int _imeCharCount;
// The TextElement associated with this node.
private TextElement _textElement;
// Reference counts of TextPositions referencing this node.
// Lazy allocated -- null means no references.
private ElementEdge _edgeReferenceCounts;
#endregion Private Fields
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Security.Cryptography.X509Certificates;
using Internal.Cryptography;
namespace System.Security.Cryptography.Pkcs
{
public sealed class EnvelopedCms
{
//
// Constructors
//
public EnvelopedCms()
: this(new ContentInfo(Array.Empty<byte>()))
{
}
public EnvelopedCms(ContentInfo contentInfo)
: this(contentInfo, new AlgorithmIdentifier(Oid.FromOidValue(Oids.TripleDesCbc, OidGroup.EncryptionAlgorithm)))
{
}
public EnvelopedCms(ContentInfo contentInfo, AlgorithmIdentifier encryptionAlgorithm)
{
if (contentInfo == null)
throw new ArgumentNullException(nameof(contentInfo));
if (encryptionAlgorithm == null)
throw new ArgumentNullException(nameof(encryptionAlgorithm));
Version = 0; // It makes little sense to ask for a version before you've decoded, but since the desktop returns 0 in that case, we will too.
ContentInfo = contentInfo;
ContentEncryptionAlgorithm = encryptionAlgorithm;
Certificates = new X509Certificate2Collection();
UnprotectedAttributes = new CryptographicAttributeObjectCollection();
_decryptorPal = null;
_lastCall = LastCall.Ctor;
}
//
// Latched properties.
// - For senders, the caller sets their values and they act as implicit inputs to the Encrypt() method.
// - For recipients, the Decode() and Decrypt() methods reset their values and the caller can inspect them if desired.
//
public int Version { get; private set; }
public ContentInfo ContentInfo { get; private set; }
public AlgorithmIdentifier ContentEncryptionAlgorithm { get; private set; }
public X509Certificate2Collection Certificates { get; private set; }
public CryptographicAttributeObjectCollection UnprotectedAttributes { get; private set; }
//
// Recipients invoke this property to retrieve the recipient information after a Decode() operation.
// Senders should not invoke this property.
//
public RecipientInfoCollection RecipientInfos
{
get
{
switch (_lastCall)
{
case LastCall.Ctor:
return new RecipientInfoCollection();
case LastCall.Encrypt:
throw PkcsPal.Instance.CreateRecipientInfosAfterEncryptException();
case LastCall.Decode:
case LastCall.Decrypt:
return _decryptorPal.RecipientInfos;
default:
Debug.Fail($"Unexpected _lastCall value: {_lastCall}");
throw new InvalidOperationException();
}
}
}
//
// Encrypt() overloads. Senders invoke this to encrypt and encode a CMS. Afterward, invoke the Encode() method to retrieve the actual encoding.
//
public void Encrypt(CmsRecipient recipient)
{
if (recipient == null)
throw new ArgumentNullException(nameof(recipient));
Encrypt(new CmsRecipientCollection(recipient));
}
public void Encrypt(CmsRecipientCollection recipients)
{
if (recipients == null)
throw new ArgumentNullException(nameof(recipients));
// Desktop compat note: Unlike the desktop, we don't provide a free UI to select the recipient. The app must give it to us programmatically.
if (recipients.Count == 0)
throw new PlatformNotSupportedException(SR.Cryptography_Cms_NoRecipients);
if (_decryptorPal != null)
{
_decryptorPal.Dispose();
_decryptorPal = null;
}
_encodedMessage = PkcsPal.Instance.Encrypt(recipients, ContentInfo, ContentEncryptionAlgorithm, Certificates, UnprotectedAttributes);
_lastCall = LastCall.Encrypt;
}
//
// Senders invoke Encode() after a successful Encrypt() to retrieve the RFC-compliant on-the-wire representation.
//
public byte[] Encode()
{
if (_encodedMessage == null)
throw new InvalidOperationException(SR.Cryptography_Cms_MessageNotEncrypted);
return _encodedMessage.CloneByteArray();
}
//
// Recipients invoke Decode() to turn the on-the-wire representation into a usable EnvelopedCms instance. Next step is to call Decrypt().
//
public void Decode(byte[] encodedMessage)
{
if (encodedMessage == null)
throw new ArgumentNullException(nameof(encodedMessage));
if (_decryptorPal != null)
{
_decryptorPal.Dispose();
_decryptorPal = null;
}
int version;
ContentInfo contentInfo;
AlgorithmIdentifier contentEncryptionAlgorithm;
X509Certificate2Collection originatorCerts;
CryptographicAttributeObjectCollection unprotectedAttributes;
_decryptorPal = PkcsPal.Instance.Decode(encodedMessage, out version, out contentInfo, out contentEncryptionAlgorithm, out originatorCerts, out unprotectedAttributes);
Version = version;
ContentInfo = contentInfo;
ContentEncryptionAlgorithm = contentEncryptionAlgorithm;
Certificates = originatorCerts;
UnprotectedAttributes = unprotectedAttributes;
// Desktop compat: Encode() after a Decode() returns you the same thing that ContentInfo.Content does.
_encodedMessage = contentInfo.Content.CloneByteArray();
_lastCall = LastCall.Decode;
}
//
// Decrypt() overloads: Recipients invoke Decrypt() after a successful Decode(). Afterwards, invoke ContentInfo to get the decrypted content.
//
public void Decrypt()
{
DecryptContent(RecipientInfos, null);
}
public void Decrypt(RecipientInfo recipientInfo)
{
if (recipientInfo == null)
throw new ArgumentNullException(nameof(recipientInfo));
DecryptContent(new RecipientInfoCollection(recipientInfo), null);
}
public void Decrypt(RecipientInfo recipientInfo, X509Certificate2Collection extraStore)
{
if (recipientInfo == null)
throw new ArgumentNullException(nameof(recipientInfo));
if (extraStore == null)
throw new ArgumentNullException(nameof(extraStore));
DecryptContent(new RecipientInfoCollection(recipientInfo), extraStore);
}
public void Decrypt(X509Certificate2Collection extraStore)
{
if (extraStore == null)
throw new ArgumentNullException(nameof(extraStore));
DecryptContent(RecipientInfos, extraStore);
}
private void DecryptContent(RecipientInfoCollection recipientInfos, X509Certificate2Collection extraStore)
{
switch (_lastCall)
{
case LastCall.Ctor:
throw new InvalidOperationException(SR.Cryptography_Cms_MessageNotEncrypted);
case LastCall.Encrypt:
throw PkcsPal.Instance.CreateDecryptAfterEncryptException();
case LastCall.Decrypt:
throw PkcsPal.Instance.CreateDecryptTwiceException();
case LastCall.Decode:
break; // This is the expected state.
default:
Debug.Fail($"Unexpected _lastCall value: {_lastCall}");
throw new InvalidOperationException();
}
extraStore = extraStore ?? new X509Certificate2Collection();
X509Certificate2Collection certs = new X509Certificate2Collection();
PkcsPal.Instance.AddCertsFromStoreForDecryption(certs);
certs.AddRange(extraStore);
X509Certificate2Collection originatorCerts = Certificates;
ContentInfo newContentInfo = null;
Exception exception = PkcsPal.Instance.CreateRecipientsNotFoundException();
foreach (RecipientInfo recipientInfo in recipientInfos)
{
using (X509Certificate2 cert = certs.TryFindMatchingCertificate(recipientInfo.RecipientIdentifier))
{
if (cert == null)
{
exception = PkcsPal.Instance.CreateRecipientsNotFoundException();
continue;
}
newContentInfo = _decryptorPal.TryDecrypt(recipientInfo, cert, originatorCerts, extraStore, out exception);
}
if (exception != null)
continue;
break;
}
if (exception != null)
throw exception;
ContentInfo = newContentInfo;
// Desktop compat: Encode() after a Decrypt() returns you the same thing that ContentInfo.Content does.
_encodedMessage = newContentInfo.Content.CloneByteArray();
_lastCall = LastCall.Decrypt;
}
//
// Instance fields
//
private DecryptorPal _decryptorPal;
private byte[] _encodedMessage;
private LastCall _lastCall;
private enum LastCall
{
Ctor = 1,
Encrypt = 2,
Decode = 3,
Decrypt = 4,
}
}
}
| |
// 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.ObjectModel;
using System.IdentityModel.Policy;
using System.ServiceModel.Channels;
using System.ServiceModel.Security.Tokens;
namespace System.ServiceModel.Security
{
public class SecurityMessageProperty : IMessageProperty, IDisposable
{
// This is the list of outgoing supporting tokens
private Collection<SupportingTokenSpecification> _outgoingSupportingTokens;
private Collection<SupportingTokenSpecification> _incomingSupportingTokens;
private SecurityTokenSpecification _transportToken;
private SecurityTokenSpecification _protectionToken;
private SecurityTokenSpecification _initiatorToken;
private SecurityTokenSpecification _recipientToken;
private ServiceSecurityContext _securityContext;
private ReadOnlyCollection<IAuthorizationPolicy> _externalAuthorizationPolicies;
private string _senderIdPrefix = "_";
private bool _disposed = false;
public SecurityMessageProperty()
{
_securityContext = ServiceSecurityContext.Anonymous;
}
public ServiceSecurityContext ServiceSecurityContext
{
get
{
ThrowIfDisposed();
return _securityContext;
}
set
{
ThrowIfDisposed();
_securityContext = value;
}
}
public ReadOnlyCollection<IAuthorizationPolicy> ExternalAuthorizationPolicies
{
get
{
return _externalAuthorizationPolicies;
}
set
{
_externalAuthorizationPolicies = value;
}
}
public SecurityTokenSpecification ProtectionToken
{
get
{
ThrowIfDisposed();
return _protectionToken;
}
set
{
ThrowIfDisposed();
_protectionToken = value;
}
}
public SecurityTokenSpecification InitiatorToken
{
get
{
ThrowIfDisposed();
return _initiatorToken;
}
set
{
ThrowIfDisposed();
_initiatorToken = value;
}
}
public SecurityTokenSpecification RecipientToken
{
get
{
ThrowIfDisposed();
return _recipientToken;
}
set
{
ThrowIfDisposed();
_recipientToken = value;
}
}
public SecurityTokenSpecification TransportToken
{
get
{
ThrowIfDisposed();
return _transportToken;
}
set
{
ThrowIfDisposed();
_transportToken = value;
}
}
public string SenderIdPrefix
{
get
{
return _senderIdPrefix;
}
set
{
XmlHelper.ValidateIdPrefix(value);
_senderIdPrefix = value;
}
}
public bool HasIncomingSupportingTokens
{
get
{
ThrowIfDisposed();
return ((_incomingSupportingTokens != null) && (_incomingSupportingTokens.Count > 0));
}
}
public Collection<SupportingTokenSpecification> IncomingSupportingTokens
{
get
{
ThrowIfDisposed();
if (_incomingSupportingTokens == null)
{
_incomingSupportingTokens = new Collection<SupportingTokenSpecification>();
}
return _incomingSupportingTokens;
}
}
public Collection<SupportingTokenSpecification> OutgoingSupportingTokens
{
get
{
if (_outgoingSupportingTokens == null)
{
_outgoingSupportingTokens = new Collection<SupportingTokenSpecification>();
}
return _outgoingSupportingTokens;
}
}
internal bool HasOutgoingSupportingTokens
{
get
{
return ((_outgoingSupportingTokens != null) && (_outgoingSupportingTokens.Count > 0));
}
}
public IMessageProperty CreateCopy()
{
ThrowIfDisposed();
SecurityMessageProperty result = new SecurityMessageProperty();
if (this.HasOutgoingSupportingTokens)
{
for (int i = 0; i < _outgoingSupportingTokens.Count; ++i)
{
result.OutgoingSupportingTokens.Add(_outgoingSupportingTokens[i]);
}
}
if (this.HasIncomingSupportingTokens)
{
for (int i = 0; i < _incomingSupportingTokens.Count; ++i)
{
result.IncomingSupportingTokens.Add(_incomingSupportingTokens[i]);
}
}
result._securityContext = _securityContext;
result._externalAuthorizationPolicies = _externalAuthorizationPolicies;
result._senderIdPrefix = _senderIdPrefix;
result._protectionToken = _protectionToken;
result._initiatorToken = _initiatorToken;
result._recipientToken = _recipientToken;
result._transportToken = _transportToken;
return result;
}
public static SecurityMessageProperty GetOrCreate(Message message)
{
if (message == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
SecurityMessageProperty result = null;
if (message.Properties != null)
result = message.Properties.Security;
if (result == null)
{
result = new SecurityMessageProperty();
message.Properties.Security = result;
}
return result;
}
private void AddAuthorizationPolicies(SecurityTokenSpecification spec, Collection<IAuthorizationPolicy> policies)
{
if (spec != null && spec.SecurityTokenPolicies != null && spec.SecurityTokenPolicies.Count > 0)
{
for (int i = 0; i < spec.SecurityTokenPolicies.Count; ++i)
{
policies.Add(spec.SecurityTokenPolicies[i]);
}
}
}
internal ReadOnlyCollection<IAuthorizationPolicy> GetInitiatorTokenAuthorizationPolicies()
{
return GetInitiatorTokenAuthorizationPolicies(true);
}
internal ReadOnlyCollection<IAuthorizationPolicy> GetInitiatorTokenAuthorizationPolicies(bool includeTransportToken)
{
return GetInitiatorTokenAuthorizationPolicies(includeTransportToken, null);
}
internal ReadOnlyCollection<IAuthorizationPolicy> GetInitiatorTokenAuthorizationPolicies(bool includeTransportToken, SecurityContextSecurityToken supportingSessionTokenToExclude)
{
// fast path
if (!this.HasIncomingSupportingTokens)
{
if (_transportToken != null && _initiatorToken == null && _protectionToken == null)
{
if (includeTransportToken && _transportToken.SecurityTokenPolicies != null)
{
return _transportToken.SecurityTokenPolicies;
}
else
{
return EmptyReadOnlyCollection<IAuthorizationPolicy>.Instance;
}
}
else if (_transportToken == null && _initiatorToken != null && _protectionToken == null)
{
return _initiatorToken.SecurityTokenPolicies ?? EmptyReadOnlyCollection<IAuthorizationPolicy>.Instance;
}
else if (_transportToken == null && _initiatorToken == null && _protectionToken != null)
{
return _protectionToken.SecurityTokenPolicies ?? EmptyReadOnlyCollection<IAuthorizationPolicy>.Instance;
}
}
Collection<IAuthorizationPolicy> policies = new Collection<IAuthorizationPolicy>();
if (includeTransportToken)
{
AddAuthorizationPolicies(_transportToken, policies);
}
AddAuthorizationPolicies(_initiatorToken, policies);
AddAuthorizationPolicies(_protectionToken, policies);
if (this.HasIncomingSupportingTokens)
{
for (int i = 0; i < _incomingSupportingTokens.Count; ++i)
{
if (supportingSessionTokenToExclude != null)
{
SecurityContextSecurityToken sct = _incomingSupportingTokens[i].SecurityToken as SecurityContextSecurityToken;
if (sct != null && sct.ContextId == supportingSessionTokenToExclude.ContextId)
{
continue;
}
}
SecurityTokenAttachmentMode attachmentMode = _incomingSupportingTokens[i].SecurityTokenAttachmentMode;
// a safety net in case more attachment modes get added to the product without
// reviewing this code.
if (attachmentMode == SecurityTokenAttachmentMode.Endorsing
|| attachmentMode == SecurityTokenAttachmentMode.Signed
|| attachmentMode == SecurityTokenAttachmentMode.SignedEncrypted
|| attachmentMode == SecurityTokenAttachmentMode.SignedEndorsing)
{
AddAuthorizationPolicies(_incomingSupportingTokens[i], policies);
}
}
}
return new ReadOnlyCollection<IAuthorizationPolicy>(policies);
}
public void Dispose()
{
// do no-op for future V2
if (!_disposed)
{
_disposed = true;
}
}
private void ThrowIfDisposed()
{
if (_disposed)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().FullName));
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security;
using System.Text;
using System.Threading;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
namespace System
{
public sealed partial class TimeZoneInfo
{
// registry constants for the 'Time Zones' hive
//
private const string TimeZonesRegistryHive = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones";
private const string DisplayValue = "Display";
private const string DaylightValue = "Dlt";
private const string StandardValue = "Std";
private const string MuiDisplayValue = "MUI_Display";
private const string MuiDaylightValue = "MUI_Dlt";
private const string MuiStandardValue = "MUI_Std";
private const string TimeZoneInfoValue = "TZI";
private const string FirstEntryValue = "FirstEntry";
private const string LastEntryValue = "LastEntry";
private const int MaxKeyLength = 255;
private const int RegByteLength = 44;
#pragma warning disable 0420
private sealed partial class CachedData
{
private static TimeZoneInfo GetCurrentOneYearLocal()
{
// load the data from the OS
Win32Native.TimeZoneInformation timeZoneInformation;
long result = UnsafeNativeMethods.GetTimeZoneInformation(out timeZoneInformation);
return result == Win32Native.TIME_ZONE_ID_INVALID ?
CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId) :
GetLocalTimeZoneFromWin32Data(timeZoneInformation, dstDisabled: false);
}
private volatile OffsetAndRule _oneYearLocalFromUtc;
public OffsetAndRule GetOneYearLocalFromUtc(int year)
{
OffsetAndRule oneYearLocFromUtc = _oneYearLocalFromUtc;
if (oneYearLocFromUtc == null || oneYearLocFromUtc.Year != year)
{
TimeZoneInfo currentYear = GetCurrentOneYearLocal();
AdjustmentRule rule = currentYear._adjustmentRules == null ? null : currentYear._adjustmentRules[0];
oneYearLocFromUtc = new OffsetAndRule(year, currentYear.BaseUtcOffset, rule);
_oneYearLocalFromUtc = oneYearLocFromUtc;
}
return oneYearLocFromUtc;
}
}
#pragma warning restore 0420
private sealed class OffsetAndRule
{
public readonly int Year;
public readonly TimeSpan Offset;
public readonly AdjustmentRule Rule;
public OffsetAndRule(int year, TimeSpan offset, AdjustmentRule rule)
{
Year = year;
Offset = offset;
Rule = rule;
}
}
/// <summary>
/// Returns a cloned array of AdjustmentRule objects
/// </summary>
public AdjustmentRule[] GetAdjustmentRules()
{
if (_adjustmentRules == null)
{
return Array.Empty<AdjustmentRule>();
}
return (AdjustmentRule[])_adjustmentRules.Clone();
}
private static void PopulateAllSystemTimeZones(CachedData cachedData)
{
Debug.Assert(Monitor.IsEntered(cachedData));
using (RegistryKey reg = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive, writable: false))
{
if (reg != null)
{
foreach (string keyName in reg.GetSubKeyNames())
{
TimeZoneInfo value;
Exception ex;
TryGetTimeZone(keyName, false, out value, out ex, cachedData); // populate the cache
}
}
}
}
private TimeZoneInfo(Win32Native.TimeZoneInformation zone, bool dstDisabled)
{
if (string.IsNullOrEmpty(zone.StandardName))
{
_id = LocalId; // the ID must contain at least 1 character - initialize _id to "Local"
}
else
{
_id = zone.StandardName;
}
_baseUtcOffset = new TimeSpan(0, -(zone.Bias), 0);
if (!dstDisabled)
{
// only create the adjustment rule if DST is enabled
Win32Native.RegistryTimeZoneInformation regZone = new Win32Native.RegistryTimeZoneInformation(zone);
AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(regZone, DateTime.MinValue.Date, DateTime.MaxValue.Date, zone.Bias);
if (rule != null)
{
_adjustmentRules = new AdjustmentRule[1];
_adjustmentRules[0] = rule;
}
}
ValidateTimeZoneInfo(_id, _baseUtcOffset, _adjustmentRules, out _supportsDaylightSavingTime);
_displayName = zone.StandardName;
_standardDisplayName = zone.StandardName;
_daylightDisplayName = zone.DaylightName;
}
/// <summary>
/// Helper function to check if the current TimeZoneInformation struct does not support DST.
/// This check returns true when the DaylightDate == StandardDate.
/// This check is only meant to be used for "Local".
/// </summary>
private static bool CheckDaylightSavingTimeNotSupported(Win32Native.TimeZoneInformation timeZone) =>
timeZone.DaylightDate.Year == timeZone.StandardDate.Year &&
timeZone.DaylightDate.Month == timeZone.StandardDate.Month &&
timeZone.DaylightDate.DayOfWeek == timeZone.StandardDate.DayOfWeek &&
timeZone.DaylightDate.Day == timeZone.StandardDate.Day &&
timeZone.DaylightDate.Hour == timeZone.StandardDate.Hour &&
timeZone.DaylightDate.Minute == timeZone.StandardDate.Minute &&
timeZone.DaylightDate.Second == timeZone.StandardDate.Second &&
timeZone.DaylightDate.Milliseconds == timeZone.StandardDate.Milliseconds;
/// <summary>
/// Converts a Win32Native.RegistryTimeZoneInformation (REG_TZI_FORMAT struct) to an AdjustmentRule.
/// </summary>
private static AdjustmentRule CreateAdjustmentRuleFromTimeZoneInformation(Win32Native.RegistryTimeZoneInformation timeZoneInformation, DateTime startDate, DateTime endDate, int defaultBaseUtcOffset)
{
bool supportsDst = timeZoneInformation.StandardDate.Month != 0;
if (!supportsDst)
{
if (timeZoneInformation.Bias == defaultBaseUtcOffset)
{
// this rule will not contain any information to be used to adjust dates. just ignore it
return null;
}
return AdjustmentRule.CreateAdjustmentRule(
startDate,
endDate,
TimeSpan.Zero, // no daylight saving transition
TransitionTime.CreateFixedDateRule(DateTime.MinValue, 1, 1),
TransitionTime.CreateFixedDateRule(DateTime.MinValue.AddMilliseconds(1), 1, 1),
new TimeSpan(0, defaultBaseUtcOffset - timeZoneInformation.Bias, 0), // Bias delta is all what we need from this rule
noDaylightTransitions: false);
}
//
// Create an AdjustmentRule with TransitionTime objects
//
TransitionTime daylightTransitionStart;
if (!TransitionTimeFromTimeZoneInformation(timeZoneInformation, out daylightTransitionStart, readStartDate: true))
{
return null;
}
TransitionTime daylightTransitionEnd;
if (!TransitionTimeFromTimeZoneInformation(timeZoneInformation, out daylightTransitionEnd, readStartDate: false))
{
return null;
}
if (daylightTransitionStart.Equals(daylightTransitionEnd))
{
// this happens when the time zone does support DST but the OS has DST disabled
return null;
}
return AdjustmentRule.CreateAdjustmentRule(
startDate,
endDate,
new TimeSpan(0, -timeZoneInformation.DaylightBias, 0),
daylightTransitionStart,
daylightTransitionEnd,
new TimeSpan(0, defaultBaseUtcOffset - timeZoneInformation.Bias, 0),
noDaylightTransitions: false);
}
/// <summary>
/// Helper function that searches the registry for a time zone entry
/// that matches the TimeZoneInformation struct.
/// </summary>
private static string FindIdFromTimeZoneInformation(Win32Native.TimeZoneInformation timeZone, out bool dstDisabled)
{
dstDisabled = false;
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive, writable: false))
{
if (key == null)
{
return null;
}
foreach (string keyName in key.GetSubKeyNames())
{
if (TryCompareTimeZoneInformationToRegistry(timeZone, keyName, out dstDisabled))
{
return keyName;
}
}
}
return null;
}
/// <summary>
/// Helper function for retrieving the local system time zone.
/// May throw COMException, TimeZoneNotFoundException, InvalidTimeZoneException.
/// Assumes cachedData lock is taken.
/// </summary>
/// <returns>A new TimeZoneInfo instance.</returns>
private static TimeZoneInfo GetLocalTimeZone(CachedData cachedData)
{
Debug.Assert(Monitor.IsEntered(cachedData));
string id = null;
//
// Try using the "kernel32!GetDynamicTimeZoneInformation" API to get the "id"
//
var dynamicTimeZoneInformation = new Win32Native.DynamicTimeZoneInformation();
// call kernel32!GetDynamicTimeZoneInformation...
long result = UnsafeNativeMethods.GetDynamicTimeZoneInformation(out dynamicTimeZoneInformation);
if (result == Win32Native.TIME_ZONE_ID_INVALID)
{
// return a dummy entry
return CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId);
}
var timeZoneInformation = new Win32Native.TimeZoneInformation(dynamicTimeZoneInformation);
bool dstDisabled = dynamicTimeZoneInformation.DynamicDaylightTimeDisabled;
// check to see if we can use the key name returned from the API call
if (!string.IsNullOrEmpty(dynamicTimeZoneInformation.TimeZoneKeyName))
{
TimeZoneInfo zone;
Exception ex;
if (TryGetTimeZone(dynamicTimeZoneInformation.TimeZoneKeyName, dstDisabled, out zone, out ex, cachedData) == TimeZoneInfoResult.Success)
{
// successfully loaded the time zone from the registry
return zone;
}
}
// the key name was not returned or it pointed to a bogus entry - search for the entry ourselves
id = FindIdFromTimeZoneInformation(timeZoneInformation, out dstDisabled);
if (id != null)
{
TimeZoneInfo zone;
Exception ex;
if (TryGetTimeZone(id, dstDisabled, out zone, out ex, cachedData) == TimeZoneInfoResult.Success)
{
// successfully loaded the time zone from the registry
return zone;
}
}
// We could not find the data in the registry. Fall back to using
// the data from the Win32 API
return GetLocalTimeZoneFromWin32Data(timeZoneInformation, dstDisabled);
}
/// <summary>
/// Helper function used by 'GetLocalTimeZone()' - this function wraps a bunch of
/// try/catch logic for handling the TimeZoneInfo private constructor that takes
/// a Win32Native.TimeZoneInformation structure.
/// </summary>
private static TimeZoneInfo GetLocalTimeZoneFromWin32Data(Win32Native.TimeZoneInformation timeZoneInformation, bool dstDisabled)
{
// first try to create the TimeZoneInfo with the original 'dstDisabled' flag
try
{
return new TimeZoneInfo(timeZoneInformation, dstDisabled);
}
catch (ArgumentException) { }
catch (InvalidTimeZoneException) { }
// if 'dstDisabled' was false then try passing in 'true' as a last ditch effort
if (!dstDisabled)
{
try
{
return new TimeZoneInfo(timeZoneInformation, dstDisabled: true);
}
catch (ArgumentException) { }
catch (InvalidTimeZoneException) { }
}
// the data returned from Windows is completely bogus; return a dummy entry
return CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId);
}
/// <summary>
/// Helper function for retrieving a TimeZoneInfo object by <time_zone_name>.
/// This function wraps the logic necessary to keep the private
/// SystemTimeZones cache in working order
///
/// This function will either return a valid TimeZoneInfo instance or
/// it will throw 'InvalidTimeZoneException' / 'TimeZoneNotFoundException'.
/// </summary>
public static TimeZoneInfo FindSystemTimeZoneById(string id)
{
// Special case for Utc as it will not exist in the dictionary with the rest
// of the system time zones. There is no need to do this check for Local.Id
// since Local is a real time zone that exists in the dictionary cache
if (string.Equals(id, UtcId, StringComparison.OrdinalIgnoreCase))
{
return Utc;
}
if (id == null)
{
throw new ArgumentNullException(nameof(id));
}
else if (id.Length == 0 || id.Length > MaxKeyLength || id.Contains("\0"))
{
throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id));
}
TimeZoneInfo value;
Exception e;
TimeZoneInfoResult result;
CachedData cachedData = s_cachedData;
lock (cachedData)
{
result = TryGetTimeZone(id, false, out value, out e, cachedData);
}
if (result == TimeZoneInfoResult.Success)
{
return value;
}
else if (result == TimeZoneInfoResult.InvalidTimeZoneException)
{
throw new InvalidTimeZoneException(SR.Format(SR.InvalidTimeZone_InvalidRegistryData, id), e);
}
else if (result == TimeZoneInfoResult.SecurityException)
{
throw new SecurityException(SR.Format(SR.Security_CannotReadRegistryData, id), e);
}
else
{
throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id), e);
}
}
// DateTime.Now fast path that avoids allocating an historically accurate TimeZoneInfo.Local and just creates a 1-year (current year) accurate time zone
internal static TimeSpan GetDateTimeNowUtcOffsetFromUtc(DateTime time, out bool isAmbiguousLocalDst)
{
bool isDaylightSavings = false;
isAmbiguousLocalDst = false;
TimeSpan baseOffset;
int timeYear = time.Year;
OffsetAndRule match = s_cachedData.GetOneYearLocalFromUtc(timeYear);
baseOffset = match.Offset;
if (match.Rule != null)
{
baseOffset = baseOffset + match.Rule.BaseUtcOffsetDelta;
if (match.Rule.HasDaylightSaving)
{
isDaylightSavings = GetIsDaylightSavingsFromUtc(time, timeYear, match.Offset, match.Rule, null, out isAmbiguousLocalDst, Local);
baseOffset += (isDaylightSavings ? match.Rule.DaylightDelta : TimeSpan.Zero /* FUTURE: rule.StandardDelta */);
}
}
return baseOffset;
}
/// <summary>
/// Converts a Win32Native.RegistryTimeZoneInformation (REG_TZI_FORMAT struct) to a TransitionTime
/// - When the argument 'readStart' is true the corresponding daylightTransitionTimeStart field is read
/// - When the argument 'readStart' is false the corresponding dayightTransitionTimeEnd field is read
/// </summary>
private static bool TransitionTimeFromTimeZoneInformation(Win32Native.RegistryTimeZoneInformation timeZoneInformation, out TransitionTime transitionTime, bool readStartDate)
{
//
// SYSTEMTIME -
//
// If the time zone does not support daylight saving time or if the caller needs
// to disable daylight saving time, the wMonth member in the SYSTEMTIME structure
// must be zero. If this date is specified, the DaylightDate value in the
// TIME_ZONE_INFORMATION structure must also be specified. Otherwise, the system
// assumes the time zone data is invalid and no changes will be applied.
//
bool supportsDst = (timeZoneInformation.StandardDate.Month != 0);
if (!supportsDst)
{
transitionTime = default(TransitionTime);
return false;
}
//
// SYSTEMTIME -
//
// * FixedDateRule -
// If the Year member is not zero, the transition date is absolute; it will only occur one time
//
// * FloatingDateRule -
// To select the correct day in the month, set the Year member to zero, the Hour and Minute
// members to the transition time, the DayOfWeek member to the appropriate weekday, and the
// Day member to indicate the occurence of the day of the week within the month (first through fifth).
//
// Using this notation, specify the 2:00a.m. on the first Sunday in April as follows:
// Hour = 2,
// Month = 4,
// DayOfWeek = 0,
// Day = 1.
//
// Specify 2:00a.m. on the last Thursday in October as follows:
// Hour = 2,
// Month = 10,
// DayOfWeek = 4,
// Day = 5.
//
if (readStartDate)
{
//
// read the "daylightTransitionStart"
//
if (timeZoneInformation.DaylightDate.Year == 0)
{
transitionTime = TransitionTime.CreateFloatingDateRule(
new DateTime(1, /* year */
1, /* month */
1, /* day */
timeZoneInformation.DaylightDate.Hour,
timeZoneInformation.DaylightDate.Minute,
timeZoneInformation.DaylightDate.Second,
timeZoneInformation.DaylightDate.Milliseconds),
timeZoneInformation.DaylightDate.Month,
timeZoneInformation.DaylightDate.Day, /* Week 1-5 */
(DayOfWeek)timeZoneInformation.DaylightDate.DayOfWeek);
}
else
{
transitionTime = TransitionTime.CreateFixedDateRule(
new DateTime(1, /* year */
1, /* month */
1, /* day */
timeZoneInformation.DaylightDate.Hour,
timeZoneInformation.DaylightDate.Minute,
timeZoneInformation.DaylightDate.Second,
timeZoneInformation.DaylightDate.Milliseconds),
timeZoneInformation.DaylightDate.Month,
timeZoneInformation.DaylightDate.Day);
}
}
else
{
//
// read the "daylightTransitionEnd"
//
if (timeZoneInformation.StandardDate.Year == 0)
{
transitionTime = TransitionTime.CreateFloatingDateRule(
new DateTime(1, /* year */
1, /* month */
1, /* day */
timeZoneInformation.StandardDate.Hour,
timeZoneInformation.StandardDate.Minute,
timeZoneInformation.StandardDate.Second,
timeZoneInformation.StandardDate.Milliseconds),
timeZoneInformation.StandardDate.Month,
timeZoneInformation.StandardDate.Day, /* Week 1-5 */
(DayOfWeek)timeZoneInformation.StandardDate.DayOfWeek);
}
else
{
transitionTime = TransitionTime.CreateFixedDateRule(
new DateTime(1, /* year */
1, /* month */
1, /* day */
timeZoneInformation.StandardDate.Hour,
timeZoneInformation.StandardDate.Minute,
timeZoneInformation.StandardDate.Second,
timeZoneInformation.StandardDate.Milliseconds),
timeZoneInformation.StandardDate.Month,
timeZoneInformation.StandardDate.Day);
}
}
return true;
}
/// <summary>
/// Helper function that takes:
/// 1. A string representing a <time_zone_name> registry key name.
/// 2. A RegistryTimeZoneInformation struct containing the default rule.
/// 3. An AdjustmentRule[] out-parameter.
/// </summary>
private static bool TryCreateAdjustmentRules(string id, Win32Native.RegistryTimeZoneInformation defaultTimeZoneInformation, out AdjustmentRule[] rules, out Exception e, int defaultBaseUtcOffset)
{
e = null;
try
{
// Optional, Dynamic Time Zone Registry Data
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//
// HKLM
// Software
// Microsoft
// Windows NT
// CurrentVersion
// Time Zones
// <time_zone_name>
// Dynamic DST
// * "FirstEntry" REG_DWORD "1980"
// First year in the table. If the current year is less than this value,
// this entry will be used for DST boundaries
// * "LastEntry" REG_DWORD "2038"
// Last year in the table. If the current year is greater than this value,
// this entry will be used for DST boundaries"
// * "<year1>" REG_BINARY REG_TZI_FORMAT
// See Win32Native.RegistryTimeZoneInformation
// * "<year2>" REG_BINARY REG_TZI_FORMAT
// See Win32Native.RegistryTimeZoneInformation
// * "<year3>" REG_BINARY REG_TZI_FORMAT
// See Win32Native.RegistryTimeZoneInformation
//
using (RegistryKey dynamicKey = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id + "\\Dynamic DST", writable: false))
{
if (dynamicKey == null)
{
AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(
defaultTimeZoneInformation, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset);
rules = rule == null ? null : new[] { rule };
return true;
}
//
// loop over all of the "<time_zone_name>\Dynamic DST" hive entries
//
// read FirstEntry {MinValue - (year1, 12, 31)}
// read MiddleEntry {(yearN, 1, 1) - (yearN, 12, 31)}
// read LastEntry {(yearN, 1, 1) - MaxValue }
// read the FirstEntry and LastEntry key values (ex: "1980", "2038")
int first = (int)dynamicKey.GetValue(FirstEntryValue, -1, RegistryValueOptions.None);
int last = (int)dynamicKey.GetValue(LastEntryValue, -1, RegistryValueOptions.None);
if (first == -1 || last == -1 || first > last)
{
rules = null;
return false;
}
// read the first year entry
Win32Native.RegistryTimeZoneInformation dtzi;
byte[] regValue = dynamicKey.GetValue(first.ToString(CultureInfo.InvariantCulture), null, RegistryValueOptions.None) as byte[];
if (regValue == null || regValue.Length != RegByteLength)
{
rules = null;
return false;
}
dtzi = new Win32Native.RegistryTimeZoneInformation(regValue);
if (first == last)
{
// there is just 1 dynamic rule for this time zone.
AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(dtzi, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset);
rules = rule == null ? null : new[] { rule };
return true;
}
List<AdjustmentRule> rulesList = new List<AdjustmentRule>(1);
// there are more than 1 dynamic rules for this time zone.
AdjustmentRule firstRule = CreateAdjustmentRuleFromTimeZoneInformation(
dtzi,
DateTime.MinValue.Date, // MinValue
new DateTime(first, 12, 31), // December 31, <FirstYear>
defaultBaseUtcOffset);
if (firstRule != null)
{
rulesList.Add(firstRule);
}
// read the middle year entries
for (int i = first + 1; i < last; i++)
{
regValue = dynamicKey.GetValue(i.ToString(CultureInfo.InvariantCulture), null, RegistryValueOptions.None) as byte[];
if (regValue == null || regValue.Length != RegByteLength)
{
rules = null;
return false;
}
dtzi = new Win32Native.RegistryTimeZoneInformation(regValue);
AdjustmentRule middleRule = CreateAdjustmentRuleFromTimeZoneInformation(
dtzi,
new DateTime(i, 1, 1), // January 01, <Year>
new DateTime(i, 12, 31), // December 31, <Year>
defaultBaseUtcOffset);
if (middleRule != null)
{
rulesList.Add(middleRule);
}
}
// read the last year entry
regValue = dynamicKey.GetValue(last.ToString(CultureInfo.InvariantCulture), null, RegistryValueOptions.None) as byte[];
dtzi = new Win32Native.RegistryTimeZoneInformation(regValue);
if (regValue == null || regValue.Length != RegByteLength)
{
rules = null;
return false;
}
AdjustmentRule lastRule = CreateAdjustmentRuleFromTimeZoneInformation(
dtzi,
new DateTime(last, 1, 1), // January 01, <LastYear>
DateTime.MaxValue.Date, // MaxValue
defaultBaseUtcOffset);
if (lastRule != null)
{
rulesList.Add(lastRule);
}
// convert the ArrayList to an AdjustmentRule array
rules = rulesList.ToArray();
if (rules != null && rules.Length == 0)
{
rules = null;
}
} // end of: using (RegistryKey dynamicKey...
}
catch (InvalidCastException ex)
{
// one of the RegistryKey.GetValue calls could not be cast to an expected value type
rules = null;
e = ex;
return false;
}
catch (ArgumentOutOfRangeException ex)
{
rules = null;
e = ex;
return false;
}
catch (ArgumentException ex)
{
rules = null;
e = ex;
return false;
}
return true;
}
/// <summary>
/// Helper function that compares the StandardBias and StandardDate portion a
/// TimeZoneInformation struct to a time zone registry entry.
/// </summary>
private static bool TryCompareStandardDate(Win32Native.TimeZoneInformation timeZone, Win32Native.RegistryTimeZoneInformation registryTimeZoneInfo) =>
timeZone.Bias == registryTimeZoneInfo.Bias &&
timeZone.StandardBias == registryTimeZoneInfo.StandardBias &&
timeZone.StandardDate.Year == registryTimeZoneInfo.StandardDate.Year &&
timeZone.StandardDate.Month == registryTimeZoneInfo.StandardDate.Month &&
timeZone.StandardDate.DayOfWeek == registryTimeZoneInfo.StandardDate.DayOfWeek &&
timeZone.StandardDate.Day == registryTimeZoneInfo.StandardDate.Day &&
timeZone.StandardDate.Hour == registryTimeZoneInfo.StandardDate.Hour &&
timeZone.StandardDate.Minute == registryTimeZoneInfo.StandardDate.Minute &&
timeZone.StandardDate.Second == registryTimeZoneInfo.StandardDate.Second &&
timeZone.StandardDate.Milliseconds == registryTimeZoneInfo.StandardDate.Milliseconds;
/// <summary>
/// Helper function that compares a TimeZoneInformation struct to a time zone registry entry.
/// </summary>
private static bool TryCompareTimeZoneInformationToRegistry(Win32Native.TimeZoneInformation timeZone, string id, out bool dstDisabled)
{
dstDisabled = false;
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id, writable: false))
{
if (key == null)
{
return false;
}
Win32Native.RegistryTimeZoneInformation registryTimeZoneInfo;
byte[] regValue = key.GetValue(TimeZoneInfoValue, null, RegistryValueOptions.None) as byte[];
if (regValue == null || regValue.Length != RegByteLength) return false;
registryTimeZoneInfo = new Win32Native.RegistryTimeZoneInformation(regValue);
//
// first compare the bias and standard date information between the data from the Win32 API
// and the data from the registry...
//
bool result = TryCompareStandardDate(timeZone, registryTimeZoneInfo);
if (!result)
{
return false;
}
result = dstDisabled || CheckDaylightSavingTimeNotSupported(timeZone) ||
//
// since Daylight Saving Time is not "disabled", do a straight comparision between
// the Win32 API data and the registry data ...
//
(timeZone.DaylightBias == registryTimeZoneInfo.DaylightBias &&
timeZone.DaylightDate.Year == registryTimeZoneInfo.DaylightDate.Year &&
timeZone.DaylightDate.Month == registryTimeZoneInfo.DaylightDate.Month &&
timeZone.DaylightDate.DayOfWeek == registryTimeZoneInfo.DaylightDate.DayOfWeek &&
timeZone.DaylightDate.Day == registryTimeZoneInfo.DaylightDate.Day &&
timeZone.DaylightDate.Hour == registryTimeZoneInfo.DaylightDate.Hour &&
timeZone.DaylightDate.Minute == registryTimeZoneInfo.DaylightDate.Minute &&
timeZone.DaylightDate.Second == registryTimeZoneInfo.DaylightDate.Second &&
timeZone.DaylightDate.Milliseconds == registryTimeZoneInfo.DaylightDate.Milliseconds);
// Finally compare the "StandardName" string value...
//
// we do not compare "DaylightName" as this TimeZoneInformation field may contain
// either "StandardName" or "DaylightName" depending on the time of year and current machine settings
//
if (result)
{
string registryStandardName = key.GetValue(StandardValue, string.Empty, RegistryValueOptions.None) as string;
result = string.Equals(registryStandardName, timeZone.StandardName, StringComparison.Ordinal);
}
return result;
}
}
/// <summary>
/// Helper function for retrieving a localized string resource via MUI.
/// The function expects a string in the form: "@resource.dll, -123"
///
/// "resource.dll" is a language-neutral portable executable (LNPE) file in
/// the %windir%\system32 directory. The OS is queried to find the best-fit
/// localized resource file for this LNPE (ex: %windir%\system32\en-us\resource.dll.mui).
/// If a localized resource file exists, we LoadString resource ID "123" and
/// return it to our caller.
/// </summary>
private static string TryGetLocalizedNameByMuiNativeResource(string resource)
{
if (string.IsNullOrEmpty(resource))
{
return string.Empty;
}
// parse "@tzres.dll, -100"
//
// filePath = "C:\Windows\System32\tzres.dll"
// resourceId = -100
//
string[] resources = resource.Split(',');
if (resources.Length != 2)
{
return string.Empty;
}
string filePath;
int resourceId;
// get the path to Windows\System32
string system32 = Environment.SystemDirectory;
// trim the string "@tzres.dll" => "tzres.dll"
string tzresDll = resources[0].TrimStart('@');
try
{
filePath = Path.Combine(system32, tzresDll);
}
catch (ArgumentException)
{
// there were probably illegal characters in the path
return string.Empty;
}
if (!int.TryParse(resources[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out resourceId))
{
return string.Empty;
}
resourceId = -resourceId;
try
{
StringBuilder fileMuiPath = StringBuilderCache.Acquire(Path.MaxPath);
fileMuiPath.Length = Path.MaxPath;
int fileMuiPathLength = Path.MaxPath;
int languageLength = 0;
long enumerator = 0;
bool succeeded = UnsafeNativeMethods.GetFileMUIPath(
Win32Native.MUI_PREFERRED_UI_LANGUAGES,
filePath, null /* language */, ref languageLength,
fileMuiPath, ref fileMuiPathLength, ref enumerator);
if (!succeeded)
{
StringBuilderCache.Release(fileMuiPath);
return string.Empty;
}
return TryGetLocalizedNameByNativeResource(StringBuilderCache.GetStringAndRelease(fileMuiPath), resourceId);
}
catch (EntryPointNotFoundException)
{
return string.Empty;
}
}
/// <summary>
/// Helper function for retrieving a localized string resource via a native resource DLL.
/// The function expects a string in the form: "C:\Windows\System32\en-us\resource.dll"
///
/// "resource.dll" is a language-specific resource DLL.
/// If the localized resource DLL exists, LoadString(resource) is returned.
/// </summary>
private static string TryGetLocalizedNameByNativeResource(string filePath, int resource)
{
using (SafeLibraryHandle handle =
Interop.Kernel32.LoadLibraryExW(filePath, IntPtr.Zero, Interop.Kernel32.LOAD_LIBRARY_AS_DATAFILE))
{
if (!handle.IsInvalid)
{
StringBuilder localizedResource = StringBuilderCache.Acquire(Win32Native.LOAD_STRING_MAX_LENGTH);
localizedResource.Length = Win32Native.LOAD_STRING_MAX_LENGTH;
int result = Interop.User32.LoadStringW(handle, resource,
localizedResource, localizedResource.Length);
if (result != 0)
{
return StringBuilderCache.GetStringAndRelease(localizedResource);
}
}
}
return string.Empty;
}
/// <summary>
/// Helper function for retrieving the DisplayName, StandardName, and DaylightName from the registry
///
/// The function first checks the MUI_ key-values, and if they exist, it loads the strings from the MUI
/// resource dll(s). When the keys do not exist, the function falls back to reading from the standard
/// key-values
/// </summary>
private static bool TryGetLocalizedNamesByRegistryKey(RegistryKey key, out string displayName, out string standardName, out string daylightName)
{
displayName = string.Empty;
standardName = string.Empty;
daylightName = string.Empty;
// read the MUI_ registry keys
string displayNameMuiResource = key.GetValue(MuiDisplayValue, string.Empty, RegistryValueOptions.None) as string;
string standardNameMuiResource = key.GetValue(MuiStandardValue, string.Empty, RegistryValueOptions.None) as string;
string daylightNameMuiResource = key.GetValue(MuiDaylightValue, string.Empty, RegistryValueOptions.None) as string;
// try to load the strings from the native resource DLL(s)
if (!string.IsNullOrEmpty(displayNameMuiResource))
{
displayName = TryGetLocalizedNameByMuiNativeResource(displayNameMuiResource);
}
if (!string.IsNullOrEmpty(standardNameMuiResource))
{
standardName = TryGetLocalizedNameByMuiNativeResource(standardNameMuiResource);
}
if (!string.IsNullOrEmpty(daylightNameMuiResource))
{
daylightName = TryGetLocalizedNameByMuiNativeResource(daylightNameMuiResource);
}
// fallback to using the standard registry keys
if (string.IsNullOrEmpty(displayName))
{
displayName = key.GetValue(DisplayValue, string.Empty, RegistryValueOptions.None) as string;
}
if (string.IsNullOrEmpty(standardName))
{
standardName = key.GetValue(StandardValue, string.Empty, RegistryValueOptions.None) as string;
}
if (string.IsNullOrEmpty(daylightName))
{
daylightName = key.GetValue(DaylightValue, string.Empty, RegistryValueOptions.None) as string;
}
return true;
}
/// <summary>
/// Helper function that takes a string representing a <time_zone_name> registry key name
/// and returns a TimeZoneInfo instance.
/// </summary>
private static TimeZoneInfoResult TryGetTimeZoneFromLocalMachine(string id, out TimeZoneInfo value, out Exception e)
{
e = null;
// Standard Time Zone Registry Data
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// HKLM
// Software
// Microsoft
// Windows NT
// CurrentVersion
// Time Zones
// <time_zone_name>
// * STD, REG_SZ "Standard Time Name"
// (For OS installed zones, this will always be English)
// * MUI_STD, REG_SZ "@tzres.dll,-1234"
// Indirect string to localized resource for Standard Time,
// add "%windir%\system32\" after "@"
// * DLT, REG_SZ "Daylight Time Name"
// (For OS installed zones, this will always be English)
// * MUI_DLT, REG_SZ "@tzres.dll,-1234"
// Indirect string to localized resource for Daylight Time,
// add "%windir%\system32\" after "@"
// * Display, REG_SZ "Display Name like (GMT-8:00) Pacific Time..."
// * MUI_Display, REG_SZ "@tzres.dll,-1234"
// Indirect string to localized resource for the Display,
// add "%windir%\system32\" after "@"
// * TZI, REG_BINARY REG_TZI_FORMAT
// See Win32Native.RegistryTimeZoneInformation
//
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id, writable: false))
{
if (key == null)
{
value = null;
return TimeZoneInfoResult.TimeZoneNotFoundException;
}
Win32Native.RegistryTimeZoneInformation defaultTimeZoneInformation;
byte[] regValue = key.GetValue(TimeZoneInfoValue, null, RegistryValueOptions.None) as byte[];
if (regValue == null || regValue.Length != RegByteLength)
{
// the registry value could not be cast to a byte array
value = null;
return TimeZoneInfoResult.InvalidTimeZoneException;
}
defaultTimeZoneInformation = new Win32Native.RegistryTimeZoneInformation(regValue);
AdjustmentRule[] adjustmentRules;
if (!TryCreateAdjustmentRules(id, defaultTimeZoneInformation, out adjustmentRules, out e, defaultTimeZoneInformation.Bias))
{
value = null;
return TimeZoneInfoResult.InvalidTimeZoneException;
}
string displayName;
string standardName;
string daylightName;
if (!TryGetLocalizedNamesByRegistryKey(key, out displayName, out standardName, out daylightName))
{
value = null;
return TimeZoneInfoResult.InvalidTimeZoneException;
}
try
{
value = new TimeZoneInfo(
id,
new TimeSpan(0, -(defaultTimeZoneInformation.Bias), 0),
displayName,
standardName,
daylightName,
adjustmentRules,
disableDaylightSavingTime: false);
return TimeZoneInfoResult.Success;
}
catch (ArgumentException ex)
{
// TimeZoneInfo constructor can throw ArgumentException and InvalidTimeZoneException
value = null;
e = ex;
return TimeZoneInfoResult.InvalidTimeZoneException;
}
catch (InvalidTimeZoneException ex)
{
// TimeZoneInfo constructor can throw ArgumentException and InvalidTimeZoneException
value = null;
e = ex;
return TimeZoneInfoResult.InvalidTimeZoneException;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
namespace MongoDB.Connections
{
/// <summary>
/// Connection pool implementation based on this document:
/// http://msdn.microsoft.com/en-us/library/8xx3tyca%28VS.100%29.aspx
/// </summary>
internal class PooledConnectionFactory : ConnectionFactoryBase
{
private readonly object _syncObject = new object();
private readonly Queue<RawConnection> _freeConnections = new Queue<RawConnection>();
private readonly List<RawConnection> _usedConnections = new List<RawConnection>();
private readonly List<RawConnection> _invalidConnections = new List<RawConnection>();
/// <summary>
/// Initializes a new instance of the
/// <see cref="PooledConnectionFactory"/>
/// class.
/// </summary>
/// <param name="connectionString">The connection string.</param>
public PooledConnectionFactory(string connectionString)
:base(connectionString)
{
if(Builder.MaximumPoolSize < 1){
throw new ArgumentException("MaximumPoolSize have to be greater or equal then 1");
}
if(Builder.MinimumPoolSize < 0){
throw new ArgumentException("MinimumPoolSize have to be greater or equal then 0");
}
if(Builder.MinimumPoolSize > Builder.MaximumPoolSize){
throw new ArgumentException("MinimumPoolSize must be smaller than MaximumPoolSize");
}
if(Builder.ConnectionLifetime.TotalSeconds < 0){
throw new ArgumentException("ConnectionLifetime have to be greater or equal then 0");
}
EnsureMinimalPoolSize();
}
/// <summary>
/// Gets the size of the pool.
/// </summary>
/// <value>The size of the pool.</value>
public int PoolSize
{
get
{
lock(_syncObject)
return _freeConnections.Count + _usedConnections.Count;
}
}
/// <summary>
/// Cleanups the connections.
/// </summary>
public override void Cleanup()
{
CheckFreeConnectionsAlive();
DisposeInvalidConnections();
EnsureMinimalPoolSize();
}
/// <summary>
/// Checks the free connections alive.
/// </summary>
private void CheckFreeConnectionsAlive()
{
lock(_syncObject)
{
var freeConnections = _freeConnections.ToArray();
_freeConnections.Clear();
foreach(var freeConnection in freeConnections)
if(IsAlive(freeConnection))
_freeConnections.Enqueue(freeConnection);
else
_invalidConnections.Add(freeConnection);
}
}
/// <summary>
/// Disposes the invalid connections.
/// </summary>
private void DisposeInvalidConnections()
{
RawConnection[] invalidConnections;
lock(_syncObject)
{
invalidConnections = _invalidConnections.ToArray();
_invalidConnections.Clear();
}
foreach(var invalidConnection in invalidConnections)
invalidConnection.Dispose();
}
/// <summary>
/// Determines whether the specified connection is alive.
/// </summary>
/// <param name="connection">The connection.</param>
/// <returns>
/// <c>true</c> if the specified connection is alive; otherwise, <c>false</c>.
/// </returns>
private bool IsAlive(RawConnection connection)
{
if(connection == null)
throw new ArgumentNullException("connection");
if(!connection.IsConnected)
return false;
if(connection.IsInvalid)
return false;
if(Builder.ConnectionLifetime != TimeSpan.Zero)
if(connection.CreationTime.Add(Builder.ConnectionLifetime) < DateTime.Now)
return false;
return true;
}
/// <summary>
/// Borrows the connection.
/// </summary>
/// <returns></returns>
public override RawConnection Open()
{
RawConnection connection;
lock(_syncObject)
{
if(_freeConnections.Count > 0)
{
connection = _freeConnections.Dequeue();
_usedConnections.Add(connection);
return connection;
}
if(PoolSize >= Builder.MaximumPoolSize)
{
if(!Monitor.Wait(_syncObject, Builder.ConnectionTimeout))
//Todo: custom exception?
throw new MongoException("Timeout expired. The timeout period elapsed prior to obtaining a connection from pool. This may have occured because all pooled connections were in use and max poolsize was reached.");
return Open();
}
}
connection = CreateRawConnection();
lock(_syncObject)
_usedConnections.Add(connection);
return connection;
}
/// <summary>
/// Returns the connection.
/// </summary>
/// <param name = "connection">The connection.</param>
public override void Close(RawConnection connection)
{
if(connection == null)
throw new ArgumentNullException("connection");
if(!IsAlive(connection))
{
lock(_syncObject)
{
_usedConnections.Remove(connection);
_invalidConnections.Add(connection);
}
return;
}
lock(_syncObject)
{
_usedConnections.Remove(connection);
_freeConnections.Enqueue(connection);
Monitor.Pulse(_syncObject);
}
}
/// <summary>
/// Ensures the size of the minimal pool.
/// </summary>
private void EnsureMinimalPoolSize()
{
lock(_syncObject)
while(PoolSize < Builder.MinimumPoolSize)
_freeConnections.Enqueue(CreateRawConnection());
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public override void Dispose()
{
lock(_syncObject)
{
foreach(var usedConnection in _usedConnections)
usedConnection.Dispose();
foreach(var freeConnection in _freeConnections)
freeConnection.Dispose();
foreach(var invalidConnection in _invalidConnections)
invalidConnection.Dispose();
_usedConnections.Clear();
_freeConnections.Clear();
_invalidConnections.Clear();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Reflection;
using System.Reflection.Emit;
using static System.Linq.Expressions.CachedReflectionInfo;
namespace System.Linq.Expressions.Compiler
{
internal static class ILGen
{
internal static void Emit(this ILGenerator il, OpCode opcode, MethodBase methodBase)
{
Debug.Assert(methodBase is MethodInfo || methodBase is ConstructorInfo);
var ctor = methodBase as ConstructorInfo;
if ((object)ctor != null)
{
il.Emit(opcode, ctor);
}
else
{
il.Emit(opcode, (MethodInfo)methodBase);
}
}
#region Instruction helpers
internal static void EmitLoadArg(this ILGenerator il, int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < ushort.MaxValue);
switch (index)
{
case 0:
il.Emit(OpCodes.Ldarg_0);
break;
case 1:
il.Emit(OpCodes.Ldarg_1);
break;
case 2:
il.Emit(OpCodes.Ldarg_2);
break;
case 3:
il.Emit(OpCodes.Ldarg_3);
break;
default:
if (index <= byte.MaxValue)
{
il.Emit(OpCodes.Ldarg_S, (byte)index);
}
else
{
// cast to short, result is correct ushort.
il.Emit(OpCodes.Ldarg, (short)index);
}
break;
}
}
internal static void EmitLoadArgAddress(this ILGenerator il, int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < ushort.MaxValue);
if (index <= byte.MaxValue)
{
il.Emit(OpCodes.Ldarga_S, (byte)index);
}
else
{
// cast to short, result is correct ushort.
il.Emit(OpCodes.Ldarga, (short)index);
}
}
internal static void EmitStoreArg(this ILGenerator il, int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < ushort.MaxValue);
if (index <= byte.MaxValue)
{
il.Emit(OpCodes.Starg_S, (byte)index);
}
else
{
// cast to short, result is correct ushort.
il.Emit(OpCodes.Starg, (short)index);
}
}
/// <summary>
/// Emits a Ldind* instruction for the appropriate type
/// </summary>
internal static void EmitLoadValueIndirect(this ILGenerator il, Type type)
{
Debug.Assert(type != null);
switch (type.GetTypeCode())
{
case TypeCode.Byte:
il.Emit(OpCodes.Ldind_I1);
break;
case TypeCode.Boolean:
case TypeCode.SByte:
il.Emit(OpCodes.Ldind_U1);
break;
case TypeCode.Int16:
il.Emit(OpCodes.Ldind_I2);
break;
case TypeCode.Char:
case TypeCode.UInt16:
il.Emit(OpCodes.Ldind_U2);
break;
case TypeCode.Int32:
il.Emit(OpCodes.Ldind_I4);
break;
case TypeCode.UInt32:
il.Emit(OpCodes.Ldind_U4);
break;
case TypeCode.Int64:
case TypeCode.UInt64:
il.Emit(OpCodes.Ldind_I8);
break;
case TypeCode.Single:
il.Emit(OpCodes.Ldind_R4);
break;
case TypeCode.Double:
il.Emit(OpCodes.Ldind_R8);
break;
default:
if (type.IsValueType)
{
il.Emit(OpCodes.Ldobj, type);
}
else
{
il.Emit(OpCodes.Ldind_Ref);
}
break;
}
}
/// <summary>
/// Emits a Stind* instruction for the appropriate type.
/// </summary>
internal static void EmitStoreValueIndirect(this ILGenerator il, Type type)
{
Debug.Assert(type != null);
switch (type.GetTypeCode())
{
case TypeCode.Boolean:
case TypeCode.Byte:
case TypeCode.SByte:
il.Emit(OpCodes.Stind_I1);
break;
case TypeCode.Char:
case TypeCode.Int16:
case TypeCode.UInt16:
il.Emit(OpCodes.Stind_I2);
break;
case TypeCode.Int32:
case TypeCode.UInt32:
il.Emit(OpCodes.Stind_I4);
break;
case TypeCode.Int64:
case TypeCode.UInt64:
il.Emit(OpCodes.Stind_I8);
break;
case TypeCode.Single:
il.Emit(OpCodes.Stind_R4);
break;
case TypeCode.Double:
il.Emit(OpCodes.Stind_R8);
break;
default:
if (type.IsValueType)
{
il.Emit(OpCodes.Stobj, type);
}
else
{
il.Emit(OpCodes.Stind_Ref);
}
break;
}
}
// Emits the Ldelem* instruction for the appropriate type
internal static void EmitLoadElement(this ILGenerator il, Type type)
{
Debug.Assert(type != null);
if (!type.IsValueType)
{
il.Emit(OpCodes.Ldelem_Ref);
}
else
{
switch (type.GetTypeCode())
{
case TypeCode.Boolean:
case TypeCode.SByte:
il.Emit(OpCodes.Ldelem_I1);
break;
case TypeCode.Byte:
il.Emit(OpCodes.Ldelem_U1);
break;
case TypeCode.Int16:
il.Emit(OpCodes.Ldelem_I2);
break;
case TypeCode.Char:
case TypeCode.UInt16:
il.Emit(OpCodes.Ldelem_U2);
break;
case TypeCode.Int32:
il.Emit(OpCodes.Ldelem_I4);
break;
case TypeCode.UInt32:
il.Emit(OpCodes.Ldelem_U4);
break;
case TypeCode.Int64:
case TypeCode.UInt64:
il.Emit(OpCodes.Ldelem_I8);
break;
case TypeCode.Single:
il.Emit(OpCodes.Ldelem_R4);
break;
case TypeCode.Double:
il.Emit(OpCodes.Ldelem_R8);
break;
default:
il.Emit(OpCodes.Ldelem, type);
break;
}
}
}
/// <summary>
/// Emits a Stelem* instruction for the appropriate type.
/// </summary>
internal static void EmitStoreElement(this ILGenerator il, Type type)
{
Debug.Assert(type != null);
switch (type.GetTypeCode())
{
case TypeCode.Boolean:
case TypeCode.SByte:
case TypeCode.Byte:
il.Emit(OpCodes.Stelem_I1);
break;
case TypeCode.Char:
case TypeCode.Int16:
case TypeCode.UInt16:
il.Emit(OpCodes.Stelem_I2);
break;
case TypeCode.Int32:
case TypeCode.UInt32:
il.Emit(OpCodes.Stelem_I4);
break;
case TypeCode.Int64:
case TypeCode.UInt64:
il.Emit(OpCodes.Stelem_I8);
break;
case TypeCode.Single:
il.Emit(OpCodes.Stelem_R4);
break;
case TypeCode.Double:
il.Emit(OpCodes.Stelem_R8);
break;
default:
if (type.IsValueType)
{
il.Emit(OpCodes.Stelem, type);
}
else
{
il.Emit(OpCodes.Stelem_Ref);
}
break;
}
}
internal static void EmitType(this ILGenerator il, Type type)
{
Debug.Assert(type != null);
il.Emit(OpCodes.Ldtoken, type);
il.Emit(OpCodes.Call, Type_GetTypeFromHandle);
}
#endregion
#region Fields, properties and methods
internal static void EmitFieldAddress(this ILGenerator il, FieldInfo fi)
{
Debug.Assert(fi != null);
il.Emit(fi.IsStatic ? OpCodes.Ldsflda : OpCodes.Ldflda, fi);
}
internal static void EmitFieldGet(this ILGenerator il, FieldInfo fi)
{
Debug.Assert(fi != null);
il.Emit(fi.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld, fi);
}
internal static void EmitFieldSet(this ILGenerator il, FieldInfo fi)
{
Debug.Assert(fi != null);
il.Emit(fi.IsStatic ? OpCodes.Stsfld : OpCodes.Stfld, fi);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
internal static void EmitNew(this ILGenerator il, ConstructorInfo ci)
{
Debug.Assert(ci != null);
Debug.Assert(!ci.DeclaringType.ContainsGenericParameters);
il.Emit(OpCodes.Newobj, ci);
}
#endregion
#region Constants
internal static void EmitNull(this ILGenerator il)
{
il.Emit(OpCodes.Ldnull);
}
internal static void EmitString(this ILGenerator il, string value)
{
Debug.Assert(value != null);
il.Emit(OpCodes.Ldstr, value);
}
internal static void EmitPrimitive(this ILGenerator il, bool value)
{
il.Emit(value ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
}
internal static void EmitPrimitive(this ILGenerator il, int value)
{
OpCode c;
switch (value)
{
case -1:
c = OpCodes.Ldc_I4_M1;
break;
case 0:
c = OpCodes.Ldc_I4_0;
break;
case 1:
c = OpCodes.Ldc_I4_1;
break;
case 2:
c = OpCodes.Ldc_I4_2;
break;
case 3:
c = OpCodes.Ldc_I4_3;
break;
case 4:
c = OpCodes.Ldc_I4_4;
break;
case 5:
c = OpCodes.Ldc_I4_5;
break;
case 6:
c = OpCodes.Ldc_I4_6;
break;
case 7:
c = OpCodes.Ldc_I4_7;
break;
case 8:
c = OpCodes.Ldc_I4_8;
break;
default:
if (value >= sbyte.MinValue && value <= sbyte.MaxValue)
{
il.Emit(OpCodes.Ldc_I4_S, (sbyte)value);
}
else
{
il.Emit(OpCodes.Ldc_I4, value);
}
return;
}
il.Emit(c);
}
private static void EmitPrimitive(this ILGenerator il, uint value)
{
il.EmitPrimitive(unchecked((int)value));
}
private static void EmitPrimitive(this ILGenerator il, long value)
{
if (int.MinValue <= value & value <= uint.MaxValue)
{
il.EmitPrimitive(unchecked((int)value));
// While often not of consequence depending on what follows, there are cases where this
// casting matters. Values [0, int.MaxValue] can use either safely, but negative values
// must use conv.i8 and those (int.MaxValue, uint.MaxValue] must use conv.u8, or else
// the higher bits will be wrong.
il.Emit(value > 0 ? OpCodes.Conv_U8 : OpCodes.Conv_I8);
}
else
{
il.Emit(OpCodes.Ldc_I8, value);
}
}
private static void EmitPrimitive(this ILGenerator il, ulong value)
{
il.EmitPrimitive(unchecked((long)value));
}
private static void EmitPrimitive(this ILGenerator il, double value)
{
il.Emit(OpCodes.Ldc_R8, value);
}
private static void EmitPrimitive(this ILGenerator il, float value)
{
il.Emit(OpCodes.Ldc_R4, value);
}
// matches TryEmitConstant
internal static bool CanEmitConstant(object value, Type type)
{
if (value == null || CanEmitILConstant(type))
{
return true;
}
Type t = value as Type;
if (t != null)
{
return ShouldLdtoken(t);
}
MethodBase mb = value as MethodBase;
return mb != null && ShouldLdtoken(mb);
}
// matches TryEmitILConstant
private static bool CanEmitILConstant(Type type)
{
switch (type.GetNonNullableType().GetTypeCode())
{
case TypeCode.Boolean:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Char:
case TypeCode.Byte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
case TypeCode.Decimal:
case TypeCode.String:
return true;
}
return false;
}
//
// Note: we support emitting more things as IL constants than
// Linq does
internal static bool TryEmitConstant(this ILGenerator il, object value, Type type, ILocalCache locals)
{
if (value == null)
{
// Smarter than the Linq implementation which uses the initobj
// pattern for all value types (works, but requires a local and
// more IL)
il.EmitDefault(type, locals);
return true;
}
// Handle the easy cases
if (il.TryEmitILConstant(value, type))
{
return true;
}
// Check for a few more types that we support emitting as constants
Type t = value as Type;
if (t != null)
{
if (ShouldLdtoken(t))
{
il.EmitType(t);
if (type != typeof(Type))
{
il.Emit(OpCodes.Castclass, type);
}
return true;
}
return false;
}
MethodBase mb = value as MethodBase;
if (mb != null && ShouldLdtoken(mb))
{
il.Emit(OpCodes.Ldtoken, mb);
Type dt = mb.DeclaringType;
if (dt != null && dt.IsGenericType)
{
il.Emit(OpCodes.Ldtoken, dt);
il.Emit(OpCodes.Call, MethodBase_GetMethodFromHandle_RuntimeMethodHandle_RuntimeTypeHandle);
}
else
{
il.Emit(OpCodes.Call, MethodBase_GetMethodFromHandle_RuntimeMethodHandle);
}
if (type != typeof(MethodBase))
{
il.Emit(OpCodes.Castclass, type);
}
return true;
}
return false;
}
private static bool ShouldLdtoken(Type t)
{
// If CompileToMethod is re-enabled, t is TypeBuilder should also return
// true when not compiling to a DynamicMethod
return t.IsGenericParameter || t.IsVisible;
}
internal static bool ShouldLdtoken(MethodBase mb)
{
// Can't ldtoken on a DynamicMethod
if (mb is DynamicMethod)
{
return false;
}
Type dt = mb.DeclaringType;
return dt == null || ShouldLdtoken(dt);
}
private static bool TryEmitILConstant(this ILGenerator il, object value, Type type)
{
Debug.Assert(value != null);
if (type.IsNullableType())
{
Type nonNullType = type.GetNonNullableType();
if (TryEmitILConstant(il, value, nonNullType))
{
il.Emit(OpCodes.Newobj, type.GetConstructor(new[] { nonNullType }));
return true;
}
return false;
}
switch (type.GetTypeCode())
{
case TypeCode.Boolean:
il.EmitPrimitive((bool)value);
return true;
case TypeCode.SByte:
il.EmitPrimitive((sbyte)value);
return true;
case TypeCode.Int16:
il.EmitPrimitive((short)value);
return true;
case TypeCode.Int32:
il.EmitPrimitive((int)value);
return true;
case TypeCode.Int64:
il.EmitPrimitive((long)value);
return true;
case TypeCode.Single:
il.EmitPrimitive((float)value);
return true;
case TypeCode.Double:
il.EmitPrimitive((double)value);
return true;
case TypeCode.Char:
il.EmitPrimitive((char)value);
return true;
case TypeCode.Byte:
il.EmitPrimitive((byte)value);
return true;
case TypeCode.UInt16:
il.EmitPrimitive((ushort)value);
return true;
case TypeCode.UInt32:
il.EmitPrimitive((uint)value);
return true;
case TypeCode.UInt64:
il.EmitPrimitive((ulong)value);
return true;
case TypeCode.Decimal:
il.EmitDecimal((decimal)value);
return true;
case TypeCode.String:
il.EmitString((string)value);
return true;
default:
return false;
}
}
#endregion
#region Linq Conversions
internal static void EmitConvertToType(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked, ILocalCache locals)
{
if (TypeUtils.AreEquivalent(typeFrom, typeTo))
{
return;
}
Debug.Assert(typeFrom != typeof(void) && typeTo != typeof(void));
bool isTypeFromNullable = typeFrom.IsNullableType();
bool isTypeToNullable = typeTo.IsNullableType();
Type nnExprType = typeFrom.GetNonNullableType();
Type nnType = typeTo.GetNonNullableType();
if (typeFrom.IsInterface || // interface cast
typeTo.IsInterface ||
typeFrom == typeof(object) || // boxing cast
typeTo == typeof(object) ||
typeFrom == typeof(System.Enum) ||
typeFrom == typeof(System.ValueType) ||
TypeUtils.IsLegalExplicitVariantDelegateConversion(typeFrom, typeTo))
{
il.EmitCastToType(typeFrom, typeTo);
}
else if (isTypeFromNullable || isTypeToNullable)
{
il.EmitNullableConversion(typeFrom, typeTo, isChecked, locals);
}
else if (!(typeFrom.IsConvertible() && typeTo.IsConvertible()) // primitive runtime conversion
&&
(nnExprType.IsAssignableFrom(nnType) || // down cast
nnType.IsAssignableFrom(nnExprType))) // up cast
{
il.EmitCastToType(typeFrom, typeTo);
}
else if (typeFrom.IsArray && typeTo.IsArray) // reference conversion from one array type to another via castclass
{
il.EmitCastToType(typeFrom, typeTo);
}
else
{
il.EmitNumericConversion(typeFrom, typeTo, isChecked);
}
}
private static void EmitCastToType(this ILGenerator il, Type typeFrom, Type typeTo)
{
if (typeFrom.IsValueType)
{
Debug.Assert(!typeTo.IsValueType);
il.Emit(OpCodes.Box, typeFrom);
if (typeTo != typeof(object))
{
il.Emit(OpCodes.Castclass, typeTo);
}
}
else
{
il.Emit(typeTo.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, typeTo);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private static void EmitNumericConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked)
{
TypeCode tc = typeTo.GetTypeCode();
TypeCode tf = typeFrom.GetTypeCode();
if (tc == tf)
{
// Between enums of same underlying type, or between such an enum and the underlying type itself.
// Includes bool-backed enums, which is the only valid conversion to or from bool.
// Just leave the value on the stack, and treat it as the wanted type.
return;
}
bool isFromUnsigned = tf.IsUnsigned();
OpCode convCode;
switch (tc)
{
case TypeCode.Single:
if (isFromUnsigned)
il.Emit(OpCodes.Conv_R_Un);
convCode = OpCodes.Conv_R4;
break;
case TypeCode.Double:
if (isFromUnsigned)
il.Emit(OpCodes.Conv_R_Un);
convCode = OpCodes.Conv_R8;
break;
case TypeCode.Decimal:
// NB: TypeUtils.IsImplicitNumericConversion makes the promise that implicit conversions
// from various integral types and char to decimal are possible. Coalesce allows the
// conversion lambda to be omitted in these cases, so we have to handle this case in
// here as well, by using the op_Implicit operator implementation on System.Decimal
// because there are no opcodes for System.Decimal.
Debug.Assert(typeFrom != typeTo);
MethodInfo method;
switch (tf)
{
case TypeCode.Byte: method = Decimal_op_Implicit_Byte; break;
case TypeCode.SByte: method = Decimal_op_Implicit_SByte; break;
case TypeCode.Int16: method = Decimal_op_Implicit_Int16; break;
case TypeCode.UInt16: method = Decimal_op_Implicit_UInt16; break;
case TypeCode.Int32: method = Decimal_op_Implicit_Int32; break;
case TypeCode.UInt32: method = Decimal_op_Implicit_UInt32; break;
case TypeCode.Int64: method = Decimal_op_Implicit_Int64; break;
case TypeCode.UInt64: method = Decimal_op_Implicit_UInt64; break;
case TypeCode.Char: method = Decimal_op_Implicit_Char; break;
default:
throw ContractUtils.Unreachable;
}
il.Emit(OpCodes.Call, method);
return;
case TypeCode.SByte:
if (isChecked)
{
convCode = isFromUnsigned ? OpCodes.Conv_Ovf_I1_Un : OpCodes.Conv_Ovf_I1;
}
else
{
if (tf == TypeCode.Byte)
{
return;
}
convCode = OpCodes.Conv_I1;
}
break;
case TypeCode.Byte:
if (isChecked)
{
convCode = isFromUnsigned ? OpCodes.Conv_Ovf_U1_Un : OpCodes.Conv_Ovf_U1;
}
else
{
if (tf == TypeCode.SByte)
{
return;
}
convCode = OpCodes.Conv_U1;
}
break;
case TypeCode.Int16:
switch (tf)
{
case TypeCode.SByte:
case TypeCode.Byte:
return;
case TypeCode.Char:
case TypeCode.UInt16:
if (!isChecked)
{
return;
}
break;
}
convCode = isChecked
? (isFromUnsigned ? OpCodes.Conv_Ovf_I2_Un : OpCodes.Conv_Ovf_I2)
: OpCodes.Conv_I2;
break;
case TypeCode.Char:
case TypeCode.UInt16:
switch (tf)
{
case TypeCode.Byte:
case TypeCode.Char:
case TypeCode.UInt16:
return;
case TypeCode.SByte:
case TypeCode.Int16:
if (!isChecked)
{
return;
}
break;
}
convCode = isChecked
? (isFromUnsigned ? OpCodes.Conv_Ovf_U2_Un : OpCodes.Conv_Ovf_U2)
: OpCodes.Conv_U2;
break;
case TypeCode.Int32:
switch (tf)
{
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.UInt16:
return;
case TypeCode.UInt32:
if (!isChecked)
{
return;
}
break;
}
convCode = isChecked
? (isFromUnsigned ? OpCodes.Conv_Ovf_I4_Un : OpCodes.Conv_Ovf_I4)
: OpCodes.Conv_I4;
break;
case TypeCode.UInt32:
switch (tf)
{
case TypeCode.Byte:
case TypeCode.Char:
case TypeCode.UInt16:
return;
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
if (!isChecked)
{
return;
}
break;
}
convCode = isChecked
? (isFromUnsigned ? OpCodes.Conv_Ovf_U4_Un : OpCodes.Conv_Ovf_U4)
: OpCodes.Conv_U4;
break;
case TypeCode.Int64:
if (!isChecked && tf == TypeCode.UInt64)
{
return;
}
convCode = isChecked
? (isFromUnsigned ? OpCodes.Conv_Ovf_I8_Un : OpCodes.Conv_Ovf_I8)
: (isFromUnsigned ? OpCodes.Conv_U8 : OpCodes.Conv_I8);
break;
case TypeCode.UInt64:
if (!isChecked && tf == TypeCode.Int64)
{
return;
}
convCode = isChecked
? (isFromUnsigned || tf.IsFloatingPoint() ? OpCodes.Conv_Ovf_U8_Un : OpCodes.Conv_Ovf_U8)
: (isFromUnsigned || tf.IsFloatingPoint() ? OpCodes.Conv_U8 : OpCodes.Conv_I8);
break;
default:
throw ContractUtils.Unreachable;
}
il.Emit(convCode);
}
private static void EmitNullableToNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked, ILocalCache locals)
{
Debug.Assert(typeFrom.IsNullableType());
Debug.Assert(typeTo.IsNullableType());
Label labIfNull;
Label labEnd;
LocalBuilder locFrom = locals.GetLocal(typeFrom);
il.Emit(OpCodes.Stloc, locFrom);
// test for null
il.Emit(OpCodes.Ldloca, locFrom);
il.EmitHasValue(typeFrom);
labIfNull = il.DefineLabel();
il.Emit(OpCodes.Brfalse_S, labIfNull);
il.Emit(OpCodes.Ldloca, locFrom);
locals.FreeLocal(locFrom);
il.EmitGetValueOrDefault(typeFrom);
Type nnTypeFrom = typeFrom.GetNonNullableType();
Type nnTypeTo = typeTo.GetNonNullableType();
il.EmitConvertToType(nnTypeFrom, nnTypeTo, isChecked, locals);
// construct result type
ConstructorInfo ci = typeTo.GetConstructor(new Type[] { nnTypeTo });
il.Emit(OpCodes.Newobj, ci);
labEnd = il.DefineLabel();
il.Emit(OpCodes.Br_S, labEnd);
// if null then create a default one
il.MarkLabel(labIfNull);
LocalBuilder locTo = locals.GetLocal(typeTo);
il.Emit(OpCodes.Ldloca, locTo);
il.Emit(OpCodes.Initobj, typeTo);
il.Emit(OpCodes.Ldloc, locTo);
locals.FreeLocal(locTo);
il.MarkLabel(labEnd);
}
private static void EmitNonNullableToNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked, ILocalCache locals)
{
Debug.Assert(!typeFrom.IsNullableType());
Debug.Assert(typeTo.IsNullableType());
Type nnTypeTo = typeTo.GetNonNullableType();
il.EmitConvertToType(typeFrom, nnTypeTo, isChecked, locals);
ConstructorInfo ci = typeTo.GetConstructor(new Type[] { nnTypeTo });
il.Emit(OpCodes.Newobj, ci);
}
private static void EmitNullableToNonNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked, ILocalCache locals)
{
Debug.Assert(typeFrom.IsNullableType());
Debug.Assert(!typeTo.IsNullableType());
if (typeTo.IsValueType)
il.EmitNullableToNonNullableStructConversion(typeFrom, typeTo, isChecked, locals);
else
il.EmitNullableToReferenceConversion(typeFrom);
}
private static void EmitNullableToNonNullableStructConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked, ILocalCache locals)
{
Debug.Assert(typeFrom.IsNullableType());
Debug.Assert(!typeTo.IsNullableType());
Debug.Assert(typeTo.IsValueType);
LocalBuilder locFrom = locals.GetLocal(typeFrom);
il.Emit(OpCodes.Stloc, locFrom);
il.Emit(OpCodes.Ldloca, locFrom);
locals.FreeLocal(locFrom);
il.EmitGetValue(typeFrom);
Type nnTypeFrom = typeFrom.GetNonNullableType();
il.EmitConvertToType(nnTypeFrom, typeTo, isChecked, locals);
}
private static void EmitNullableToReferenceConversion(this ILGenerator il, Type typeFrom)
{
Debug.Assert(typeFrom.IsNullableType());
// We've got a conversion from nullable to Object, ValueType, Enum, etc. Just box it so that
// we get the nullable semantics.
il.Emit(OpCodes.Box, typeFrom);
}
private static void EmitNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked, ILocalCache locals)
{
bool isTypeFromNullable = typeFrom.IsNullableType();
bool isTypeToNullable = typeTo.IsNullableType();
Debug.Assert(isTypeFromNullable || isTypeToNullable);
if (isTypeFromNullable && isTypeToNullable)
il.EmitNullableToNullableConversion(typeFrom, typeTo, isChecked, locals);
else if (isTypeFromNullable)
il.EmitNullableToNonNullableConversion(typeFrom, typeTo, isChecked, locals);
else
il.EmitNonNullableToNullableConversion(typeFrom, typeTo, isChecked, locals);
}
internal static void EmitHasValue(this ILGenerator il, Type nullableType)
{
MethodInfo mi = nullableType.GetMethod("get_HasValue", BindingFlags.Instance | BindingFlags.Public);
Debug.Assert(nullableType.IsValueType);
il.Emit(OpCodes.Call, mi);
}
internal static void EmitGetValue(this ILGenerator il, Type nullableType)
{
MethodInfo mi = nullableType.GetMethod("get_Value", BindingFlags.Instance | BindingFlags.Public);
Debug.Assert(nullableType.IsValueType);
il.Emit(OpCodes.Call, mi);
}
internal static void EmitGetValueOrDefault(this ILGenerator il, Type nullableType)
{
MethodInfo mi = nullableType.GetMethod("GetValueOrDefault", System.Type.EmptyTypes);
Debug.Assert(nullableType.IsValueType);
il.Emit(OpCodes.Call, mi);
}
#endregion
#region Arrays
#if FEATURE_COMPILE_TO_METHODBUILDER
/// <summary>
/// Emits an array of constant values provided in the given array.
/// The array is strongly typed.
/// </summary>
internal static void EmitArray<T>(this ILGenerator il, T[] items, ILocalCache locals)
{
Debug.Assert(items != null);
il.EmitPrimitive(items.Length);
il.Emit(OpCodes.Newarr, typeof(T));
for (int i = 0; i < items.Length; i++)
{
il.Emit(OpCodes.Dup);
il.EmitPrimitive(i);
il.TryEmitConstant(items[i], typeof(T), locals);
il.EmitStoreElement(typeof(T));
}
}
#endif
/// <summary>
/// Emits an array of values of count size.
/// </summary>
internal static void EmitArray(this ILGenerator il, Type elementType, int count)
{
Debug.Assert(elementType != null);
Debug.Assert(count >= 0);
il.EmitPrimitive(count);
il.Emit(OpCodes.Newarr, elementType);
}
/// <summary>
/// Emits an array construction code.
/// The code assumes that bounds for all dimensions
/// are already emitted.
/// </summary>
internal static void EmitArray(this ILGenerator il, Type arrayType)
{
Debug.Assert(arrayType != null);
Debug.Assert(arrayType.IsArray);
if (arrayType.IsSZArray)
{
il.Emit(OpCodes.Newarr, arrayType.GetElementType());
}
else
{
Type[] types = new Type[arrayType.GetArrayRank()];
for (int i = 0; i < types.Length; i++)
{
types[i] = typeof(int);
}
ConstructorInfo ci = arrayType.GetConstructor(types);
Debug.Assert(ci != null);
il.EmitNew(ci);
}
}
#endregion
#region Support for emitting constants
private static void EmitDecimal(this ILGenerator il, decimal value)
{
int[] bits = decimal.GetBits(value);
int scale = (bits[3] & int.MaxValue) >> 16;
if (scale == 0)
{
if (int.MinValue <= value)
{
if (value <= int.MaxValue)
{
int intValue = decimal.ToInt32(value);
switch (intValue)
{
case -1:
il.Emit(OpCodes.Ldsfld, Decimal_MinusOne);
return;
case 0:
il.EmitDefault(typeof(decimal), locals: null); // locals won't be used.
return;
case 1:
il.Emit(OpCodes.Ldsfld, Decimal_One);
return;
default:
il.EmitPrimitive(intValue);
il.EmitNew(Decimal_Ctor_Int32);
return;
}
}
if (value <= uint.MaxValue)
{
il.EmitPrimitive(decimal.ToUInt32(value));
il.EmitNew(Decimal_Ctor_UInt32);
return;
}
}
if (long.MinValue <= value)
{
if (value <= long.MaxValue)
{
il.EmitPrimitive(decimal.ToInt64(value));
il.EmitNew(Decimal_Ctor_Int64);
return;
}
if (value <= ulong.MaxValue)
{
il.EmitPrimitive(decimal.ToUInt64(value));
il.EmitNew(Decimal_Ctor_UInt64);
return;
}
if (value == decimal.MaxValue)
{
il.Emit(OpCodes.Ldsfld, Decimal_MaxValue);
return;
}
}
else if (value == decimal.MinValue)
{
il.Emit(OpCodes.Ldsfld, Decimal_MinValue);
return;
}
}
il.EmitPrimitive(bits[0]);
il.EmitPrimitive(bits[1]);
il.EmitPrimitive(bits[2]);
il.EmitPrimitive((bits[3] & 0x80000000) != 0);
il.EmitPrimitive(unchecked((byte)scale));
il.EmitNew(Decimal_Ctor_Int32_Int32_Int32_Bool_Byte);
}
/// <summary>
/// Emits default(T)
/// Semantics match C# compiler behavior
/// </summary>
internal static void EmitDefault(this ILGenerator il, Type type, ILocalCache locals)
{
switch (type.GetTypeCode())
{
case TypeCode.DateTime:
il.Emit(OpCodes.Ldsfld, DateTime_MinValue);
break;
case TypeCode.Object:
if (type.IsValueType)
{
// Type.GetTypeCode on an enum returns the underlying
// integer TypeCode, so we won't get here.
Debug.Assert(!type.IsEnum);
// This is the IL for default(T) if T is a generic type
// parameter, so it should work for any type. It's also
// the standard pattern for structs.
LocalBuilder lb = locals.GetLocal(type);
il.Emit(OpCodes.Ldloca, lb);
il.Emit(OpCodes.Initobj, type);
il.Emit(OpCodes.Ldloc, lb);
locals.FreeLocal(lb);
break;
}
goto case TypeCode.Empty;
case TypeCode.Empty:
case TypeCode.String:
case TypeCode.DBNull:
il.Emit(OpCodes.Ldnull);
break;
case TypeCode.Boolean:
case TypeCode.Char:
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
il.Emit(OpCodes.Ldc_I4_0);
break;
case TypeCode.Int64:
case TypeCode.UInt64:
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Conv_I8);
break;
case TypeCode.Single:
il.Emit(OpCodes.Ldc_R4, default(float));
break;
case TypeCode.Double:
il.Emit(OpCodes.Ldc_R8, default(double));
break;
case TypeCode.Decimal:
il.Emit(OpCodes.Ldsfld, Decimal_Zero);
break;
default:
throw ContractUtils.Unreachable;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using LibGit2Sharp.Core;
using LibGit2Sharp.Core.Handles;
namespace LibGit2Sharp
{
/// <summary>
/// Show changes between the working tree and the index or a tree, changes between the index and a tree, changes between two trees, or changes between two files on disk.
/// <para>
/// Copied and renamed files currently cannot be detected, as the feature is not supported by libgit2 yet.
/// These files will be shown as a pair of Deleted/Added files.</para>
/// </summary>
public class Diff
{
private readonly Repository repo;
private static GitDiffOptions BuildOptions(DiffModifiers diffOptions, FilePath[] filePaths = null, MatchedPathsAggregator matchedPathsAggregator = null, CompareOptions compareOptions = null)
{
var options = new GitDiffOptions();
options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_TYPECHANGE;
compareOptions = compareOptions ?? new CompareOptions();
options.ContextLines = (ushort)compareOptions.ContextLines;
options.InterhunkLines = (ushort)compareOptions.InterhunkLines;
if (diffOptions.HasFlag(DiffModifiers.IncludeUntracked))
{
options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_UNTRACKED |
GitDiffOptionFlags.GIT_DIFF_RECURSE_UNTRACKED_DIRS |
GitDiffOptionFlags.GIT_DIFF_SHOW_UNTRACKED_CONTENT;
}
if (diffOptions.HasFlag(DiffModifiers.IncludeIgnored))
{
options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_IGNORED |
GitDiffOptionFlags.GIT_DIFF_RECURSE_IGNORED_DIRS;
}
if (diffOptions.HasFlag(DiffModifiers.IncludeUnmodified) || compareOptions.IncludeUnmodified ||
(compareOptions.Similarity != null &&
(compareOptions.Similarity.RenameDetectionMode == RenameDetectionMode.CopiesHarder ||
compareOptions.Similarity.RenameDetectionMode == RenameDetectionMode.Exact)))
{
options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_UNMODIFIED;
}
if (compareOptions.Algorithm == DiffAlgorithm.Patience)
{
options.Flags |= GitDiffOptionFlags.GIT_DIFF_PATIENCE;
}
if (diffOptions.HasFlag(DiffModifiers.DisablePathspecMatch))
{
options.Flags |= GitDiffOptionFlags.GIT_DIFF_DISABLE_PATHSPEC_MATCH;
}
if (matchedPathsAggregator != null)
{
options.NotifyCallback = matchedPathsAggregator.OnGitDiffNotify;
}
if (filePaths != null)
{
options.PathSpec = GitStrArrayManaged.BuildFrom(filePaths);
}
return options;
}
/// <summary>
/// Needed for mocking purposes.
/// </summary>
protected Diff()
{ }
internal Diff(Repository repo)
{
this.repo = repo;
}
private static readonly IDictionary<DiffTargets, Func<Repository, TreeComparisonHandleRetriever>> HandleRetrieverDispatcher = BuildHandleRetrieverDispatcher();
private static IDictionary<DiffTargets, Func<Repository, TreeComparisonHandleRetriever>> BuildHandleRetrieverDispatcher()
{
return new Dictionary<DiffTargets, Func<Repository, TreeComparisonHandleRetriever>>
{
{ DiffTargets.Index, IndexToTree },
{ DiffTargets.WorkingDirectory, WorkdirToTree },
{ DiffTargets.Index | DiffTargets.WorkingDirectory, WorkdirAndIndexToTree },
};
}
private static readonly IDictionary<Type, Func<DiffSafeHandle, object>> ChangesBuilders = new Dictionary<Type, Func<DiffSafeHandle, object>>
{
{ typeof(Patch), diff => new Patch(diff) },
{ typeof(TreeChanges), diff => new TreeChanges(diff) },
{ typeof(PatchStats), diff => new PatchStats(diff) },
};
private static T BuildDiffResult<T>(DiffSafeHandle diff) where T : class, IDiffResult
{
Func<DiffSafeHandle, object> builder;
if (!ChangesBuilders.TryGetValue(typeof(T), out builder))
{
throw new LibGit2SharpException(CultureInfo.InvariantCulture,
"User-defined types passed to Compare are not supported. Supported values are: {0}",
string.Join(", ", ChangesBuilders.Keys.Select(x => x.Name)));
}
return (T)builder(diff);
}
/// <summary>
/// Show changes between two <see cref="Blob"/>s.
/// </summary>
/// <param name="oldBlob">The <see cref="Blob"/> you want to compare from.</param>
/// <param name="newBlob">The <see cref="Blob"/> you want to compare to.</param>
/// <returns>A <see cref="ContentChanges"/> containing the changes between the <paramref name="oldBlob"/> and the <paramref name="newBlob"/>.</returns>
public virtual ContentChanges Compare(Blob oldBlob, Blob newBlob)
{
return Compare(oldBlob, newBlob, null);
}
/// <summary>
/// Show changes between two <see cref="Blob"/>s.
/// </summary>
/// <param name="oldBlob">The <see cref="Blob"/> you want to compare from.</param>
/// <param name="newBlob">The <see cref="Blob"/> you want to compare to.</param>
/// <param name="compareOptions">Additional options to define comparison behavior.</param>
/// <returns>A <see cref="ContentChanges"/> containing the changes between the <paramref name="oldBlob"/> and the <paramref name="newBlob"/>.</returns>
public virtual ContentChanges Compare(Blob oldBlob, Blob newBlob, CompareOptions compareOptions)
{
using (GitDiffOptions options = BuildOptions(DiffModifiers.None, compareOptions: compareOptions))
{
return new ContentChanges(repo, oldBlob, newBlob, options);
}
}
/// <summary>
/// Show changes between two <see cref="Tree"/>s.
/// </summary>
/// <param name="oldTree">The <see cref="Tree"/> you want to compare from.</param>
/// <param name="newTree">The <see cref="Tree"/> you want to compare to.</param>
/// <returns>A <see cref="TreeChanges"/> containing the changes between the <paramref name="oldTree"/> and the <paramref name="newTree"/>.</returns>
public virtual T Compare<T>(Tree oldTree, Tree newTree) where T : class, IDiffResult
{
return Compare<T>(oldTree, newTree, null, null, null);
}
/// <summary>
/// Show changes between two <see cref="Tree"/>s.
/// </summary>
/// <param name="oldTree">The <see cref="Tree"/> you want to compare from.</param>
/// <param name="newTree">The <see cref="Tree"/> you want to compare to.</param>
/// <param name="paths">The list of paths (either files or directories) that should be compared.</param>
/// <returns>A <see cref="TreeChanges"/> containing the changes between the <paramref name="oldTree"/> and the <paramref name="newTree"/>.</returns>
public virtual T Compare<T>(Tree oldTree, Tree newTree, IEnumerable<string> paths) where T : class, IDiffResult
{
return Compare<T>(oldTree, newTree, paths, null, null);
}
/// <summary>
/// Show changes between two <see cref="Tree"/>s.
/// </summary>
/// <param name="oldTree">The <see cref="Tree"/> you want to compare from.</param>
/// <param name="newTree">The <see cref="Tree"/> you want to compare to.</param>
/// <param name="paths">The list of paths (either files or directories) that should be compared.</param>
/// <param name="explicitPathsOptions">
/// If set, the passed <paramref name="paths"/> will be treated as explicit paths.
/// Use these options to determine how unmatched explicit paths should be handled.
/// </param>
/// <returns>A <see cref="TreeChanges"/> containing the changes between the <paramref name="oldTree"/> and the <paramref name="newTree"/>.</returns>
public virtual T Compare<T>(Tree oldTree, Tree newTree, IEnumerable<string> paths,
ExplicitPathsOptions explicitPathsOptions) where T : class, IDiffResult
{
return Compare<T>(oldTree, newTree, paths, explicitPathsOptions, null);
}
/// <summary>
/// Show changes between two <see cref="Tree"/>s.
/// </summary>
/// <param name="oldTree">The <see cref="Tree"/> you want to compare from.</param>
/// <param name="newTree">The <see cref="Tree"/> you want to compare to.</param>
/// <param name="paths">The list of paths (either files or directories) that should be compared.</param>
/// <param name="compareOptions">Additional options to define patch generation behavior.</param>
/// <returns>A <see cref="TreeChanges"/> containing the changes between the <paramref name="oldTree"/> and the <paramref name="newTree"/>.</returns>
public virtual T Compare<T>(Tree oldTree, Tree newTree, IEnumerable<string> paths, CompareOptions compareOptions) where T : class, IDiffResult
{
return Compare<T>(oldTree, newTree, paths, null, compareOptions);
}
/// <summary>
/// Show changes between two <see cref="Tree"/>s.
/// </summary>
/// <param name="oldTree">The <see cref="Tree"/> you want to compare from.</param>
/// <param name="newTree">The <see cref="Tree"/> you want to compare to.</param>
/// <param name="compareOptions">Additional options to define patch generation behavior.</param>
/// <returns>A <see cref="TreeChanges"/> containing the changes between the <paramref name="oldTree"/> and the <paramref name="newTree"/>.</returns>
public virtual T Compare<T>(Tree oldTree, Tree newTree, CompareOptions compareOptions) where T : class, IDiffResult
{
return Compare<T>(oldTree, newTree, null, null, compareOptions);
}
/// <summary>
/// Show changes between two <see cref="Tree"/>s.
/// </summary>
/// <param name="oldTree">The <see cref="Tree"/> you want to compare from.</param>
/// <param name="newTree">The <see cref="Tree"/> you want to compare to.</param>
/// <param name="paths">The list of paths (either files or directories) that should be compared.</param>
/// <param name="explicitPathsOptions">
/// If set, the passed <paramref name="paths"/> will be treated as explicit paths.
/// Use these options to determine how unmatched explicit paths should be handled.
/// </param>
/// <param name="compareOptions">Additional options to define patch generation behavior.</param>
/// <returns>A <see cref="TreeChanges"/> containing the changes between the <paramref name="oldTree"/> and the <paramref name="newTree"/>.</returns>
public virtual T Compare<T>(Tree oldTree, Tree newTree, IEnumerable<string> paths, ExplicitPathsOptions explicitPathsOptions,
CompareOptions compareOptions) where T : class, IDiffResult
{
var comparer = TreeToTree(repo);
ObjectId oldTreeId = oldTree != null ? oldTree.Id : null;
ObjectId newTreeId = newTree != null ? newTree.Id : null;
var diffOptions = DiffModifiers.None;
if (explicitPathsOptions != null)
{
diffOptions |= DiffModifiers.DisablePathspecMatch;
if (explicitPathsOptions.ShouldFailOnUnmatchedPath || explicitPathsOptions.OnUnmatchedPath != null)
{
diffOptions |= DiffModifiers.IncludeUnmodified;
}
}
using (DiffSafeHandle diff = BuildDiffList(oldTreeId, newTreeId, comparer, diffOptions, paths, explicitPathsOptions, compareOptions))
{
return BuildDiffResult<T>(diff);
}
}
/// <summary>
/// Show changes between a <see cref="Tree"/> and the Index, the Working Directory, or both.
/// <para>
/// The level of diff performed can be specified by passing either a <see cref="TreeChanges"/>
/// or <see cref="Patch"/> type as the generic parameter.
/// </para>
/// </summary>
/// <param name="oldTree">The <see cref="Tree"/> to compare from.</param>
/// <param name="diffTargets">The targets to compare to.</param>
/// <typeparam name="T">Can be either a <see cref="TreeChanges"/> if you are only interested in the list of files modified, added, ..., or
/// a <see cref="Patch"/> if you want the actual patch content for the whole diff and for individual files.</typeparam>
/// <returns>A <typeparamref name="T"/> containing the changes between the <see cref="Tree"/> and the selected target.</returns>
public virtual T Compare<T>(Tree oldTree, DiffTargets diffTargets) where T : class, IDiffResult
{
return Compare<T>(oldTree, diffTargets, null, null, null);
}
/// <summary>
/// Show changes between a <see cref="Tree"/> and the Index, the Working Directory, or both.
/// <para>
/// The level of diff performed can be specified by passing either a <see cref="TreeChanges"/>
/// or <see cref="Patch"/> type as the generic parameter.
/// </para>
/// </summary>
/// <param name="oldTree">The <see cref="Tree"/> to compare from.</param>
/// <param name="diffTargets">The targets to compare to.</param>
/// <param name="paths">The list of paths (either files or directories) that should be compared.</param>
/// <typeparam name="T">Can be either a <see cref="TreeChanges"/> if you are only interested in the list of files modified, added, ..., or
/// a <see cref="Patch"/> if you want the actual patch content for the whole diff and for individual files.</typeparam>
/// <returns>A <typeparamref name="T"/> containing the changes between the <see cref="Tree"/> and the selected target.</returns>
public virtual T Compare<T>(Tree oldTree, DiffTargets diffTargets, IEnumerable<string> paths) where T : class, IDiffResult
{
return Compare<T>(oldTree, diffTargets, paths, null, null);
}
/// <summary>
/// Show changes between a <see cref="Tree"/> and the Index, the Working Directory, or both.
/// <para>
/// The level of diff performed can be specified by passing either a <see cref="TreeChanges"/>
/// or <see cref="Patch"/> type as the generic parameter.
/// </para>
/// </summary>
/// <param name="oldTree">The <see cref="Tree"/> to compare from.</param>
/// <param name="diffTargets">The targets to compare to.</param>
/// <param name="paths">The list of paths (either files or directories) that should be compared.</param>
/// <param name="explicitPathsOptions">
/// If set, the passed <paramref name="paths"/> will be treated as explicit paths.
/// Use these options to determine how unmatched explicit paths should be handled.
/// </param>
/// <typeparam name="T">Can be either a <see cref="TreeChanges"/> if you are only interested in the list of files modified, added, ..., or
/// a <see cref="Patch"/> if you want the actual patch content for the whole diff and for individual files.</typeparam>
/// <returns>A <typeparamref name="T"/> containing the changes between the <see cref="Tree"/> and the selected target.</returns>
public virtual T Compare<T>(Tree oldTree, DiffTargets diffTargets, IEnumerable<string> paths,
ExplicitPathsOptions explicitPathsOptions) where T : class, IDiffResult
{
return Compare<T>(oldTree, diffTargets, paths, explicitPathsOptions, null);
}
/// <summary>
/// Show changes between a <see cref="Tree"/> and the Index, the Working Directory, or both.
/// <para>
/// The level of diff performed can be specified by passing either a <see cref="TreeChanges"/>
/// or <see cref="Patch"/> type as the generic parameter.
/// </para>
/// </summary>
/// <param name="oldTree">The <see cref="Tree"/> to compare from.</param>
/// <param name="diffTargets">The targets to compare to.</param>
/// <param name="paths">The list of paths (either files or directories) that should be compared.</param>
/// <param name="explicitPathsOptions">
/// If set, the passed <paramref name="paths"/> will be treated as explicit paths.
/// Use these options to determine how unmatched explicit paths should be handled.
/// </param>
/// <param name="compareOptions">Additional options to define patch generation behavior.</param>
/// <typeparam name="T">Can be either a <see cref="TreeChanges"/> if you are only interested in the list of files modified, added, ..., or
/// a <see cref="Patch"/> if you want the actual patch content for the whole diff and for individual files.</typeparam>
/// <returns>A <typeparamref name="T"/> containing the changes between the <see cref="Tree"/> and the selected target.</returns>
public virtual T Compare<T>(Tree oldTree, DiffTargets diffTargets, IEnumerable<string> paths,
ExplicitPathsOptions explicitPathsOptions, CompareOptions compareOptions) where T : class, IDiffResult
{
var comparer = HandleRetrieverDispatcher[diffTargets](repo);
ObjectId oldTreeId = oldTree != null ? oldTree.Id : null;
DiffModifiers diffOptions = diffTargets.HasFlag(DiffTargets.WorkingDirectory)
? DiffModifiers.IncludeUntracked
: DiffModifiers.None;
if (explicitPathsOptions != null)
{
diffOptions |= DiffModifiers.DisablePathspecMatch;
if (explicitPathsOptions.ShouldFailOnUnmatchedPath || explicitPathsOptions.OnUnmatchedPath != null)
{
diffOptions |= DiffModifiers.IncludeUnmodified;
}
}
using (DiffSafeHandle diff = BuildDiffList(oldTreeId, null, comparer, diffOptions, paths, explicitPathsOptions, compareOptions))
{
return BuildDiffResult<T>(diff);
}
}
/// <summary>
/// Show changes between the working directory and the index.
/// <para>
/// The level of diff performed can be specified by passing either a <see cref="TreeChanges"/>
/// or <see cref="Patch"/> type as the generic parameter.
/// </para>
/// </summary>
/// <typeparam name="T">Can be either a <see cref="TreeChanges"/> if you are only interested in the list of files modified, added, ..., or
/// a <see cref="Patch"/> if you want the actual patch content for the whole diff and for individual files.</typeparam>
/// <returns>A <typeparamref name="T"/> containing the changes between the working directory and the index.</returns>
public virtual T Compare<T>() where T : class, IDiffResult
{
return Compare<T>(DiffModifiers.None);
}
/// <summary>
/// Show changes between the working directory and the index.
/// <para>
/// The level of diff performed can be specified by passing either a <see cref="TreeChanges"/>
/// or <see cref="Patch"/> type as the generic parameter.
/// </para>
/// </summary>
/// <param name="paths">The list of paths (either files or directories) that should be compared.</param>
/// <typeparam name="T">Can be either a <see cref="TreeChanges"/> if you are only interested in the list of files modified, added, ..., or
/// a <see cref="Patch"/> if you want the actual patch content for the whole diff and for individual files.</typeparam>
/// <returns>A <typeparamref name="T"/> containing the changes between the working directory and the index.</returns>
public virtual T Compare<T>(IEnumerable<string> paths) where T : class, IDiffResult
{
return Compare<T>(DiffModifiers.None, paths);
}
/// <summary>
/// Show changes between the working directory and the index.
/// <para>
/// The level of diff performed can be specified by passing either a <see cref="TreeChanges"/>
/// or <see cref="Patch"/> type as the generic parameter.
/// </para>
/// </summary>
/// <param name="paths">The list of paths (either files or directories) that should be compared.</param>
/// <param name="includeUntracked">If true, include untracked files from the working dir as additions. Otherwise ignore them.</param>
/// <typeparam name="T">Can be either a <see cref="TreeChanges"/> if you are only interested in the list of files modified, added, ..., or
/// a <see cref="Patch"/> if you want the actual patch content for the whole diff and for individual files.</typeparam>
/// <returns>A <typeparamref name="T"/> containing the changes between the working directory and the index.</returns>
public virtual T Compare<T>(IEnumerable<string> paths, bool includeUntracked) where T : class, IDiffResult
{
return Compare<T>(includeUntracked ? DiffModifiers.IncludeUntracked : DiffModifiers.None, paths);
}
/// <summary>
/// Show changes between the working directory and the index.
/// <para>
/// The level of diff performed can be specified by passing either a <see cref="TreeChanges"/>
/// or <see cref="Patch"/> type as the generic parameter.
/// </para>
/// </summary>
/// <param name="paths">The list of paths (either files or directories) that should be compared.</param>
/// <param name="includeUntracked">If true, include untracked files from the working dir as additions. Otherwise ignore them.</param>
/// <param name="explicitPathsOptions">
/// If set, the passed <paramref name="paths"/> will be treated as explicit paths.
/// Use these options to determine how unmatched explicit paths should be handled.
/// </param>
/// <typeparam name="T">Can be either a <see cref="TreeChanges"/> if you are only interested in the list of files modified, added, ..., or
/// a <see cref="Patch"/> if you want the actual patch content for the whole diff and for individual files.</typeparam>
/// <returns>A <typeparamref name="T"/> containing the changes between the working directory and the index.</returns>
public virtual T Compare<T>(IEnumerable<string> paths, bool includeUntracked, ExplicitPathsOptions explicitPathsOptions) where T : class, IDiffResult
{
return Compare<T>(includeUntracked ? DiffModifiers.IncludeUntracked : DiffModifiers.None, paths, explicitPathsOptions);
}
/// <summary>
/// Show changes between the working directory and the index.
/// <para>
/// The level of diff performed can be specified by passing either a <see cref="TreeChanges"/>
/// or <see cref="Patch"/> type as the generic parameter.
/// </para>
/// </summary>
/// <param name="paths">The list of paths (either files or directories) that should be compared.</param>
/// <param name="includeUntracked">If true, include untracked files from the working dir as additions. Otherwise ignore them.</param>
/// <param name="explicitPathsOptions">
/// If set, the passed <paramref name="paths"/> will be treated as explicit paths.
/// Use these options to determine how unmatched explicit paths should be handled.
/// </param>
/// <param name="compareOptions">Additional options to define patch generation behavior.</param>
/// <typeparam name="T">Can be either a <see cref="TreeChanges"/> if you are only interested in the list of files modified, added, ..., or
/// a <see cref="Patch"/> if you want the actual patch content for the whole diff and for individual files.</typeparam>
/// <returns>A <typeparamref name="T"/> containing the changes between the working directory and the index.</returns>
public virtual T Compare<T>(
IEnumerable<string> paths,
bool includeUntracked,
ExplicitPathsOptions explicitPathsOptions,
CompareOptions compareOptions) where T : class, IDiffResult
{
return Compare<T>(includeUntracked ? DiffModifiers.IncludeUntracked : DiffModifiers.None, paths, explicitPathsOptions, compareOptions);
}
internal virtual T Compare<T>(
DiffModifiers diffOptions,
IEnumerable<string> paths = null,
ExplicitPathsOptions explicitPathsOptions = null,
CompareOptions compareOptions = null) where T : class, IDiffResult
{
var comparer = WorkdirToIndex(repo);
if (explicitPathsOptions != null)
{
diffOptions |= DiffModifiers.DisablePathspecMatch;
if (explicitPathsOptions.ShouldFailOnUnmatchedPath || explicitPathsOptions.OnUnmatchedPath != null)
{
diffOptions |= DiffModifiers.IncludeUnmodified;
}
}
using (DiffSafeHandle diff = BuildDiffList(null, null, comparer, diffOptions, paths, explicitPathsOptions, compareOptions))
{
return BuildDiffResult<T>(diff);
}
}
internal delegate DiffSafeHandle TreeComparisonHandleRetriever(ObjectId oldTreeId, ObjectId newTreeId, GitDiffOptions options);
private static TreeComparisonHandleRetriever TreeToTree(Repository repo)
{
return (oh, nh, o) => Proxy.git_diff_tree_to_tree(repo.Handle, oh, nh, o);
}
private static TreeComparisonHandleRetriever WorkdirToIndex(Repository repo)
{
return (oh, nh, o) => Proxy.git_diff_index_to_workdir(repo.Handle, repo.Index.Handle, o);
}
private static TreeComparisonHandleRetriever WorkdirToTree(Repository repo)
{
return (oh, nh, o) => Proxy.git_diff_tree_to_workdir(repo.Handle, oh, o);
}
private static TreeComparisonHandleRetriever WorkdirAndIndexToTree(Repository repo)
{
TreeComparisonHandleRetriever comparisonHandleRetriever = (oh, nh, o) =>
{
DiffSafeHandle diff = Proxy.git_diff_tree_to_index(repo.Handle, repo.Index.Handle, oh, o);
using (DiffSafeHandle diff2 = Proxy.git_diff_index_to_workdir(repo.Handle, repo.Index.Handle, o))
{
Proxy.git_diff_merge(diff, diff2);
}
return diff;
};
return comparisonHandleRetriever;
}
private static TreeComparisonHandleRetriever IndexToTree(Repository repo)
{
return (oh, nh, o) => Proxy.git_diff_tree_to_index(repo.Handle, repo.Index.Handle, oh, o);
}
private DiffSafeHandle BuildDiffList(
ObjectId oldTreeId,
ObjectId newTreeId,
TreeComparisonHandleRetriever comparisonHandleRetriever,
DiffModifiers diffOptions,
IEnumerable<string> paths,
ExplicitPathsOptions explicitPathsOptions,
CompareOptions compareOptions)
{
var matchedPaths = new MatchedPathsAggregator();
var filePaths = repo.ToFilePaths(paths);
using (GitDiffOptions options = BuildOptions(diffOptions, filePaths, matchedPaths, compareOptions))
{
var diffList = comparisonHandleRetriever(oldTreeId, newTreeId, options);
if (explicitPathsOptions != null)
{
try
{
DispatchUnmatchedPaths(explicitPathsOptions, filePaths, matchedPaths);
}
catch
{
diffList.Dispose();
throw;
}
}
DetectRenames(diffList, compareOptions);
return diffList;
}
}
private static void DetectRenames(DiffSafeHandle diffList, CompareOptions compareOptions)
{
var similarityOptions = (compareOptions == null) ? null : compareOptions.Similarity;
if (similarityOptions == null || similarityOptions.RenameDetectionMode == RenameDetectionMode.Default)
{
Proxy.git_diff_find_similar(diffList, null);
return;
}
if (similarityOptions.RenameDetectionMode == RenameDetectionMode.None)
{
return;
}
var opts = new GitDiffFindOptions
{
RenameThreshold = (ushort)similarityOptions.RenameThreshold,
RenameFromRewriteThreshold = (ushort)similarityOptions.RenameFromRewriteThreshold,
CopyThreshold = (ushort)similarityOptions.CopyThreshold,
BreakRewriteThreshold = (ushort)similarityOptions.BreakRewriteThreshold,
RenameLimit = (UIntPtr)similarityOptions.RenameLimit,
};
switch (similarityOptions.RenameDetectionMode)
{
case RenameDetectionMode.Exact:
opts.Flags = GitDiffFindFlags.GIT_DIFF_FIND_EXACT_MATCH_ONLY |
GitDiffFindFlags.GIT_DIFF_FIND_RENAMES |
GitDiffFindFlags.GIT_DIFF_FIND_COPIES |
GitDiffFindFlags.GIT_DIFF_FIND_COPIES_FROM_UNMODIFIED;
break;
case RenameDetectionMode.Renames:
opts.Flags = GitDiffFindFlags.GIT_DIFF_FIND_RENAMES;
break;
case RenameDetectionMode.Copies:
opts.Flags = GitDiffFindFlags.GIT_DIFF_FIND_RENAMES |
GitDiffFindFlags.GIT_DIFF_FIND_COPIES;
break;
case RenameDetectionMode.CopiesHarder:
opts.Flags = GitDiffFindFlags.GIT_DIFF_FIND_RENAMES |
GitDiffFindFlags.GIT_DIFF_FIND_COPIES |
GitDiffFindFlags.GIT_DIFF_FIND_COPIES_FROM_UNMODIFIED;
break;
}
if (!compareOptions.IncludeUnmodified)
{
opts.Flags |= GitDiffFindFlags.GIT_DIFF_FIND_REMOVE_UNMODIFIED;
}
switch (similarityOptions.WhitespaceMode)
{
case WhitespaceMode.DontIgnoreWhitespace:
opts.Flags |= GitDiffFindFlags.GIT_DIFF_FIND_DONT_IGNORE_WHITESPACE;
break;
case WhitespaceMode.IgnoreLeadingWhitespace:
opts.Flags |= GitDiffFindFlags.GIT_DIFF_FIND_IGNORE_LEADING_WHITESPACE;
break;
case WhitespaceMode.IgnoreAllWhitespace:
opts.Flags |= GitDiffFindFlags.GIT_DIFF_FIND_IGNORE_WHITESPACE;
break;
}
Proxy.git_diff_find_similar(diffList, opts);
}
private static void DispatchUnmatchedPaths(
ExplicitPathsOptions explicitPathsOptions,
IEnumerable<FilePath> filePaths,
IEnumerable<FilePath> matchedPaths)
{
List<FilePath> unmatchedPaths = (filePaths != null ?
filePaths.Except(matchedPaths) : Enumerable.Empty<FilePath>()).ToList();
if (!unmatchedPaths.Any())
{
return;
}
if (explicitPathsOptions.OnUnmatchedPath != null)
{
unmatchedPaths.ForEach(filePath => explicitPathsOptions.OnUnmatchedPath(filePath.Native));
}
if (explicitPathsOptions.ShouldFailOnUnmatchedPath)
{
throw new UnmatchedPathException(BuildUnmatchedPathsMessage(unmatchedPaths));
}
}
private static string BuildUnmatchedPathsMessage(List<FilePath> unmatchedPaths)
{
var message = new StringBuilder("There were some unmatched paths:" + Environment.NewLine);
unmatchedPaths.ForEach(filePath => message.AppendFormat("- {0}{1}", filePath.Native, Environment.NewLine));
return message.ToString();
}
}
}
| |
// ------------------------------------------------------------------------------
// <copyright from='2002' to='2002' company='Scott Hanselman'>
// Copyright (c) Scott Hanselman. All Rights Reserved.
// </copyright>
// ------------------------------------------------------------------------------
//
// Scott Hanselman's Tiny Academic Virtual CPU and OS
// Copyright (c) 2002, Scott Hanselman (scott@hanselman.com)
// All rights reserved.
//
// A BSD License
// 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 Scott Hanselman nor the names of its contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
// BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Text.RegularExpressions;
namespace Hanselman.CST352
{
/// <summary>
/// Represents a single line in a program, consisting of an <see cref="OpCode"/>
/// and one or two optional parameters. An instruction can parse a raw instruction from a test file.
/// Tge instruction is then loaded into an <see cref="InstructionCollection"/> which is a member of
/// <see cref="Program"/>. The <see cref="InstructionCollection"/> is translated into bytes that are
/// loaded into the processes memory space. It's never used again, but it's a neat overly object oriented
/// construct that simplified the coding of the creation of a <see cref="Program"/> and complicated the
/// running of the whole system. It was worth it though.
/// </summary>
public class Instruction
{
/// <summary>
/// Overridden method for pretty printing of Instructions
/// </summary>
/// <returns>A formatted string representing an Instruction</returns>
public override string ToString()
{
return String.Format("OpCode: {0,-2:G} {1,-12:G} Param1: {2,4:G} Param2: {3,4:G}", (byte)this.OpCode, this.OpCode, this.Param1 == uint.MaxValue? "" :this.Param1.ToString(),this.Param2 == uint.MaxValue ? "" :this.Param2.ToString());
}
/// <summary>
/// The OpCode for this Instruction
/// </summary>
public InstructionType OpCode;
/// <summary>
/// The first parameter to the opCode. May be a Constant or a Register value, or not used at all
/// </summary>
public uint Param1 = uint.MaxValue;
/// <summary>
/// The second parameter to the opCode. May be a Constant or a Register value, or not used at all
/// </summary>
public uint Param2 = uint.MaxValue;
/// <summary>
/// Public constructor for an Instruction
/// </summary>
/// <param name="rawInstruction">A raw string from a Program File.</param>
/// <example>Any one of the following lines is a valid rawInstruction
/// <pre>
/// 1 r1 ; incr r1
/// 2 r6, $16 ; add 16 to r6
/// 26 r6 ; setPriority to r6
/// 2 r2, $5 ; increment r2 by 5
/// 3 r1, r2 ; add 1 and 2 and the result goes in 1
/// 2 r2, $5 ; increment r2 by 5
/// 6 r3, $99 ; move 99 into r3
/// 7 r4, r3 ; move r3 into r4
/// 11 r4 ; print r4
/// 27 ; this is exit.
/// </pre>
/// </example>
public Instruction(string rawInstruction)
{
Regex r = new Regex("(?:;.+)|\\A(?<opcode>\\d+){1}|\\sr(?<param>[-]*\\d)|\\$(?<const>[-]*\\d+)");
MatchCollection matchcol = r.Matches(rawInstruction);
foreach(Match m in matchcol)
{
GroupCollection g = m.Groups;
for (int i = 1; i < g.Count ; i++)
{
if (g[i].Value.Length != 0 )
{
if (r.GroupNameFromNumber(i) == "opcode")
{
this.OpCode = (InstructionType)byte.Parse(g[i].Value);
}
if (r.GroupNameFromNumber(i) == "param" || r.GroupNameFromNumber(i) == "const")
{
//Yank them as ints (to preserve signed-ness)
// Treat them as uints for storage
// This will only affect negative numbers, and
// VERY large unsigned numbers
if (uint.MaxValue == this.Param1)
this.Param1 = uint.Parse(g[i].Value);
else if (uint.MaxValue == this.Param2)
{
if (g[i].Value[0] == '-')
this.Param2 = (uint)int.Parse(g[i].Value);
else
this.Param2 = uint.Parse(g[i].Value);
}
}
}
}
}
}
}
/// <summary>
/// This enum provides an easy conversion between numerical opCodes like "2" and text
/// and easy to remember consts like "Addi"
/// </summary>
public enum InstructionType
{
/// <summary>
/// No op
/// </summary>
Noop = 0,
/// <summary>
/// Increments register
/// <pre>
/// 1 r1
/// </pre>
/// </summary>
Incr,
/// <summary>
/// Adds constant 1 to register 1
/// <pre>
/// 2 r1, $1
/// </pre>
/// </summary>
Addi,
/// <summary>
/// Adds r2 to r1 and stores the value in r1
/// <pre>
/// 3 r1, r2
/// </pre>
/// </summary>
Addr,
/// <summary>
/// Pushes contents of register 1 onto stack
/// <pre>
/// 4 r1
/// </pre>
/// </summary>
Pushr,
/// <summary>
/// Pushes constant 1 onto stack
/// <pre>
/// 5 $1
/// </pre>
/// </summary>
Pushi,
/// <summary>
/// Moves constant 1 into register 1
/// <pre>
/// 6 r1, $1
/// </pre>
/// </summary>
Movi,
/// <summary>
/// Moves contents of register2 into register 1
/// <pre>
/// 7 r1, r2
/// </pre>
/// </summary>
Movr,
/// <summary>
/// Moves contents of memory pointed to register 2 into register 1
/// <pre>
/// 8 r1, r2
/// </pre>
/// </summary>
Movmr,
/// <summary>
/// Moves contents of register 2 into memory pointed to by register 1
/// <pre>
/// 9 r1, r2
/// </pre>
/// </summary>
Movrm,
/// <summary>
/// Moves contents of memory pointed to by register 2 into memory pointed to by register 1
/// <pre>
/// 10 r1, r2
/// </pre>
/// </summary>
Movmm,
/// <summary>
/// Prints out contents of register 1
/// <pre>
/// 11 r1
/// </pre>
/// </summary>
Printr,
/// <summary>
/// Prints out contents of memory pointed to by register 1
/// <pre>
/// 12 r1
/// </pre>
/// </summary>
Printm,
/// <summary>
/// Control transfers to the instruction whose address is r1 bytes relative to the current instruction.
/// r1 may be negative.
/// <pre>
/// 13 r1
/// </pre>
/// </summary>
Jmp,
/// <summary>
/// Compare contents of r1 with 1. If r1 < 9 set sign flag. If r1 > 9 clear sign flag.
/// If r1 == 9 set zero flag.
/// <pre>
/// 14 r1, $9
/// </pre>
/// </summary>
Cmpi,
/// <summary>
/// Compare contents of r1 with r2. If r1 < r2 set sign flag. If r1 > r2 clear sign flag.
/// If r1 == r2 set zero flag.
/// <pre>
/// 15 r1, r2
/// </pre>
/// </summary>
Cmpr,
/// <summary>
/// If the sign flag is set, jump to the instruction that is offset r1 bytes from the current instruction
/// <pre>
/// 16 r1
/// </pre>
/// </summary>
Jlt,
/// <summary>
/// If the sign flag is clear, jump to the instruction that is offset r1 bytes from the current instruction
/// <pre>
/// 17 r1
/// </pre>
/// </summary>
Jgt,
/// <summary>
/// If the zero flag is set, jump to the instruction that is offset r1 bytes from the current instruction
/// <pre>
/// 18 r1
/// </pre>
/// </summary>
Je,
/// <summary>
/// Call the procedure at offset r1 bytes from the current instrucion.
/// The address of the next instruction to excetute after a return is pushed on the stack
/// <pre>
/// 19 r1
/// </pre>
/// </summary>
Call,
/// <summary>
/// Call the procedure at offset of the bytes in memory pointed by r1 from the current instrucion.
/// The address of the next instruction to excetute after a return is pushed on the stack
/// <pre>
/// 20 r1
/// </pre>
/// </summary>
Callm,
/// <summary>
/// Pop the return address from the stack and transfer control to this instruction
/// <pre>
/// 21
/// </pre>
/// </summary>
Ret,
/// <summary>
/// Allocate memory of the size equal to r1 bytes and return the address of the new memory in r2.
/// If failed, r2 is cleared to 0.
/// <pre>
/// 22 r1, r2
/// </pre>
/// </summary>
Alloc,
/// <summary>
/// Acquire the OS lock whose # is provided in register r1.
/// Icf the lock is not held by the current process
/// the operation is a no-op
/// <pre>
/// 23 r1
/// </pre>
/// </summary>
AcquireLock,
/// <summary>
/// Release the OS lock whose # is provided in register r1.
/// Another process or the idle process
/// must be scheduled at this point.
/// if the lock is not held by the current process,
/// the instruction is a no-op
/// <pre>
/// 24 r1
/// </pre>
/// </summary>
ReleaseLock,
/// <summary>
/// Sleep the # of clock cycles as indicated in r1.
/// Another process or the idle process
/// must be scheduled at this point.
/// If the time to sleep is 0, the process sleeps infinitely
/// <pre>
/// 25 r1
/// </pre>
/// </summary>
Sleep,
/// <summary>
/// Set the priority of the current process to the value
/// in register r1
/// <pre>
/// 26 r1
/// </pre>
/// </summary>
SetPriority,
/// <summary>
/// This opcode causes an exit and the process's memory to be unloaded.
/// Another process or the idle process must now be scheduled
/// <pre>
/// 27
/// </pre>
/// </summary>
Exit,
/// <summary>
/// Free the memory allocated whose address is in r1
/// <pre>
/// 28 r1
/// </pre>
/// </summary>
FreeMemory,
/// <summary>
/// Map the shared memory region identified by r1 and return the start address in r2
/// <pre>
/// 29 r1, r2
/// </pre>
/// </summary>
MapSharedMem,
/// <summary>
/// Signal the event indicated by the value in register r1
/// <pre>
/// 30 r1
/// </pre>
/// </summary>
SignalEvent,
/// <summary>
/// Wait for the event in register r1 to be triggered resulting in a context-switch
/// <pre>
/// 31 r1
/// </pre>
/// </summary>
WaitEvent,
/// <summary>
/// Read the next 32-bit value into register r1
/// <pre>
/// 32 r1
/// </pre>
/// </summary>
Input,
/// <summary>
/// set the bytes starting at address r1 of length r2 to zero
/// <pre>
/// 33 r1, r2
/// </pre>
/// </summary>
MemoryClear,
/// <summary>
/// Terminate the process whose id is in the register r1
/// <pre>
/// 34 r1
/// </pre>
/// </summary>
TerminateProcess,
/// <summary>
/// Pop the contents at the top of the stack into register r1
/// <pre>
/// 35 r1
/// </pre>
/// </summary>
Popr,
/// <summary>
/// Pop the contents at the top of the stack into the memory pointed to by register r1
/// <pre>
/// 36 r1
/// </pre>
/// </summary>
Popm
};
}
| |
#if !UNITY_WINRT || UNITY_EDITOR || (UNITY_WP8 && !UNITY_WP_8_1)
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Formatters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
using System.Runtime.Serialization;
using System.Security;
using UnityEngine;
#if (UNITY_IPHONE || UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII)
using Newtonsoft.Json.Aot;
#endif
namespace Newtonsoft.Json.Serialization
{
internal class JsonSerializerInternalWriter : JsonSerializerInternalBase
{
private JsonSerializerProxy _internalSerializer;
private List<object> _serializeStack;
private List<object> SerializeStack
{
get
{
if (_serializeStack == null)
_serializeStack = new List<object>();
return _serializeStack;
}
}
public JsonSerializerInternalWriter(JsonSerializer serializer)
: base(serializer)
{
}
public void Serialize(JsonWriter jsonWriter, object value)
{
if (jsonWriter == null)
throw new ArgumentNullException("jsonWriter");
SerializeValue(jsonWriter, value, GetContractSafe(value), null, null);
}
private JsonSerializerProxy GetInternalSerializer()
{
if (_internalSerializer == null)
_internalSerializer = new JsonSerializerProxy(this);
return _internalSerializer;
}
private JsonContract GetContractSafe(object value)
{
if (value == null)
return null;
return Serializer.ContractResolver.ResolveContract(value.GetType());
}
private void SerializePrimitive(JsonWriter writer, object value, JsonPrimitiveContract contract, JsonProperty member, JsonContract collectionValueContract)
{
if (contract.UnderlyingType == typeof(byte[]))
{
bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionValueContract);
if (includeTypeDetails)
{
writer.WriteStartObject();
WriteTypeProperty(writer, contract.CreatedType);
writer.WritePropertyName(JsonTypeReflector.ValuePropertyName);
writer.WriteValue(value);
writer.WriteEndObject();
return;
}
}
writer.WriteValue(value);
}
private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContract collectionValueContract)
{
JsonConverter converter = (member != null) ? member.Converter : null;
if (value == null)
{
writer.WriteNull();
return;
}
if ((converter != null
|| ((converter = valueContract.Converter) != null)
|| ((converter = Serializer.GetMatchingConverter(valueContract.UnderlyingType)) != null)
|| ((converter = valueContract.InternalConverter) != null))
&& converter.CanWrite)
{
SerializeConvertable(writer, converter, value, valueContract);
}
else if (valueContract is JsonPrimitiveContract)
{
SerializePrimitive(writer, value, (JsonPrimitiveContract)valueContract, member, collectionValueContract);
}
else if (valueContract is JsonStringContract)
{
SerializeString(writer, value, (JsonStringContract)valueContract);
}
else if (valueContract is JsonObjectContract)
{
SerializeObject(writer, value, (JsonObjectContract)valueContract, member, collectionValueContract);
}
else if (valueContract is JsonDictionaryContract)
{
JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)valueContract;
SerializeDictionary(writer, dictionaryContract.CreateWrapper(value), dictionaryContract, member, collectionValueContract);
}
else if (valueContract is JsonArrayContract)
{
JsonArrayContract arrayContract = (JsonArrayContract)valueContract;
if (!arrayContract.IsMultidimensionalArray)
SerializeList(writer, arrayContract.CreateWrapper(value), arrayContract, member, collectionValueContract);
else
SerializeMultidimensionalArray(writer, (Array)value, arrayContract, member, collectionValueContract);
}
else if (valueContract is JsonLinqContract)
{
((JToken)value).WriteTo(writer, (Serializer.Converters != null) ? Serializer.Converters.ToArray() : null);
}
#if !((UNITY_WINRT && !UNITY_EDITOR) || (UNITY_WP8 || UNITY_WP_8_1))
else if (valueContract is JsonISerializableContract)
{
SerializeISerializable(writer, (ISerializable)value, (JsonISerializableContract)valueContract);
}
#endif
}
private bool ShouldWriteReference(object value, JsonProperty property, JsonContract contract)
{
if (value == null)
return false;
if (contract is JsonPrimitiveContract)
return false;
bool? isReference = null;
// value could be coming from a dictionary or array and not have a property
if (property != null)
isReference = property.IsReference;
if (isReference == null)
isReference = contract.IsReference;
if (isReference == null)
{
if (contract is JsonArrayContract)
isReference = HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Arrays);
else
isReference = HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Objects);
}
if (!isReference.Value)
return false;
return Serializer.ReferenceResolver.IsReferenced(this, value);
}
private void WriteMemberInfoProperty(JsonWriter writer, object memberValue, JsonProperty property, JsonContract contract)
{
string propertyName = property.PropertyName;
object defaultValue = property.DefaultValue;
if (property.NullValueHandling.GetValueOrDefault(Serializer.NullValueHandling) == NullValueHandling.Ignore &&
memberValue == null)
return;
if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer.DefaultValueHandling), DefaultValueHandling.Ignore)
&& MiscellaneousUtils.ValueEquals(memberValue, defaultValue))
return;
if (ShouldWriteReference(memberValue, property, contract))
{
writer.WritePropertyName(propertyName);
WriteReference(writer, memberValue);
return;
}
if (!CheckForCircularReference(memberValue, property.ReferenceLoopHandling, contract))
return;
if (memberValue == null && property.Required == Required.Always)
throw new JsonSerializationException("Cannot write a null value for property '{0}'. Property requires a value.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName));
writer.WritePropertyName(propertyName);
SerializeValue(writer, memberValue, contract, property, null);
}
private bool CheckForCircularReference(object value, ReferenceLoopHandling? referenceLoopHandling, JsonContract contract)
{
if (value == null || contract is JsonPrimitiveContract)
return true;
if (SerializeStack.IndexOf(value) != -1)
{
var selfRef = (value is Vector2 || value is Vector3 || value is Vector4 || value is Color || value is Color32)
? ReferenceLoopHandling.Ignore
: referenceLoopHandling.GetValueOrDefault(Serializer.ReferenceLoopHandling);
switch (selfRef)
{
case ReferenceLoopHandling.Error:
throw new JsonSerializationException("Self referencing loop detected for type '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
case ReferenceLoopHandling.Ignore:
return false;
case ReferenceLoopHandling.Serialize:
return true;
default:
throw new InvalidOperationException("Unexpected ReferenceLoopHandling value: '{0}'".FormatWith(CultureInfo.InvariantCulture, Serializer.ReferenceLoopHandling));
}
}
return true;
}
private void WriteReference(JsonWriter writer, object value)
{
writer.WriteStartObject();
writer.WritePropertyName(JsonTypeReflector.RefPropertyName);
writer.WriteValue(Serializer.ReferenceResolver.GetReference(this, value));
writer.WriteEndObject();
}
internal static bool TryConvertToString(object value, Type type, out string s)
{
#if !(UNITY_WP8 || UNITY_WP_8_1)
TypeConverter converter = ConvertUtils.GetConverter(type);
// use the objectType's TypeConverter if it has one and can convert to a string
if (converter != null
#if !(UNITY_WP8 || UNITY_WP_8_1)
&& !(converter is ComponentConverter)
#endif
&& converter.GetType() != typeof(TypeConverter))
{
if (converter.CanConvertTo(typeof(string)))
{
#if !(UNITY_WP8 || UNITY_WP_8_1)
s = converter.ConvertToInvariantString(value);
#else
s = converter.ConvertToString(value);
#endif
return true;
}
}
#endif
#if (UNITY_WP8 || UNITY_WP_8_1)
if (value is Guid || value is Uri || value is TimeSpan)
{
s = value.ToString();
return true;
}
#endif
if (value is Type)
{
s = ((Type)value).AssemblyQualifiedName;
return true;
}
s = null;
return false;
}
private void SerializeString(JsonWriter writer, object value, JsonStringContract contract)
{
contract.InvokeOnSerializing(value, Serializer.Context);
string s;
TryConvertToString(value, contract.UnderlyingType, out s);
writer.WriteValue(s);
contract.InvokeOnSerialized(value, Serializer.Context);
}
private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract, JsonProperty member, JsonContract collectionValueContract)
{
contract.InvokeOnSerializing(value, Serializer.Context);
SerializeStack.Add(value);
writer.WriteStartObject();
bool isReference = contract.IsReference ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Objects);
if (isReference)
{
writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
writer.WriteValue(Serializer.ReferenceResolver.GetReference(this, value));
}
if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionValueContract))
{
WriteTypeProperty(writer, contract.UnderlyingType);
}
int initialDepth = writer.Top;
foreach (JsonProperty property in contract.Properties)
{
try
{
if (!property.Ignored && property.Readable && ShouldSerialize(property, value) && IsSpecified(property, value))
{
object memberValue = property.ValueProvider.GetValue(value);
JsonContract memberContract = GetContractSafe(memberValue);
WriteMemberInfoProperty(writer, memberValue, property, memberContract);
}
}
catch (Exception ex)
{
if (IsErrorHandled(value, contract, property.PropertyName, ex))
HandleError(writer, initialDepth);
else
throw;
}
}
writer.WriteEndObject();
SerializeStack.RemoveAt(SerializeStack.Count - 1);
contract.InvokeOnSerialized(value, Serializer.Context);
}
private void WriteTypeProperty(JsonWriter writer, Type type)
{
writer.WritePropertyName(JsonTypeReflector.TypePropertyName);
writer.WriteValue(ReflectionUtils.GetTypeName(type, Serializer.TypeNameAssemblyFormat, Serializer.Binder));
}
private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag)
{
return ((value & flag) == flag);
}
private bool HasFlag(PreserveReferencesHandling value, PreserveReferencesHandling flag)
{
return ((value & flag) == flag);
}
private bool HasFlag(TypeNameHandling value, TypeNameHandling flag)
{
return ((value & flag) == flag);
}
private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value, JsonContract contract)
{
if (ShouldWriteReference(value, null, contract))
{
WriteReference(writer, value);
}
else
{
if (!CheckForCircularReference(value, null, contract))
return;
SerializeStack.Add(value);
converter.WriteJson(writer, value, GetInternalSerializer());
SerializeStack.RemoveAt(SerializeStack.Count - 1);
}
}
private void SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContract collectionValueContract)
{
contract.InvokeOnSerializing(values.UnderlyingCollection, Serializer.Context);
SerializeStack.Add(values.UnderlyingCollection);
bool isReference = contract.IsReference ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Arrays);
bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Arrays, contract, member, collectionValueContract);
if (isReference || includeTypeDetails)
{
writer.WriteStartObject();
if (isReference)
{
writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
writer.WriteValue(Serializer.ReferenceResolver.GetReference(this, values.UnderlyingCollection));
}
if (includeTypeDetails)
{
WriteTypeProperty(writer, values.UnderlyingCollection.GetType());
}
writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName);
}
JsonContract childValuesContract = Serializer.ContractResolver.ResolveContract(contract.CollectionItemType ?? typeof(object));
writer.WriteStartArray();
int initialDepth = writer.Top;
int index = 0;
// note that an error in the IEnumerable won't be caught
#if !(UNITY_IPHONE || UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII) || (UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII && !(UNITY_3_5 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3))
foreach (object value in values)
{
try
{
JsonContract valueContract = GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract))
{
WriteReference(writer, value);
}
else
{
if (CheckForCircularReference(value, null, contract))
{
SerializeValue(writer, value, valueContract, null, childValuesContract);
}
}
}
catch (Exception ex)
{
if (IsErrorHandled(values.UnderlyingCollection, contract, index, ex))
HandleError(writer, initialDepth);
else
throw;
}
finally
{
index++;
}
}
#else
values.ForEach(value =>
{
try
{
JsonContract valueContract = GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract))
{
WriteReference(writer, value);
}
else
{
if (CheckForCircularReference(value, null, contract))
{
SerializeValue(writer, value, valueContract, null, childValuesContract);
}
}
}
catch (Exception ex)
{
if (IsErrorHandled(values.UnderlyingCollection, contract, index, ex))
HandleError(writer, initialDepth);
else
throw;
}
finally
{
index++;
}
});
#endif
writer.WriteEndArray();
if (isReference || includeTypeDetails)
{
writer.WriteEndObject();
}
SerializeStack.RemoveAt(SerializeStack.Count - 1);
contract.InvokeOnSerialized(values.UnderlyingCollection, Serializer.Context);
}
private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, JsonContract collectionContract)
{
contract.InvokeOnSerializing(values, Serializer.Context);
_serializeStack.Add(values);
bool hasWrittenMetadataObject = WriteStartArray(writer, values, contract, member, collectionContract);
SerializeMultidimensionalArray(writer, values, contract, member, writer.Top, new int[0]);
if (hasWrittenMetadataObject)
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
contract.InvokeOnSerialized(values, Serializer.Context);
}
private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, int initialDepth, int[] indices)
{
int dimension = indices.Length;
int[] newIndices = new int[dimension + 1];
for (int i = 0; i < dimension; i++)
{
newIndices[i] = indices[i];
}
writer.WriteStartArray();
for (int i = 0; i < values.GetLength(dimension); i++)
{
newIndices[dimension] = i;
bool isTopLevel = (newIndices.Length == values.Rank);
if (isTopLevel)
{
object value = values.GetValue(newIndices);
try
{
JsonContract valueContract = GetContractSafe(value);
if (ShouldWriteReference(value, member, valueContract))
{
WriteReference(writer, value);
}
else
{
if (CheckForCircularReference(value, null, valueContract))
{
SerializeValue(writer, value, valueContract, member, contract);
}
}
}
catch (Exception ex)
{
if (IsErrorHandled(values, contract, i, ex))
HandleError(writer, initialDepth + 1);
else
throw;
}
}
else
{
SerializeMultidimensionalArray(writer, values, contract, member, initialDepth + 1, newIndices);
}
}
writer.WriteEndArray();
}
private string GetReference(JsonWriter writer, object value)
{
try
{
string reference = Serializer.ReferenceResolver.GetReference(this, value);
return reference;
}
catch (Exception ex)
{
throw new JsonSerializationException("Error writing object reference for '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), ex);
}
}
private bool WriteStartArray(JsonWriter writer, object values, JsonArrayContract contract, JsonProperty member, JsonContract containerContract)
{
bool isReference = contract.IsReference ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Arrays);
bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Arrays, contract, member, containerContract);
bool writeMetadataObject = isReference || includeTypeDetails;
if (writeMetadataObject)
{
writer.WriteStartObject();
if (isReference)
{
writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
writer.WriteValue(GetReference(writer, values));
}
if (includeTypeDetails)
{
WriteTypeProperty(writer, values.GetType());
}
writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName);
}
/*if (contract.ItemContract == null)
contract.ItemContract = Serializer.ContractResolver.ResolveContract(contract.CollectionItemType ?? typeof(object));
*/
return writeMetadataObject;
}
#if !((UNITY_WINRT && !UNITY_EDITOR) || (UNITY_WP8 || UNITY_WP_8_1))
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1903:UseOnlyApiFromTargetedFramework", MessageId = "System.Security.SecuritySafeCriticalAttribute")]
[SecuritySafeCritical]
private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract)
{
contract.InvokeOnSerializing(value, Serializer.Context);
SerializeStack.Add(value);
writer.WriteStartObject();
SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter());
value.GetObjectData(serializationInfo, Serializer.Context);
foreach (SerializationEntry serializationEntry in serializationInfo)
{
writer.WritePropertyName(serializationEntry.Name);
SerializeValue(writer, serializationEntry.Value, GetContractSafe(serializationEntry.Value), null, null);
}
writer.WriteEndObject();
SerializeStack.RemoveAt(SerializeStack.Count - 1);
contract.InvokeOnSerialized(value, Serializer.Context);
}
#endif
private bool ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract contract, JsonProperty member, JsonContract collectionValueContract)
{
if (HasFlag(((member != null) ? member.TypeNameHandling : null) ?? Serializer.TypeNameHandling, typeNameHandlingFlag))
return true;
if (member != null)
{
if ((member.TypeNameHandling ?? Serializer.TypeNameHandling) == TypeNameHandling.Auto
// instance and property type are different
&& contract.UnderlyingType != member.PropertyType)
{
JsonContract memberTypeContract = Serializer.ContractResolver.ResolveContract(member.PropertyType);
// instance type and the property's type's contract default type are different (no need to put the type in JSON because the type will be created by default)
if (contract.UnderlyingType != memberTypeContract.CreatedType)
return true;
}
}
else if (collectionValueContract != null)
{
if (Serializer.TypeNameHandling == TypeNameHandling.Auto && contract.UnderlyingType != collectionValueContract.UnderlyingType)
return true;
}
return false;
}
private void SerializeDictionary(JsonWriter writer, IWrappedDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContract collectionValueContract)
{
contract.InvokeOnSerializing(values.UnderlyingDictionary, Serializer.Context);
SerializeStack.Add(values.UnderlyingDictionary);
writer.WriteStartObject();
bool isReference = contract.IsReference ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Objects);
if (isReference)
{
writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
writer.WriteValue(Serializer.ReferenceResolver.GetReference(this, values.UnderlyingDictionary));
}
if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionValueContract))
{
WriteTypeProperty(writer, values.UnderlyingDictionary.GetType());
}
JsonContract childValuesContract = Serializer.ContractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));
int initialDepth = writer.Top;
// Mono Unity 3.0 fix
IDictionary d = values;
foreach (DictionaryEntry entry in d)
{
string propertyName = GetPropertyName(entry);
propertyName = (contract.PropertyNameResolver != null)
? contract.PropertyNameResolver(propertyName)
: propertyName;
try
{
object value = entry.Value;
JsonContract valueContract = GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract))
{
writer.WritePropertyName(propertyName);
WriteReference(writer, value);
}
else
{
if (!CheckForCircularReference(value, null, contract))
continue;
writer.WritePropertyName(propertyName);
SerializeValue(writer, value, valueContract, null, childValuesContract);
}
}
catch (Exception ex)
{
if (IsErrorHandled(values.UnderlyingDictionary, contract, propertyName, ex))
HandleError(writer, initialDepth);
else
throw;
}
}
writer.WriteEndObject();
SerializeStack.RemoveAt(SerializeStack.Count - 1);
contract.InvokeOnSerialized(values.UnderlyingDictionary, Serializer.Context);
}
private string GetPropertyName(DictionaryEntry entry)
{
string propertyName;
if (entry.Key is IConvertible)
return Convert.ToString(entry.Key, CultureInfo.InvariantCulture);
else if (TryConvertToString(entry.Key, entry.Key.GetType(), out propertyName))
return propertyName;
else
return entry.Key.ToString();
}
private void HandleError(JsonWriter writer, int initialDepth)
{
ClearErrorContext();
while (writer.Top > initialDepth)
{
writer.WriteEnd();
}
}
private bool ShouldSerialize(JsonProperty property, object target)
{
if (property.ShouldSerialize == null)
return true;
return property.ShouldSerialize(target);
}
private bool IsSpecified(JsonProperty property, object target)
{
if (property.GetIsSpecified == null)
return true;
return property.GetIsSpecified(target);
}
}
}
#endif
| |
//==============================================================================
// TorqueLab -> TerrainMaterialManager
// Copyright (c) 2015 All Right Reserved, http://nordiklab.com/
//------------------------------------------------------------------------------
//==============================================================================
//==============================================================================
// TerrainObject Functions
//==============================================================================
//==============================================================================
// Manage the terrain name
//==============================================================================
//==============================================================================
// Sync the current profile values into the params objects
function TMG::applyTerrainName( %this ) {
%newName = TMG_ActiveTerrainNameEdit.getText();
if (%newName $= TMG.activeTerrain.getName())
return;
if (isObject(%newName)) {
warnLog("There's already an object using that name:",%newName);
return;
}
TMG.activeTerrain.setName(%newName);
TMG.setActiveTerrain(TMG.activeTerrain);
}
//------------------------------------------------------------------------------
//==============================================================================
// Sync the current profile values into the params objects
function TMG_ActiveTerrainNameEdit::onValidate( %this ) {
%newName = TMG_ActiveTerrainNameEdit.getText();
if (%newName $= TMG.activeTerrain.getName()) {
TMG_ActiveTerrainNameApply.active = 0;
return;
}
TMG_ActiveTerrainNameApply.active = 1;
}
//------------------------------------------------------------------------------
//==============================================================================
// Manage the terrain file
//==============================================================================
//==============================================================================
// Sync the current profile values into the params objects
function TMG::relocateTerrainFile( %this ) {
%newFile = TMG_ActiveTerrainFileEdit.getText();
if (%newFile $= TMG.activeTerrain.terrainFile) {
TMG_ActiveTerrainFileApply.active = 0;
return;
}
%fileBase = fileBase(%newFile);
%filePath = filePath(%newFile);
%file = %filePath@"/"@%fileBase@".ter";
TMG.saveTerrain(TMG.activeTerrain,%file);
}
//------------------------------------------------------------------------------
//==============================================================================
function TMG::saveTerrain(%this,%obj,%file) {
if (%obj $= "")
%obj = TMG.activeTerrain;
if (!isObject(%obj))
return;
if (%file $= "")
%file = addFilenameToPath(filePath(MissionGroup.getFileName()),%obj.getName(),"ter");
%obj.save(%file);
TMG.schedule(500,"updateTerrainFile",%obj,%file);
devLog("Terrain:",%obj.getName(),"Saved to",%file);
}
//------------------------------------------------------------------------------
//==============================================================================
function TMG::updateTerrainFile(%this,%obj,%file) {
if (!isObject(%obj))
return;
%obj.setFieldValue("terrainFile",%file);
devLog("Terrain:",%obj.getName(),"terrainFileSet to",%file);
}
//------------------------------------------------------------------------------
//==============================================================================
// Sync the current profile values into the params objects
function TMG::getTerrainFile( %this ) {
%currentFile = TMG.activeTerrain.terrainFile;
//Canvas.cursorOff();
getLoadFilename("*.*|*.*", "TMG.setTerrainFile", %currentFile);
}
//------------------------------------------------------------------------------
//==============================================================================
// Sync the current profile values into the params objects
function TMG::setTerrainFile( %this,%file ) {
%fileBase = fileBase(%file);
%filePath = filePath(%file);
%newFile = %filePath@"/"@%fileBase@".ter";
%filename = makeRelativePath( %newFile, getMainDotCsDir() );
TMG.saveTerrain(TMG.activeTerrain, %filename);
//%this.updateTerrainField("terrainFile",%filename);
}
//------------------------------------------------------------------------------
//==============================================================================
function TMG::updateTerrainField(%this,%field,%value) {
%terrain = TMG.activeTerrain;
%terrain.setFieldValue(%field,%value);
}
//------------------------------------------------------------------------------
//==============================================================================
// Terrain Layers Functions
//==============================================================================
//==============================================================================
function TMG::updateTerrainLayers(%this,%clearOnly) {
TMG_TerrainLayerStack.clear();
hide(TMG_TerrainLayerPill);
show(TMG_TerrainLayerStack);
if (%clearOnly)
return;
%mats = ETerrainEditor.getMaterials();
for( %i = 0; %i < getRecordCount( %mats ); %i++ ) {
%matInternalName = getRecord( %mats, %i );
%mat = TerrainMaterialSet.findObjectByInternalName( %matInternalName );
%pill = cloneObject(TMG_TerrainLayerPill);
%pill.matObj = %mat;
%pill.layerId = %i;
%pill.internalName = "Layer_"@%i;
%pill-->materialName.text = "Material:\c1" SPC %mat.internalName;
%pill-->materialMouse.pill = %pill;
%pill-->materialMouse.superClass = "TMG_GeneralMaterialMouse";
%pill-->materialMouse.callback = "TMG_GeneralMaterialChangeCallback";
TMG_TerrainLayerStack.add(%pill);
}
}
//------------------------------------------------------------------------------
function TMG_GeneralMaterialMouse::onMouseDown(%this,%modifier,%mousePoint,%mouseClickCount) {
if (%mouseClickCount > 1) {
TMG.showGeneralMaterialDlg(%this.pill);
}
}
//==============================================================================
function TMG::showGeneralMaterialDlg( %this,%pill ) {
if (!isObject(%pill)) {
warnLog("Invalid layer to change material");
return;
}
if (%callback $= "")
%callback = "TMG_LayerMaterialChangeCallback";
%mat = %pill.matObj;
TMG.changeMaterialPill = %pill;
TMG.changeMaterialLive = %directUpdate;
TerrainMaterialDlg.show( %pill.layerId, %mat,TMG_GeneralMaterialChangeCallback );
}
//------------------------------------------------------------------------------
//==============================================================================
// Callback from TerrainMaterialDlg returning selected material info
function TMG_GeneralMaterialChangeCallback( %mat, %matIndex, %activeIdx ) {
TMG_LayerMaterialChangeCallback(%mat, %matIndex, %activeIdx );
EPainter_TerrainMaterialUpdateCallback(%mat, %matIndex);
}
//------------------------------------------------------------------------------
//==============================================================================
function TMG::importLayerTextureMap(%this,%matInternalName) {
}
//------------------------------------------------------------------------------
//==============================================================================
function TMG::exportLayerTextureMap(%this,%matInternalName) {
}
//------------------------------------------------------------------------------
//==============================================================================
// TMG.getTerrainHeightRange
function TMG::getTerrainHeightRange( %this ) {
%heightRange = ETerrainEditor.getHeightRange();
return %heightRange;
}
//------------------------------------------------------------------------------
//==============================================================================
/*
new TerrainBlock(TerrainTile_x0y0) {
terrainFile = "art/Levels/Demo/MiniTerrain/MiniTerrainDemo.ter";
castShadows = "1";
squareSize = "2";
baseTexSize = "256";
baseTexFormat = "JPG";
lightMapSize = "256";
screenError = "16";
position = "-256 -256 0";
rotation = "1 0 0 0";
canSave = "1";
canSaveDynamicFields = "1";
scale = "1 1 1";
tile = "0";
};
*/
| |
//---------------------------------------------------------------------------
//
// <copyright file=TextTreeRootNode.cs company=Microsoft>
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: The root node of a TextContainer.
//
// History:
// 02/18/2004 : [....] - Created
//
//---------------------------------------------------------------------------
using System;
using MS.Internal;
using System.Collections;
using System.Windows.Threading;
namespace System.Windows.Documents
{
// All TextContainers contain a single TextTreeRootNode, which contains all other
// nodes. The root node is special because it contains tree-global data,
// and TextPositions may never reference its BeforeStart/AfterEnd edges.
// Because of the restrictions on TextPointer, the root node may never
// be removed from the tree.
internal class TextTreeRootNode : TextTreeNode
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
// Creates a TextTreeRootNode instance.
internal TextTreeRootNode(TextContainer tree)
{
_tree = tree;
#if REFCOUNT_DEAD_TEXTPOINTERS
_deadPositionList = new ArrayList(0);
#endif // REFCOUNT_DEAD_TEXTPOINTERS
// Root node has two imaginary element edges to match TextElementNode semantics.
_symbolCount = 2;
// CaretUnitBoundaryCache always starts unset.
_caretUnitBoundaryCacheOffset = -1;
}
#endregion Constructors
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
#if DEBUG
// Debug-only ToString override.
public override string ToString()
{
return ("RootNode Id=" + this.DebugId + " SymbolCount=" + _symbolCount);
}
#endif // DEBUG
#endregion Public Methods
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
// Returns a shallow copy of this node.
// This should never be called for the root node, since it is never
// involved in delete operations.
internal override TextTreeNode Clone()
{
Invariant.Assert(false, "Unexpected call to TextTreeRootNode.Clone!");
return null;
}
// Returns the TextPointerContext of the node.
// If node is TextTreeTextElementNode, this method returns ElementStart
// if direction == Forward, otherwise ElementEnd if direction == Backward.
internal override TextPointerContext GetPointerContext(LogicalDirection direction)
{
// End-of-tree is "None".
return TextPointerContext.None;
}
#endregion Internal methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
// The root node never has a parent node.
internal override SplayTreeNode ParentNode
{
get
{
return null;
}
set
{
Invariant.Assert(false, "Can't set ParentNode on TextContainer root!");
}
}
// Root node of a contained tree, if any.
internal override SplayTreeNode ContainedNode
{
get
{
return _containedNode;
}
set
{
_containedNode = (TextTreeNode)value;
}
}
// The root node never has sibling nodes, so the LeftSymbolCount is a
// constant zero.
internal override int LeftSymbolCount
{
get
{
return 0;
}
set
{
Invariant.Assert(false, "TextContainer root is never a sibling!");
}
}
// The root node never has sibling nodes, so the LeftCharCount is a
// constant zero.
internal override int LeftCharCount
{
get
{
return 0;
}
set
{
Invariant.Assert(false, "TextContainer root is never a sibling!");
}
}
// The root node never has siblings, so it never has child nodes.
internal override SplayTreeNode LeftChildNode
{
get
{
return null;
}
set
{
Invariant.Assert(false, "TextContainer root never has sibling nodes!");
}
}
// The root node never has siblings, so it never has child nodes.
internal override SplayTreeNode RightChildNode
{
get
{
return null;
}
set
{
Invariant.Assert(false, "TextContainer root never has sibling nodes!");
}
}
// The tree generation. Incremented whenever the tree content changes.
internal override uint Generation
{
get
{
return _generation;
}
set
{
_generation = value;
}
}
// Like the Generation property, but this counter is only updated when
// an edit that might affect TextPositions occurs. In practice, inserts
// do not bother TextPositions, but deletions do.
internal uint PositionGeneration
{
get
{
return _positionGeneration;
}
set
{
_positionGeneration = value;
}
}
// Incremeneted whenever a layout property value changes on a TextElement.
internal uint LayoutGeneration
{
get
{
return _layoutGeneration;
}
set
{
_layoutGeneration = value;
// Invalidate the caret unit boundary cache on layout update.
_caretUnitBoundaryCacheOffset = -1;
}
}
// Cached symbol offset. The root node is always at offset zero.
internal override int SymbolOffsetCache
{
get
{
return 0;
}
set
{
Invariant.Assert(value == 0, "Bad SymbolOffsetCache on TextContainer root!");
}
}
// The count of all symbols in the tree, including two edge symbols for
// the root node itself.
internal override int SymbolCount
{
get
{
return _symbolCount;
}
set
{
Invariant.Assert(value >= 2, "Bad _symbolCount on TextContainer root!");
_symbolCount = value;
}
}
// The count of all chars in the tree.
internal override int IMECharCount
{
get
{
return _imeCharCount;
}
set
{
Invariant.Assert(value >= 0, "IMECharCount may never be negative!");
_imeCharCount = value;
}
}
// Count of TextPositions referencing the node's BeforeStart
// edge. We don't bother to actually track this for the root node
// since it is only useful in delete operations and the root node
// is never deleted.
internal override bool BeforeStartReferenceCount
{
get
{
return false;
}
set
{
Invariant.Assert(!value, "Root node BeforeStart edge can never be referenced!");
}
}
// Count of TextPositions referencing the node's AfterStart
// edge. We don't bother to actually track this for the root node
// since it is only useful in delete operations and the root node
// is never deleted.
internal override bool AfterStartReferenceCount
{
get
{
return false;
}
set
{
// We can ignore the value because the TextContainer root is never removed.
}
}
// Count of TextPositions referencing the node's BeforeEnd
// edge. We don't bother to actually track this for the root node
// since it is only useful in delete operations and the root node
// is never deleted.
internal override bool BeforeEndReferenceCount
{
get
{
return false;
}
set
{
// We can ignore the value because the TextContainer root is never removed.
}
}
// Count of TextPositions referencing the node's AfterEnd
// edge. We don't bother to actually track this for the root node
// since it is only useful in delete operations and the root node
// is never deleted.
internal override bool AfterEndReferenceCount
{
get
{
return false;
}
set
{
Invariant.Assert(!value, "Root node AfterEnd edge can never be referenced!");
}
}
// The owning TextContainer.
internal TextContainer TextContainer
{
get
{
return _tree;
}
}
// A tree of TextTreeTextBlocks, used to store raw text for the entire
// tree.
internal TextTreeRootTextBlock RootTextBlock
{
get
{
return _rootTextBlock;
}
set
{
_rootTextBlock = value;
}
}
#if REFCOUNT_DEAD_TEXTPOINTERS
// A list of positions ready to be garbage collected. The TextPointer
// finalizer adds positions to this list.
internal ArrayList DeadPositionList
{
get
{
return _deadPositionList;
}
set
{
_deadPositionList = value;
}
}
#endif // REFCOUNT_DEAD_TEXTPOINTERS
// Structure that allows for dispatcher processing to be
// enabled after a call to Dispatcher.DisableProcessing.
internal DispatcherProcessingDisabled DispatcherProcessingDisabled
{
get
{
return _processingDisabled;
}
set
{
_processingDisabled = value;
}
}
// Cached TextView.IsAtCaretUnitBoundary calculation for CaretUnitBoundaryCacheOffset.
internal bool CaretUnitBoundaryCache
{
get
{
return _caretUnitBoundaryCache;
}
set
{
_caretUnitBoundaryCache = value;
}
}
// Symbol offset of CaretUnitBoundaryCache, or -1 if the cache is empty.
internal int CaretUnitBoundaryCacheOffset
{
get
{
return _caretUnitBoundaryCacheOffset;
}
set
{
_caretUnitBoundaryCacheOffset = value;
}
}
#endregion Internal Properties
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
// The owning TextContainer.
private readonly TextContainer _tree;
// Root node of a contained tree, if any.
private TextTreeNode _containedNode;
// The count of all symbols in the tree, including two edge symbols for
// the root node itself.
private int _symbolCount;
// The count of all chars in the tree.
private int _imeCharCount;
// The tree generation. Incremented whenever the tree content changes.
private uint _generation;
// Like _generation, but only updated when a change could affect positions.
private uint _positionGeneration;
// Like _generation, but only updated when on a TextElement layout property change.
private uint _layoutGeneration;
// A tree of TextTreeTextBlocks, used to store raw text for the entire TextContainer.
private TextTreeRootTextBlock _rootTextBlock;
#if REFCOUNT_DEAD_TEXTPOINTERS
// A list of positions ready to be garbage collected. The TextPointer
// finalizer adds positions to this list.
private ArrayList _deadPositionList;
#endif // REFCOUNT_DEAD_TEXTPOINTERS
// Cached TextView.IsAtCaretUnitBoundary calculation for _caretUnitBoundaryCacheOffset.
private bool _caretUnitBoundaryCache;
// Symbol offset of _caretUnitBoundaryCache, or -1 if the cache is empty.
private int _caretUnitBoundaryCacheOffset;
// Structure that allows for dispatcher processing to be
// enabled after a call to Dispatcher.DisableProcessing.
private DispatcherProcessingDisabled _processingDisabled;
#endregion Private Fields
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
using System.Text;
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
namespace System.Reflection.Emit
{
public sealed class SignatureHelper
{
#region Consts Fields
private const int NO_SIZE_IN_SIG = -1;
#endregion
#region Static Members
public static SignatureHelper GetMethodSigHelper(Module mod, Type returnType, Type[] parameterTypes)
{
return GetMethodSigHelper(mod, CallingConventions.Standard, returnType, null, null, parameterTypes, null, null);
}
internal static SignatureHelper GetMethodSigHelper(Module mod, CallingConventions callingConvention, Type returnType, int cGenericParam)
{
return GetMethodSigHelper(mod, callingConvention, cGenericParam, returnType, null, null, null, null, null);
}
public static SignatureHelper GetMethodSigHelper(Module mod, CallingConventions callingConvention, Type returnType)
{
return GetMethodSigHelper(mod, callingConvention, returnType, null, null, null, null, null);
}
internal static SignatureHelper GetMethodSpecSigHelper(Module scope, Type[] inst)
{
SignatureHelper sigHelp = new SignatureHelper(scope, MdSigCallingConvention.GenericInst);
sigHelp.AddData(inst.Length);
foreach (Type t in inst)
sigHelp.AddArgument(t);
return sigHelp;
}
internal static SignatureHelper GetMethodSigHelper(
Module scope, CallingConventions callingConvention,
Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
{
return GetMethodSigHelper(scope, callingConvention, 0, returnType, requiredReturnTypeCustomModifiers,
optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
}
internal static SignatureHelper GetMethodSigHelper(
Module scope, CallingConventions callingConvention, int cGenericParam,
Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
{
SignatureHelper sigHelp;
MdSigCallingConvention intCall;
if (returnType == null)
{
returnType = typeof(void);
}
intCall = MdSigCallingConvention.Default;
if ((callingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs)
intCall = MdSigCallingConvention.Vararg;
if (cGenericParam > 0)
{
intCall |= MdSigCallingConvention.Generic;
}
if ((callingConvention & CallingConventions.HasThis) == CallingConventions.HasThis)
intCall |= MdSigCallingConvention.HasThis;
sigHelp = new SignatureHelper(scope, intCall, cGenericParam, returnType,
requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers);
sigHelp.AddArguments(parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
return sigHelp;
}
public static SignatureHelper GetMethodSigHelper(Module mod, CallingConvention unmanagedCallConv, Type returnType)
{
SignatureHelper sigHelp;
MdSigCallingConvention intCall;
if (returnType == null)
returnType = typeof(void);
if (unmanagedCallConv == CallingConvention.Cdecl)
{
intCall = MdSigCallingConvention.C;
}
else if (unmanagedCallConv == CallingConvention.StdCall || unmanagedCallConv == CallingConvention.Winapi)
{
intCall = MdSigCallingConvention.StdCall;
}
else if (unmanagedCallConv == CallingConvention.ThisCall)
{
intCall = MdSigCallingConvention.ThisCall;
}
else if (unmanagedCallConv == CallingConvention.FastCall)
{
intCall = MdSigCallingConvention.FastCall;
}
else
{
throw new ArgumentException(Environment.GetResourceString("Argument_UnknownUnmanagedCallConv"), nameof(unmanagedCallConv));
}
sigHelp = new SignatureHelper(mod, intCall, returnType, null, null);
return sigHelp;
}
public static SignatureHelper GetLocalVarSigHelper()
{
return GetLocalVarSigHelper(null);
}
public static SignatureHelper GetMethodSigHelper(CallingConventions callingConvention, Type returnType)
{
return GetMethodSigHelper(null, callingConvention, returnType);
}
public static SignatureHelper GetMethodSigHelper(CallingConvention unmanagedCallingConvention, Type returnType)
{
return GetMethodSigHelper(null, unmanagedCallingConvention, returnType);
}
public static SignatureHelper GetLocalVarSigHelper(Module mod)
{
return new SignatureHelper(mod, MdSigCallingConvention.LocalSig);
}
public static SignatureHelper GetFieldSigHelper(Module mod)
{
return new SignatureHelper(mod, MdSigCallingConvention.Field);
}
public static SignatureHelper GetPropertySigHelper(Module mod, Type returnType, Type[] parameterTypes)
{
return GetPropertySigHelper(mod, returnType, null, null, parameterTypes, null, null);
}
public static SignatureHelper GetPropertySigHelper(Module mod,
Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
{
return GetPropertySigHelper(mod, (CallingConventions)0, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers,
parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
}
public static SignatureHelper GetPropertySigHelper(Module mod, CallingConventions callingConvention,
Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
{
SignatureHelper sigHelp;
if (returnType == null)
{
returnType = typeof(void);
}
MdSigCallingConvention intCall = MdSigCallingConvention.Property;
if ((callingConvention & CallingConventions.HasThis) == CallingConventions.HasThis)
intCall |= MdSigCallingConvention.HasThis;
sigHelp = new SignatureHelper(mod, intCall,
returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers);
sigHelp.AddArguments(parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
return sigHelp;
}
internal static SignatureHelper GetTypeSigToken(Module module, Type type)
{
if (module == null)
throw new ArgumentNullException(nameof(module));
if (type == null)
throw new ArgumentNullException(nameof(type));
return new SignatureHelper(module, type);
}
#endregion
#region Private Data Members
private byte[] m_signature;
private int m_currSig; // index into m_signature buffer for next available byte
private int m_sizeLoc; // index into m_signature buffer to put m_argCount (will be NO_SIZE_IN_SIG if no arg count is needed)
private ModuleBuilder m_module;
private bool m_sigDone;
private int m_argCount; // tracking number of arguments in the signature
#endregion
#region Constructor
private SignatureHelper(Module mod, MdSigCallingConvention callingConvention)
{
// Use this constructor to instantiate a local var sig or Field where return type is not applied.
Init(mod, callingConvention);
}
private SignatureHelper(Module mod, MdSigCallingConvention callingConvention, int cGenericParameters,
Type returnType, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
{
// Use this constructor to instantiate a any signatures that will require a return type.
Init(mod, callingConvention, cGenericParameters);
if (callingConvention == MdSigCallingConvention.Field)
throw new ArgumentException(Environment.GetResourceString("Argument_BadFieldSig"));
AddOneArgTypeHelper(returnType, requiredCustomModifiers, optionalCustomModifiers);
}
private SignatureHelper(Module mod, MdSigCallingConvention callingConvention,
Type returnType, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
: this(mod, callingConvention, 0, returnType, requiredCustomModifiers, optionalCustomModifiers)
{
}
private SignatureHelper(Module mod, Type type)
{
Init(mod);
AddOneArgTypeHelper(type);
}
private void Init(Module mod)
{
m_signature = new byte[32];
m_currSig = 0;
m_module = mod as ModuleBuilder;
m_argCount = 0;
m_sigDone = false;
m_sizeLoc = NO_SIZE_IN_SIG;
if (m_module == null && mod != null)
throw new ArgumentException(Environment.GetResourceString("NotSupported_MustBeModuleBuilder"));
}
private void Init(Module mod, MdSigCallingConvention callingConvention)
{
Init(mod, callingConvention, 0);
}
private void Init(Module mod, MdSigCallingConvention callingConvention, int cGenericParam)
{
Init(mod);
AddData((byte)callingConvention);
if (callingConvention == MdSigCallingConvention.Field ||
callingConvention == MdSigCallingConvention.GenericInst)
{
m_sizeLoc = NO_SIZE_IN_SIG;
}
else
{
if (cGenericParam > 0)
AddData(cGenericParam);
m_sizeLoc = m_currSig++;
}
}
#endregion
#region Private Members
private void AddOneArgTypeHelper(Type argument, bool pinned)
{
if (pinned)
AddElementType(CorElementType.Pinned);
AddOneArgTypeHelper(argument);
}
private void AddOneArgTypeHelper(Type clsArgument, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
{
// This function will not increase the argument count. It only fills in bytes
// in the signature based on clsArgument. This helper is called for return type.
Contract.Requires(clsArgument != null);
Contract.Requires((optionalCustomModifiers == null && requiredCustomModifiers == null) || !clsArgument.ContainsGenericParameters);
if (optionalCustomModifiers != null)
{
for (int i = 0; i < optionalCustomModifiers.Length; i++)
{
Type t = optionalCustomModifiers[i];
if (t == null)
throw new ArgumentNullException(nameof(optionalCustomModifiers));
if (t.HasElementType)
throw new ArgumentException(Environment.GetResourceString("Argument_ArraysInvalid"), nameof(optionalCustomModifiers));
if (t.ContainsGenericParameters)
throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), nameof(optionalCustomModifiers));
AddElementType(CorElementType.CModOpt);
int token = m_module.GetTypeToken(t).Token;
Debug.Assert(!MetadataToken.IsNullToken(token));
AddToken(token);
}
}
if (requiredCustomModifiers != null)
{
for (int i = 0; i < requiredCustomModifiers.Length; i++)
{
Type t = requiredCustomModifiers[i];
if (t == null)
throw new ArgumentNullException(nameof(requiredCustomModifiers));
if (t.HasElementType)
throw new ArgumentException(Environment.GetResourceString("Argument_ArraysInvalid"), nameof(requiredCustomModifiers));
if (t.ContainsGenericParameters)
throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), nameof(requiredCustomModifiers));
AddElementType(CorElementType.CModReqd);
int token = m_module.GetTypeToken(t).Token;
Debug.Assert(!MetadataToken.IsNullToken(token));
AddToken(token);
}
}
AddOneArgTypeHelper(clsArgument);
}
private void AddOneArgTypeHelper(Type clsArgument) { AddOneArgTypeHelperWorker(clsArgument, false); }
private void AddOneArgTypeHelperWorker(Type clsArgument, bool lastWasGenericInst)
{
if (clsArgument.IsGenericParameter)
{
if (clsArgument.DeclaringMethod != null)
AddElementType(CorElementType.MVar);
else
AddElementType(CorElementType.Var);
AddData(clsArgument.GenericParameterPosition);
}
else if (clsArgument.IsGenericType && (!clsArgument.IsGenericTypeDefinition || !lastWasGenericInst))
{
AddElementType(CorElementType.GenericInst);
AddOneArgTypeHelperWorker(clsArgument.GetGenericTypeDefinition(), true);
Type[] args = clsArgument.GetGenericArguments();
AddData(args.Length);
foreach (Type t in args)
AddOneArgTypeHelper(t);
}
else if (clsArgument is TypeBuilder)
{
TypeBuilder clsBuilder = (TypeBuilder)clsArgument;
TypeToken tkType;
if (clsBuilder.Module.Equals(m_module))
{
tkType = clsBuilder.TypeToken;
}
else
{
tkType = m_module.GetTypeToken(clsArgument);
}
if (clsArgument.IsValueType)
{
InternalAddTypeToken(tkType, CorElementType.ValueType);
}
else
{
InternalAddTypeToken(tkType, CorElementType.Class);
}
}
else if (clsArgument is EnumBuilder)
{
TypeBuilder clsBuilder = ((EnumBuilder)clsArgument).m_typeBuilder;
TypeToken tkType;
if (clsBuilder.Module.Equals(m_module))
{
tkType = clsBuilder.TypeToken;
}
else
{
tkType = m_module.GetTypeToken(clsArgument);
}
if (clsArgument.IsValueType)
{
InternalAddTypeToken(tkType, CorElementType.ValueType);
}
else
{
InternalAddTypeToken(tkType, CorElementType.Class);
}
}
else if (clsArgument.IsByRef)
{
AddElementType(CorElementType.ByRef);
clsArgument = clsArgument.GetElementType();
AddOneArgTypeHelper(clsArgument);
}
else if (clsArgument.IsPointer)
{
AddElementType(CorElementType.Ptr);
AddOneArgTypeHelper(clsArgument.GetElementType());
}
else if (clsArgument.IsArray)
{
if (clsArgument.IsSzArray)
{
AddElementType(CorElementType.SzArray);
AddOneArgTypeHelper(clsArgument.GetElementType());
}
else
{
AddElementType(CorElementType.Array);
AddOneArgTypeHelper(clsArgument.GetElementType());
// put the rank information
int rank = clsArgument.GetArrayRank();
AddData(rank); // rank
AddData(0); // upper bounds
AddData(rank); // lower bound
for (int i = 0; i < rank; i++)
AddData(0);
}
}
else
{
CorElementType type = CorElementType.Max;
if (clsArgument is RuntimeType)
{
type = RuntimeTypeHandle.GetCorElementType((RuntimeType)clsArgument);
//GetCorElementType returns CorElementType.Class for both object and string
if (type == CorElementType.Class)
{
if (clsArgument == typeof(object))
type = CorElementType.Object;
else if (clsArgument == typeof(string))
type = CorElementType.String;
}
}
if (IsSimpleType(type))
{
AddElementType(type);
}
else if (m_module == null)
{
InternalAddRuntimeType(clsArgument);
}
else if (clsArgument.IsValueType)
{
InternalAddTypeToken(m_module.GetTypeToken(clsArgument), CorElementType.ValueType);
}
else
{
InternalAddTypeToken(m_module.GetTypeToken(clsArgument), CorElementType.Class);
}
}
}
private void AddData(int data)
{
// A managed representation of CorSigCompressData;
if (m_currSig + 4 > m_signature.Length)
{
m_signature = ExpandArray(m_signature);
}
if (data <= 0x7F)
{
m_signature[m_currSig++] = (byte)(data & 0xFF);
}
else if (data <= 0x3FFF)
{
m_signature[m_currSig++] = (byte)((data >> 8) | 0x80);
m_signature[m_currSig++] = (byte)(data & 0xFF);
}
else if (data <= 0x1FFFFFFF)
{
m_signature[m_currSig++] = (byte)((data >> 24) | 0xC0);
m_signature[m_currSig++] = (byte)((data >> 16) & 0xFF);
m_signature[m_currSig++] = (byte)((data >> 8) & 0xFF);
m_signature[m_currSig++] = (byte)((data) & 0xFF);
}
else
{
throw new ArgumentException(Environment.GetResourceString("Argument_LargeInteger"));
}
}
private void AddElementType(CorElementType cvt)
{
// Adds an element to the signature. A managed represenation of CorSigCompressElement
if (m_currSig + 1 > m_signature.Length)
m_signature = ExpandArray(m_signature);
m_signature[m_currSig++] = (byte)cvt;
}
private void AddToken(int token)
{
// A managed represenation of CompressToken
// Pulls the token appart to get a rid, adds some appropriate bits
// to the token and then adds this to the signature.
int rid = (token & 0x00FFFFFF); //This is RidFromToken;
MetadataTokenType type = (MetadataTokenType)(token & unchecked((int)0xFF000000)); //This is TypeFromToken;
if (rid > 0x3FFFFFF)
{
// token is too big to be compressed
throw new ArgumentException(Environment.GetResourceString("Argument_LargeInteger"));
}
rid = (rid << 2);
// TypeDef is encoded with low bits 00
// TypeRef is encoded with low bits 01
// TypeSpec is encoded with low bits 10
if (type == MetadataTokenType.TypeRef)
{
//if type is mdtTypeRef
rid |= 0x1;
}
else if (type == MetadataTokenType.TypeSpec)
{
//if type is mdtTypeSpec
rid |= 0x2;
}
AddData(rid);
}
private void InternalAddTypeToken(TypeToken clsToken, CorElementType CorType)
{
// Add a type token into signature. CorType will be either CorElementType.Class or CorElementType.ValueType
AddElementType(CorType);
AddToken(clsToken.Token);
}
private unsafe void InternalAddRuntimeType(Type type)
{
// Add a runtime type into the signature.
AddElementType(CorElementType.Internal);
IntPtr handle = type.GetTypeHandleInternal().Value;
// Internal types must have their pointer written into the signature directly (we don't
// want to convert to little-endian format on big-endian machines because the value is
// going to be extracted and used directly as a pointer (and only within this process)).
if (m_currSig + sizeof(void*) > m_signature.Length)
m_signature = ExpandArray(m_signature);
byte* phandle = (byte*)&handle;
for (int i = 0; i < sizeof(void*); i++)
m_signature[m_currSig++] = phandle[i];
}
private byte[] ExpandArray(byte[] inArray)
{
// Expand the signature buffer size
return ExpandArray(inArray, inArray.Length * 2);
}
private byte[] ExpandArray(byte[] inArray, int requiredLength)
{
// Expand the signature buffer size
if (requiredLength < inArray.Length)
requiredLength = inArray.Length * 2;
byte[] outArray = new byte[requiredLength];
Buffer.BlockCopy(inArray, 0, outArray, 0, inArray.Length);
return outArray;
}
private void IncrementArgCounts()
{
if (m_sizeLoc == NO_SIZE_IN_SIG)
{
//We don't have a size if this is a field.
return;
}
m_argCount++;
}
private void SetNumberOfSignatureElements(bool forceCopy)
{
// For most signatures, this will set the number of elements in a byte which we have reserved for it.
// However, if we have a field signature, we don't set the length and return.
// If we have a signature with more than 128 arguments, we can't just set the number of elements,
// we actually have to allocate more space (e.g. shift everything in the array one or more spaces to the
// right. We do this by making a copy of the array and leaving the correct number of blanks. This new
// array is now set to be m_signature and we use the AddData method to set the number of elements properly.
// The forceCopy argument can be used to force SetNumberOfSignatureElements to make a copy of
// the array. This is useful for GetSignature which promises to trim the array to be the correct size anyway.
byte[] temp;
int newSigSize;
int currSigHolder = m_currSig;
if (m_sizeLoc == NO_SIZE_IN_SIG)
return;
//If we have fewer than 128 arguments and we haven't been told to copy the
//array, we can just set the appropriate bit and return.
if (m_argCount < 0x80 && !forceCopy)
{
m_signature[m_sizeLoc] = (byte)m_argCount;
return;
}
//We need to have more bytes for the size. Figure out how many bytes here.
//Since we need to copy anyway, we're just going to take the cost of doing a
//new allocation.
if (m_argCount < 0x80)
{
newSigSize = 1;
}
else if (m_argCount < 0x4000)
{
newSigSize = 2;
}
else
{
newSigSize = 4;
}
//Allocate the new array.
temp = new byte[m_currSig + newSigSize - 1];
//Copy the calling convention. The calling convention is always just one byte
//so we just copy that byte. Then copy the rest of the array, shifting everything
//to make room for the new number of elements.
temp[0] = m_signature[0];
Buffer.BlockCopy(m_signature, m_sizeLoc + 1, temp, m_sizeLoc + newSigSize, currSigHolder - (m_sizeLoc + 1));
m_signature = temp;
//Use the AddData method to add the number of elements appropriately compressed.
m_currSig = m_sizeLoc;
AddData(m_argCount);
m_currSig = currSigHolder + (newSigSize - 1);
}
#endregion
#region Internal Members
internal int ArgumentCount
{
get
{
return m_argCount;
}
}
internal static bool IsSimpleType(CorElementType type)
{
if (type <= CorElementType.String)
return true;
if (type == CorElementType.TypedByRef || type == CorElementType.I || type == CorElementType.U || type == CorElementType.Object)
return true;
return false;
}
internal byte[] InternalGetSignature(out int length)
{
// An internal method to return the signature. Does not trim the
// array, but passes out the length of the array in an out parameter.
// This is the actual array -- not a copy -- so the callee must agree
// to not copy it.
//
// param length : an out param indicating the length of the array.
// return : A reference to the internal ubyte array.
if (!m_sigDone)
{
m_sigDone = true;
// If we have more than 128 variables, we can't just set the length, we need
// to compress it. Unfortunately, this means that we need to copy the entire
// array. Bummer, eh?
SetNumberOfSignatureElements(false);
}
length = m_currSig;
return m_signature;
}
internal byte[] InternalGetSignatureArray()
{
int argCount = m_argCount;
int currSigLength = m_currSig;
int newSigSize = currSigLength;
//Allocate the new array.
if (argCount < 0x7F)
newSigSize += 1;
else if (argCount < 0x3FFF)
newSigSize += 2;
else
newSigSize += 4;
byte[] temp = new byte[newSigSize];
// copy the sig
int sigCopyIndex = 0;
// calling convention
temp[sigCopyIndex++] = m_signature[0];
// arg size
if (argCount <= 0x7F)
temp[sigCopyIndex++] = (byte)(argCount & 0xFF);
else if (argCount <= 0x3FFF)
{
temp[sigCopyIndex++] = (byte)((argCount >> 8) | 0x80);
temp[sigCopyIndex++] = (byte)(argCount & 0xFF);
}
else if (argCount <= 0x1FFFFFFF)
{
temp[sigCopyIndex++] = (byte)((argCount >> 24) | 0xC0);
temp[sigCopyIndex++] = (byte)((argCount >> 16) & 0xFF);
temp[sigCopyIndex++] = (byte)((argCount >> 8) & 0xFF);
temp[sigCopyIndex++] = (byte)((argCount) & 0xFF);
}
else
throw new ArgumentException(Environment.GetResourceString("Argument_LargeInteger"));
// copy the sig part of the sig
Buffer.BlockCopy(m_signature, 2, temp, sigCopyIndex, currSigLength - 2);
// mark the end of sig
temp[newSigSize - 1] = (byte)CorElementType.End;
return temp;
}
#endregion
#region Public Methods
public void AddArgument(Type clsArgument)
{
AddArgument(clsArgument, null, null);
}
public void AddArgument(Type argument, bool pinned)
{
if (argument == null)
throw new ArgumentNullException(nameof(argument));
IncrementArgCounts();
AddOneArgTypeHelper(argument, pinned);
}
public void AddArguments(Type[] arguments, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
{
if (requiredCustomModifiers != null && (arguments == null || requiredCustomModifiers.Length != arguments.Length))
throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", nameof(requiredCustomModifiers), nameof(arguments)));
if (optionalCustomModifiers != null && (arguments == null || optionalCustomModifiers.Length != arguments.Length))
throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", nameof(optionalCustomModifiers), nameof(arguments)));
if (arguments != null)
{
for (int i = 0; i < arguments.Length; i++)
{
AddArgument(arguments[i],
requiredCustomModifiers == null ? null : requiredCustomModifiers[i],
optionalCustomModifiers == null ? null : optionalCustomModifiers[i]);
}
}
}
public void AddArgument(Type argument, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
{
if (m_sigDone)
throw new ArgumentException(Environment.GetResourceString("Argument_SigIsFinalized"));
if (argument == null)
throw new ArgumentNullException(nameof(argument));
IncrementArgCounts();
// Add an argument to the signature. Takes a Type and determines whether it
// is one of the primitive types of which we have special knowledge or a more
// general class. In the former case, we only add the appropriate short cut encoding,
// otherwise we will calculate proper description for the type.
AddOneArgTypeHelper(argument, requiredCustomModifiers, optionalCustomModifiers);
}
public void AddSentinel()
{
AddElementType(CorElementType.Sentinel);
}
public override bool Equals(Object obj)
{
if (!(obj is SignatureHelper))
{
return false;
}
SignatureHelper temp = (SignatureHelper)obj;
if (!temp.m_module.Equals(m_module) || temp.m_currSig != m_currSig || temp.m_sizeLoc != m_sizeLoc || temp.m_sigDone != m_sigDone)
{
return false;
}
for (int i = 0; i < m_currSig; i++)
{
if (m_signature[i] != temp.m_signature[i])
return false;
}
return true;
}
public override int GetHashCode()
{
// Start the hash code with the hash code of the module and the values of the member variables.
int HashCode = m_module.GetHashCode() + m_currSig + m_sizeLoc;
// Add one if the sig is done.
if (m_sigDone)
HashCode += 1;
// Then add the hash code of all the arguments.
for (int i = 0; i < m_currSig; i++)
HashCode += m_signature[i].GetHashCode();
return HashCode;
}
public byte[] GetSignature()
{
return GetSignature(false);
}
internal byte[] GetSignature(bool appendEndOfSig)
{
// Chops the internal signature to the appropriate length. Adds the
// end token to the signature and marks the signature as finished so that
// no further tokens can be added. Return the full signature in a trimmed array.
if (!m_sigDone)
{
if (appendEndOfSig)
AddElementType(CorElementType.End);
SetNumberOfSignatureElements(true);
m_sigDone = true;
}
// This case will only happen if the user got the signature through
// InternalGetSignature first and then called GetSignature.
if (m_signature.Length > m_currSig)
{
byte[] temp = new byte[m_currSig];
Array.Copy(m_signature, 0, temp, 0, m_currSig);
m_signature = temp;
}
return m_signature;
}
public override String ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("Length: " + m_currSig + Environment.NewLine);
if (m_sizeLoc != -1)
{
sb.Append("Arguments: " + m_signature[m_sizeLoc] + Environment.NewLine);
}
else
{
sb.Append("Field Signature" + Environment.NewLine);
}
sb.Append("Signature: " + Environment.NewLine);
for (int i = 0; i <= m_currSig; i++)
{
sb.Append(m_signature[i] + " ");
}
sb.Append(Environment.NewLine);
return sb.ToString();
}
#endregion
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using OpenMetaverse;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.CoreModules.World.Wind;
namespace OpenSim.Region.CoreModules.World.Wind.Plugins
{
class ZephyrWind : Mono.Addins.TypeExtensionNode, IWindModelPlugin
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private OpenSim.Region.Framework.Scenes.Scene _scene;
// This cell size cannot change without upending the entire wind framework.
// To improve realism, Zephyr creates three bands of currents: sea, surface, and aloft.
// sea 'wind' is an undulating current that simulates the back and forth surge.
// surface wind is subject to terrain turblence.
// wind aloft is laminar with gentle shifts.
private Vector2[] m_waterCurrent = new Vector2[16 * 16];
private Vector2[] m_windsGround = new Vector2[16 * 16];
private Vector2[] m_windsAloft = new Vector2[16 * 16];
private WindConstants[] m_options = new WindConstants[16 * 16];
private float[] m_skews = new float[16 * 16];
private float[] m_ranges = new float[16 * 16];
private float[] m_maxheights = new float[16 * 16];
private float m_avgWindStrength = 7.0f; // Average magnitude of the wind vector
private float m_avgWindDirection = 0.0f; // Average direction of the wind in degrees
private float m_varWindStrength = 7.0f; // Max Strength Variance
private float m_varWindDirection = 30.0f;// Max Direction Variance
private float m_rateChangeAloft = 1.0f; // Rate of change of the winds aloft
private float m_rateChangeFlutter = 64.0f;
private float m_avgWaterStrength = 1.0f;
private float m_avgWaterDirection = 10.0f;
private float m_varWaterStrength = 2.0f;
private float m_varWaterDirection = 180.0f;
private float m_rateChangeSurge = 128.0f;
private float SunFudge = 0.0f;
private float LastSunPos;
#region IPlugin Members
public string Version
{
get { return "1.0.0.0"; }
}
public string Name
{
get { return "ZephyrWind"; }
}
public void Initialize()
{
}
#endregion
#region IDisposable Members
public void Dispose()
{
m_waterCurrent = null;
m_windsGround = null;
m_windsAloft = null;
m_options = null;
m_skews = null;
m_ranges = null;
m_maxheights = null;
}
#endregion
#region IWindModelPlugin Members
public void WindConfig(OpenSim.Region.Framework.Scenes.Scene scene, Nini.Config.IConfig windConfig)
{
_scene = scene;
// Default to ground turbulence
for (int y = 0; y < 16; y++)
{
for (int x = 0; x < 16; x++)
{
m_options[y * 16 + x] = WindConstants.WindSpeedTurbulence;
}
}
if (windConfig != null)
{
// Uses strength value if avg_strength not specified
m_avgWindStrength = windConfig.GetFloat("strength", 5.0F);
m_avgWindStrength = windConfig.GetFloat("avg_strength", 5.0F);
m_avgWindDirection = windConfig.GetFloat("avg_direction", 0.0F);
m_varWindStrength = windConfig.GetFloat("var_strength", 5.0F);
m_varWindDirection = windConfig.GetFloat("var_direction", 30.0F);
m_rateChangeAloft = windConfig.GetFloat("rate_change_aloft", 1.0f);
m_rateChangeFlutter = windConfig.GetFloat("rate_change_flutter", 64.0f);
LogSettings();
}
}
public void WindUpdate(uint frame)
{
float h2o = (float)_scene.RegionInfo.RegionSettings.WaterHeight;
float gnd;
float sunpos;
// Simulate time passing on fixed sun regions.
// Otherwise use the region's local sun position.
if (_scene.RegionInfo.RegionSettings.FixedSun)
sunpos = (float)((DateTime.Now.TimeOfDay.TotalSeconds / 600.0) % 24.0);
else
sunpos = (float)(_scene.RegionInfo.RegionSettings.SunPosition % 24.0);
// Sun position is quantized by the simulator to about once every three seconds.
// Add a fudge factor to fill in the steps.
if (LastSunPos != sunpos)
{
LastSunPos = sunpos;
SunFudge = 0.0f;
}
else
{
SunFudge += 0.002f;
}
sunpos += SunFudge;
RunningStat rsCell = new RunningStat();
// Based on the Prevailing wind algorithm
// Inspired by Kanker Greenacre
// Modified by Balpien Hammerer to account for terrain turbulence, winds aloft and wind setters
// Wind Direction
double ThetaWD = (sunpos / 24.0 * (2.0 * Math.PI) * m_rateChangeFlutter) % (Math.PI * 2.0);
double offset = Math.Sin(ThetaWD) * Math.Sin(ThetaWD*2) * Math.Sin(ThetaWD*9) * Math.Cos(ThetaWD*4);
double windDir = m_avgWindDirection * (Math.PI/180.0f) + (m_varWindDirection * (Math.PI/180.0f) * offset);
// Wind Speed
double ThetaWS = (sunpos / 24.0 * (2.0 * Math.PI) * m_rateChangeAloft) % (Math.PI * 2.0);
offset = Math.Sin(ThetaWS) * Math.Sin(ThetaWS*4) + (Math.Sin(ThetaWS*13) / 3.0);
double windSpeed = (m_avgWindStrength + (m_varWindStrength * offset));
if (windSpeed < 0)
{
windSpeed = -windSpeed;
windDir += Math.PI;
}
// Water Direction
double ThetaHD = (sunpos / 24.0 * (2.0 * Math.PI) * m_rateChangeFlutter) % (Math.PI * 2.0);
double woffset = Math.Sin(ThetaHD) * Math.Sin(ThetaHD*2) * Math.Sin(ThetaHD*9) * Math.Cos(ThetaHD*4);
double waterDir = m_avgWaterDirection * (Math.PI/180.0f) + (m_varWaterDirection * (Math.PI/180.0f) * woffset);
// Water Speed
double ThetaHS = (sunpos / 24.0 * (2.0 * Math.PI) * m_rateChangeSurge) % (Math.PI * 2.0);
woffset = Math.Sin(ThetaHS) * Math.Sin(ThetaHS*3) * Math.Sin(ThetaHS*9) * Math.Cos(ThetaHS*4) * Math.Cos(ThetaHS*13);
double waterSpeed = (m_avgWaterStrength + (m_varWaterStrength * woffset));
if (waterSpeed < 0)
{
waterSpeed = -waterSpeed;
waterDir += Math.PI;
}
//m_log.DebugFormat("[{0}] sunpos={1} water={2} dir={3} ThetaHD={4} ThetaHS={5} wo={6}", Name, sunpos, waterSpeed, waterDir, ThetaHD, ThetaHS, woffset);
//m_log.DebugFormat("[{0}] sunpos={1} wind={2} dir={3} theta1={4} theta2={5}", Name, sunpos, windSpeed, windDir, theta1, theta2);
// Set the predominate wind in each cell, but examine the terrain heights
// to adjust the winds. Elevation and the pattern of heights in each 16m
// cell infuence the ground winds.
for (int y = 0; y < 16; y++)
{
for (int x = 0; x < 16; x++)
{
rsCell.Clear();
// Compute terrain statistics. They are needed later.
for (int iy = 0; iy < 16; iy++)
{
for (int ix = 0; ix < 16; ix++)
{
// For the purpose of these computations, it is the above water height that matters.
// Any ground below water is treated as zero.
gnd = Math.Max(_scene.PhysicsScene.TerrainChannel.GetRawHeightAt(x * 16 + ix, y * 16 + iy) - h2o, 0);
rsCell.Push(gnd);
}
}
// Look for the range of heights in the cell and the overall skewness. Use this
// to determine ground induced deflection. It is a rough approximation of
// ground wind turbulance. The max height is used later to determine the boundary layer.
float cellrange = (float)Math.Max((rsCell.Max() - rsCell.Min()) / 5.0f, 1.0);
float cellskew = (float)rsCell.Skewness();
m_ranges[y * 16 + x] = (float)(rsCell.Max() - rsCell.Min());
m_skews[y * 16 + x] = cellskew;
m_maxheights[y * 16 + x] = (float)rsCell.Max();
// Begin with winds aloft,starting with the fixed wind value set by wind setters.
Vector2 wind = m_windsAloft[y * 16 + x];
// Update the cell with default zephyr winds aloft (no turbulence) if the wind speed is not fixed.
if ((m_options[y * 16 + x] & WindConstants.WindSpeedFixed) == 0)
{
// Compute the winds aloft (no turbulence)
wind.X = (float)Math.Cos(windDir);
wind.Y = (float)Math.Sin(windDir);
//wind.Normalize();
wind.X *= (float)windSpeed;
wind.Y *= (float)windSpeed;
m_windsAloft[y * 16 + x] = wind;
}
// Compute ground winds (apply terrain turbulence) from the winds aloft cell.
if ((m_options[y * 16 + x] & WindConstants.WindSpeedTurbulence) != 0)
{
double speed = Math.Sqrt(wind.X * wind.X + wind.Y * wind.Y);
wind = wind / (float)speed;
double dir = Math.Atan2(wind.Y, wind.X);
wind.X = (float)Math.Cos((Math.PI * cellskew * 0.333 * cellrange) + dir);
wind.Y = (float)Math.Sin((Math.PI * cellskew * 0.333 * cellrange) + dir);
//wind.Normalize();
wind.X *= (float)speed;
wind.Y *= (float)speed;
}
m_windsGround[y * 16 + x] = wind;
// Update the cell with default zephyr water currents if the speed is not fixed.
if ((m_options[y * 16 + x] & WindConstants.WindSpeedFixed) == 0)
{
// Compute the winds aloft (no turbulence)
wind.X = (float)Math.Cos(waterDir);
wind.Y = (float)Math.Sin(waterDir);
//wind.Normalize();
wind.X *= (float)waterSpeed;
wind.Y *= (float)waterSpeed;
m_waterCurrent[y * 16 + x] = wind;
}
//m_log.DebugFormat("[ZephyrWind] speed={0} dir={1} skew={2} range={3} wind={4}", windSpeed, windDir, cellskew, cellrange, wind);
}
}
// Send the updated wind data to the physics engine.
_scene.PhysicsScene.SendPhysicsWindData(m_waterCurrent, m_windsGround, m_windsAloft, m_ranges, m_maxheights);
}
/// <summary>
/// Determine the wind speed at the specified local region coordinate.
/// Wind speed returned is influenced by the nearest neighbors.
/// </summary>
/// <param name="fX">region local coordinate</param>
/// <param name="fY">region local coordinate</param>
/// <param name="fZ">Presently ignored</param>
/// <returns></returns>
public Vector3 WindSpeed(float fX, float fY, float fZ)
{
int x0 = (int)fX / 16;
int y0 = (int)fY / 16;
if (x0 < 0 || x0 >= 16) return Vector3.Zero;
if (y0 < 0 || y0 >= 16) return Vector3.Zero;
int x1 = Math.Min(x0+1, 15);
int y1 = Math.Min(y0+1, 15);
//Set the wind maxtrix based on the z-position
float h2o = (float)_scene.RegionInfo.RegionSettings.WaterHeight;
float maxheight = m_maxheights[y0 * 16 + x0];
float range = Math.Max(m_ranges[y0 * 16 + x0], 15.0f);
float boundary = maxheight + range;
Vector2[] windmatrix;
if (fZ < h2o)
windmatrix = m_waterCurrent;
else if (fZ <= boundary)
windmatrix = m_windsGround;
else
windmatrix = m_windsAloft;
// Perform a bilinear interpolation of wind speeds
// f(x,y) = f(0,0) * (1-x)(1-y) + f(1,0) * x(1-y) + f(0,1) * (1-x)y + f(1,1) * xy.
Vector3 wind = Vector3.Zero;
float dx = (fX - x0*16) / 16.0f;
float dy = (fY - y0*16) / 16.0f;
//m_log.DebugFormat("pos={0} x0={1} x1={2} y0={3} y1={4} dx={5} dy={6}", new Vector3(fX,fY,fZ), x0, x0, y0, y1, dx, dy);
wind.X = windmatrix[y0 * 16 + x0].X * (1.0f-dx) * (1.0f-dy);
wind.X += windmatrix[y0 * 16 + x1].X * dx * (1.0f-dy);
wind.X += windmatrix[y1 * 16 + x0].X * dy * (1.0f-dx);
wind.X += windmatrix[y1 * 16 + x1].X * dx *dy;
wind.Y = windmatrix[y0 * 16 + x0].Y * (1.0f-dx) * (1.0f-dy);
wind.Y += windmatrix[y0 * 16 + x1].Y * dx * (1.0f-dy);
wind.Y += windmatrix[y1 * 16 + x0].Y * dy * (1.0f-dx);
wind.Y += windmatrix[y1 * 16 + x1].Y * dx *dy;
return wind;
}
/// <summary>
/// Set the wind speed characteristics for a cell. A cell is
/// presently 16x16m SW corner origined.
/// </summary>
/// <param name="type">WindConstant - fixed or default</param>
/// <param name="loc">Region local coordinate</param>
/// <param name="speed">Wind Speed</param>
public void WindSet(int type, Vector3 loc, Vector3 speed)
{
float h2o = (float)_scene.RegionInfo.RegionSettings.WaterHeight;
WindConstants wtype = (WindConstants)type;
int x = (int)loc.X / 16;
int y = (int)loc.Y / 16;
if (x < 0 || x >= 16) return;
if (y < 0 || y >= 16) return;
// Handle default case, which really means not fixed + terrain turbulence
if (wtype == WindConstants.WindSpeedDefault)
{
wtype = WindConstants.WindSpeedTurbulence;
}
// Save the overrides
m_options[y * 16 + x] = wtype;
// If fixed wind set, copy the set windspeed into the winds aloft cell.
// If the z location is underwater, then set the water current speed.
if ((wtype & WindConstants.WindSpeedFixed) != 0)
{
if (loc.Z >= h2o)
m_windsAloft[y * 16 + x] = new Vector2(speed.X, speed.Y);
else
m_waterCurrent[y * 16 + x] = new Vector2(speed.X, speed.Y);
}
//m_log.DebugFormat("[ZephyrWind] {0} {1} {2}", type, loc, speed);
}
/// <summary>
/// Return the wind speed matrix. This must comply with the
/// viewer's expectations: a 256 cell array.
/// </summary>
/// <returns>wind speed matrix</returns>
public Vector2[] WindLLClientArray(Vector3 pos)
{
float h2o = (float)_scene.RegionInfo.RegionSettings.WaterHeight;
int x = Utils.Clamp((int)pos.X/16, 0, 15);
int y = Utils.Clamp((int)pos.Y/16, 0, 15);
pos.Z = Utils.Clamp(pos.Z, 0, OpenSim.Framework.Constants.REGION_MAXIMUM_Z);
float maxheight = m_maxheights[y * 16 + x];
float range = Math.Max(m_ranges[y * 16 + x], 15.0f);
float boundary;
// When x-pos is the sentinel value, set the boundary to water level.
// This is used to communicate the three matrices to the physics engine.
if (pos.X == -1)
boundary = h2o;
// Otherwise, determine ground vs aloft based on the twice the height above the cell at
// the avatar's position. This is used to give the viewer the avatar's proximate winds.
else
boundary = h2o + maxheight + range;
//m_log.DebugFormat("[ZephyrWind] ClientArray pos={0} range={1} maxh={2} boundary={3} h2o={4}", pos, range, maxheight, boundary, h2o);
if (pos.Z < h2o)
return m_waterCurrent;
else if (pos.Z <= boundary)
return m_windsGround;
else
return m_windsAloft;
}
public string Description
{
get
{
return "Provides a sun and terrain influenced predominate wind direction that can be adjusted by wind setters.";
}
}
public System.Collections.Generic.Dictionary<string, string> WindParams()
{
Dictionary<string, string> Params = new Dictionary<string, string>();
Params.Add("avgStrength", "average wind strength");
Params.Add("avgDirection", "average wind direction in degrees");
Params.Add("varStrength", "allowable variance in wind strength");
Params.Add("varDirection", "allowable variance in wind direction in +/- degrees");
Params.Add("rateChangeAloft", "rate of change of winds aloft");
Params.Add("rateChangeFlutter", "rate of change of wind flutter");
return Params;
}
public void WindParamSet(string param, float value)
{
switch (param)
{
case "avgStrength":
m_avgWindStrength = value;
break;
case "avgDirection":
m_avgWindDirection = value;
break;
case "varStrength":
m_varWindStrength = value;
break;
case "varDirection":
m_varWindDirection = value;
break;
case "rateChangeAloft":
m_rateChangeAloft = value;
break;
case "rateChangeFlutter":
m_rateChangeFlutter = value;
break;
}
LogSettings();
}
public float WindParamGet(string param)
{
switch (param)
{
case "avgStrength":
return m_avgWindStrength;
case "avgDirection":
return m_avgWindDirection;
case "varStrength":
return m_varWindStrength;
case "varDirection":
return m_varWindDirection;
case "rateChangeAloft":
return m_rateChangeAloft;
case "rateChangeFlutter":
return m_rateChangeFlutter;
default:
//throw new Exception(String.Format("Unknown {0} parameter {1}", this.Name, param));
m_log.InfoFormat("[{0}] Unknown parameter {1}", this.Name, param);
return 0.0f;
}
}
#endregion
private void LogSettings()
{
m_log.InfoFormat("[{0}] Average Strength : {1}", Name, m_avgWindStrength);
m_log.InfoFormat("[{0}] Average Direction : {1}", Name, m_avgWindDirection);
m_log.InfoFormat("[{0}] Varience Strength : {1}", Name, m_varWindStrength);
m_log.InfoFormat("[{0}] Varience Direction : {1}", Name, m_varWindDirection);
m_log.InfoFormat("[{0}] Rate Change : {1}", Name, m_rateChangeAloft);
}
#region IWindModelPlugin Members
#endregion
}
/// <summary>
/// A running variance and standard deviation class
/// used to gather real time metrics.
/// </summary>
// Borrowed from: http://www.johndcook.com/standard_deviation.html and http://www.johndcook.com/skewness_kurtosis.html
internal class RunningStat
{
private long n;
private double M1, M2, M3, /*M4,*/ M5, M6;
public RunningStat()
{
Clear();
}
public void Clear()
{
n = 0;
M1 = M2 = M3 = /*M4 =*/ M5 = M6 = 0.0;
}
public void Push(double x)
{
double delta, delta_n, term1;
long n1 = n;
// See Knuth TAOCP vol 2, 3rd edition, page 232
n++;
delta = x - M1;
delta_n = delta / n;
term1 = delta * delta_n * n1;
M1 += delta_n;
//profiling runs show M4 calculation as hot and we're not using it. so comment out for now
//M4 += term1 * delta_n2 * (n*n - 3*n + 3) + 6 * delta_n2 * M2 - 4 * delta_n * M3;
M3 += term1 * delta_n * (n - 2) - 3 * delta_n * M2;
M2 += term1;
if (n == 1)
{
M5 = M6 = x;
}
else
{
if (x < M5) M5 = x;
if (x > M6) M6 = x;
}
}
public long NumDataValues()
{
return n;
}
public double Min()
{
return M5;
}
public double Max()
{
return M6;
}
public double Mean()
{
return M1;
}
public double Variance()
{
if (n == 0) return 0.0;
return M2/(n-1.0);
}
public double StandardDeviation()
{
return Math.Sqrt( Variance() );
}
public double Skewness()
{
double result = Math.Sqrt((double)n) * M3/ Math.Pow(M2, 1.5);
if (double.IsNaN(result)) result = 0.0;
return result;
}
/*public double Kurtosis()
{
return (double)n*M4 / (M2*M2) - 3.0;
}*/
}
}
| |
using Miner.ComCategories;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace Miner.Interop.Process
{
/// <summary>
/// Base class for Process Framework node controls.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Px")]
[ComVisible(true)]
public abstract class BasePxControl : IMMPxControl, IMMPxControl2, IMMPxDisplayName
{
#region Fields
private IMMPxNode _Node;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="BasePxControl" /> class.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="control">The control.</param>
/// <param name="displayName">The display name.</param>
protected BasePxControl(string name, IPxControlUI control, string displayName)
{
this.Name = name;
this.Control = control;
this.DisplayName = displayName;
this.Enabled = true;
}
#endregion
#region Public Properties
/// <summary>
/// Gets the handle to the control.
/// </summary>
/// <value>The handle to the control.</value>
public int hWnd
{
get
{
if (this.Control == null) return 0;
return this.Control.Handle;
}
}
/// <summary>
/// Gets a value indicating whether this instance is initialized.
/// </summary>
/// <value>
/// <c>true</c> if this instance is initialized; otherwise, <c>false</c>.
/// </value>
public virtual bool IsInitialized
{
get { return (this.PxApplication != null); }
}
/// <summary>
/// Gets the display name.
/// </summary>
/// <value>The display name.</value>
public string DisplayName { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="BasePxControl" /> is enabled.
/// </summary>
/// <value><c>true</c> if enabled; otherwise, <c>false</c>.</value>
public bool Enabled { get; set; }
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name { get; private set; }
/// <summary>
/// Sets the node.
/// </summary>
/// <value>The node.</value>
public IMMPxNode Node
{
set
{
if (this.Control != null)
this.Control.LoadControl(this.PxApplication, value);
_Node = value;
}
protected get { return _Node; }
}
/// <summary>
/// Gets a value indicating whether the state of the node is completed.
/// </summary>
/// <value>
/// <c>true</c> if the state of the node is completed; otherwise, <c>false</c>.
/// </value>
public virtual bool StateComplete { get; protected set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="BasePxControl" /> is visible.
/// </summary>
/// <value>
/// <c>true</c> if visible; otherwise, <c>false</c>.
/// </value>
public virtual bool Visible
{
get
{
if (this.Control == null)
return false;
return this.Control.Visible;
}
set
{
if (this.Control == null)
return;
this.Control.Visible = value;
}
}
#endregion
#region Protected Properties
/// <summary>
/// Gets the control.
/// </summary>
/// <value>
/// The control.
/// </value>
protected IPxControlUI Control { get; private set; }
/// <summary>
/// Gets the process application reference.
/// </summary>
/// <value>
/// The process application reference.
/// </value>
protected IMMPxApplication PxApplication { get; private set; }
#endregion
#region Public Methods
/// <summary>
/// Initializes the control with the specified <paramref name="vInitData" />.
/// </summary>
/// <param name="vInitData">The initalization data.</param>
public virtual void Initialize(object vInitData)
{
this.PxApplication = vInitData as IMMPxApplication;
}
/// <summary>
/// Called when the control is losing focus within the application.
/// </summary>
/// <param name="bTerminate">if set to <c>true</c> the control can be closed; otherwise <c>false</c> to stop the closing.</param>
public virtual void Terminate(ref bool bTerminate)
{
if (this.Control != null && this.Control.PendingUpdates)
{
DialogResult result = MessageBox.Show(@"Do you want to apply the changes?",
this.DisplayName, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
this.Control.ApplyUpdates();
}
}
#endregion
#region Internal Methods
/// <summary>
/// Registers the specified registry key.
/// </summary>
/// <param name="registryKey">The registry key.</param>
[ComRegisterFunction]
internal static void Register(string registryKey)
{
MMProcessMgrControl.Register(registryKey);
}
/// <summary>
/// Unregisters the specified registry key.
/// </summary>
/// <param name="registryKey">The registry key.</param>
[ComUnregisterFunction]
internal static void Unregister(string registryKey)
{
MMProcessMgrControl.Unregister(registryKey);
}
#endregion
}
}
| |
using Signum.Entities.Authorization;
using Signum.Utilities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq.Expressions;
using Signum.Entities.Dynamic;
using Signum.Entities.Scheduler;
using Signum.Entities.Processes;
namespace Signum.Entities.Workflow
{
[Serializable, EntityKind(EntityKind.System, EntityData.Transactional)]
public class CaseActivityEntity : Entity
{
public CaseEntity Case { get; set; }
[ImplementedBy(typeof(WorkflowActivityEntity), typeof(WorkflowEventEntity))]
public IWorkflowNodeEntity WorkflowActivity { get; set; }
[StringLengthValidator(Min = 3, Max = 255)]
public string OriginalWorkflowActivityName { get; set; }
public DateTime StartDate { get; set; } = TimeZoneManager.Now;
public Lite<CaseActivityEntity>? Previous { get; set; }
[StringLengthValidator(MultiLine = true)]
public string? Note { get; set; }
public DateTime? DoneDate { get; set; }
[Unit("min")]
public double? Duration { get; set; }
[AutoExpressionField]
public double? DurationRealTime => As.Expression(() => Duration ?? (double?)(TimeZoneManager.Now - StartDate).TotalMinutes);
[AutoExpressionField]
public double? DurationRatio => As.Expression(() => Duration / ((WorkflowActivityEntity)WorkflowActivity).EstimatedDuration);
[AutoExpressionField]
public double? DurationRealTimeRatio => As.Expression(() => DurationRealTime / ((WorkflowActivityEntity)WorkflowActivity).EstimatedDuration);
public Lite<UserEntity>? DoneBy { get; set; }
public DoneType? DoneType { get; set; }
public string? DoneDecision { get; set; }
public ScriptExecutionEmbedded? ScriptExecution { get; set; }
static Expression<Func<CaseActivityEntity, CaseActivityState>> StateExpression =
@this => @this.DoneDate.HasValue ? CaseActivityState.Done : CaseActivityState.Pending;
[ExpressionField("StateExpression")]
public CaseActivityState State
{
get
{
if (this.IsNew)
return CaseActivityState.New;
return StateExpression.Evaluate(this);
}
}
[AutoExpressionField]
public override string ToString() => As.Expression(() => WorkflowActivity + " " + DoneBy);
protected override void PreSaving(PreSavingContext ctx)
{
base.PreSaving(ctx);
this.Duration = this.DoneDate == null ? (double?)null :
(this.DoneDate.Value - this.StartDate).TotalMinutes;
}
}
[Serializable]
public class ScriptExecutionEmbedded : EmbeddedEntity
{
public DateTime NextExecution { get; set; }
public int RetryCount { get; set; }
public Guid? ProcessIdentifier { get; set; }
}
public enum DoneType
{
Next,
Jump = 3,
Timeout,
ScriptSuccess,
ScriptFailure,
Recompose,
}
public enum CaseActivityState
{
[Ignore]
New,
Pending,
Done,
}
[AutoInit]
public static class CaseActivityOperation
{
public static readonly ConstructSymbol<CaseActivityEntity>.From<WorkflowEntity> CreateCaseActivityFromWorkflow;
public static readonly ConstructSymbol<CaseEntity>.From<WorkflowEventTaskEntity> CreateCaseFromWorkflowEventTask;
public static readonly ExecuteSymbol<CaseActivityEntity> Register;
public static readonly DeleteSymbol<CaseActivityEntity> Delete;
public static readonly ExecuteSymbol<CaseActivityEntity> Next;
public static readonly ExecuteSymbol<CaseActivityEntity> Jump;
public static readonly ExecuteSymbol<CaseActivityEntity> Timer;
public static readonly ExecuteSymbol<CaseActivityEntity> MarkAsUnread;
public static readonly ExecuteSymbol<CaseActivityEntity> Undo;
public static readonly ExecuteSymbol<CaseActivityEntity> ScriptExecute;
public static readonly ExecuteSymbol<CaseActivityEntity> ScriptScheduleRetry;
public static readonly ExecuteSymbol<CaseActivityEntity> ScriptFailureJump;
public static readonly ExecuteSymbol<DynamicTypeEntity> FixCaseDescriptions;
}
[AutoInit]
public static class CaseActivityTask
{
public static readonly SimpleTaskSymbol Timeout;
}
[AutoInit]
public static class CaseActivityProcessAlgorithm
{
public static readonly ProcessAlgorithmSymbol Timeout;
}
public enum CaseActivityMessage
{
CaseContainsOtherActivities,
NoNextConnectionThatSatisfiesTheConditionsFound,
[Description("Case is a decomposition of {0}")]
CaseIsADecompositionOf0,
[Description("From {0} on {1}")]
From0On1,
[Description("Done by {0} on {1}")]
DoneBy0On1,
PersonalRemarksForThisNotification,
[Description("The activity '{0}' requires to be opened")]
TheActivity0RequiresToBeOpened,
NoOpenedOrInProgressNotificationsFound,
NextActivityAlreadyInProgress,
NextActivityOfDecompositionSurrogateAlreadyInProgress,
[Description("Only '{0}' can undo this operation")]
Only0CanUndoThisOperation,
[Description("Activity '{0}' has no jumps")]
Activity0HasNoJumps,
[Description("Activity '{0}' has no timeout")]
Activity0HasNoTimers,
ThereIsNoPreviousActivity,
OnlyForScriptWorkflowActivities,
Pending,
NoWorkflowActivity,
[Description("Impossible to delete Case Activity {0} (on Workflow Activity '{1}') because has no previouos activity")]
ImpossibleToDeleteCaseActivity0OnWorkflowActivity1BecauseHasNoPreviousActivity,
LastCaseActivity,
CurrentUserHasNotification,
NoNewOrOpenedOrInProgressNotificationsFound,
NoActorsFoundToInsertCaseActivityNotifications,
ThereAreInprogressActivities,
ShowHelp,
HideHelp,
CanceledCase,
AlreadyFinished,
NotCanceled
}
public enum CaseActivityQuery
{
Inbox
}
[Serializable]
public class ActivityWithRemarks : ModelEntity
{
public Lite<WorkflowActivityEntity>? WorkflowActivity { get; set; }
public Lite<CaseEntity> Case { get; set; }
public Lite<CaseActivityEntity>? CaseActivity { get; set; }
public Lite<CaseNotificationEntity>? Notification { get; set; }
public string? Remarks { get; set; }
public int Alerts { get; set; }
public List<CaseTagTypeEntity> Tags { get; set; }
}
[Serializable, EntityKind(EntityKind.System, EntityData.Transactional)]
public class CaseActivityExecutedTimerEntity : Entity
{
public DateTime CreationDate { get; private set; } = TimeZoneManager.Now;
public Lite<CaseActivityEntity> CaseActivity { get; set; }
public Lite<WorkflowEventEntity> BoundaryEvent { get; set; }
}
}
| |
// 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 LiftedComparisonGreaterThanNullableTests
{
#region Test methods
[Fact]
public static void CheckLiftedComparisonGreaterThanNullableByteTest()
{
byte?[] values = new byte?[] { null, 0, 1, byte.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanNullableByte(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedComparisonGreaterThanNullableCharTest()
{
char?[] values = new char?[] { null, '\0', '\b', 'A', '\uffff' };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanNullableChar(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedComparisonGreaterThanNullableDecimalTest()
{
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++)
{
VerifyComparisonGreaterThanNullableDecimal(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedComparisonGreaterThanNullableDoubleTest()
{
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++)
{
VerifyComparisonGreaterThanNullableDouble(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedComparisonGreaterThanNullableFloatTest()
{
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++)
{
VerifyComparisonGreaterThanNullableFloat(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedComparisonGreaterThanNullableIntTest()
{
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++)
{
VerifyComparisonGreaterThanNullableInt(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedComparisonGreaterThanNullableLongTest()
{
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++)
{
VerifyComparisonGreaterThanNullableLong(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedComparisonGreaterThanNullableSByteTest()
{
sbyte?[] values = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanNullableSByte(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedComparisonGreaterThanNullableShortTest()
{
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++)
{
VerifyComparisonGreaterThanNullableShort(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedComparisonGreaterThanNullableUIntTest()
{
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++)
{
VerifyComparisonGreaterThanNullableUInt(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedComparisonGreaterThanNullableULongTest()
{
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++)
{
VerifyComparisonGreaterThanNullableULong(values[i], values[j]);
}
}
}
[Fact]
public static void CheckLiftedComparisonGreaterThanNullableUShortTest()
{
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++)
{
VerifyComparisonGreaterThanNullableUShort(values[i], values[j]);
}
}
}
#endregion
#region Test verifiers
private static void VerifyComparisonGreaterThanNullableByte(byte? a, byte? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(byte?)),
Expression.Constant(b, typeof(byte?)),
true,
null));
Func<bool?> f = e.Compile();
bool? expected = a > b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonGreaterThanNullableChar(char? a, char? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(char?)),
Expression.Constant(b, typeof(char?)),
true,
null));
Func<bool?> f = e.Compile();
bool? expected = a > b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonGreaterThanNullableDecimal(decimal? a, decimal? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(decimal?)),
Expression.Constant(b, typeof(decimal?)),
true,
null));
Func<bool?> f = e.Compile();
bool? expected = a > b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonGreaterThanNullableDouble(double? a, double? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(double?)),
Expression.Constant(b, typeof(double?)),
true,
null));
Func<bool?> f = e.Compile();
bool? expected = a > b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonGreaterThanNullableFloat(float? a, float? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(float?)),
Expression.Constant(b, typeof(float?)),
true,
null));
Func<bool?> f = e.Compile();
bool? expected = a > b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonGreaterThanNullableInt(int? a, int? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?)),
true,
null));
Func<bool?> f = e.Compile();
bool? expected = a > b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonGreaterThanNullableLong(long? a, long? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(long?)),
true,
null));
Func<bool?> f = e.Compile();
bool? expected = a > b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonGreaterThanNullableSByte(sbyte? a, sbyte? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(sbyte?)),
Expression.Constant(b, typeof(sbyte?)),
true,
null));
Func<bool?> f = e.Compile();
bool? expected = a > b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonGreaterThanNullableShort(short? a, short? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(short?)),
true,
null));
Func<bool?> f = e.Compile();
bool? expected = a > b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonGreaterThanNullableUInt(uint? a, uint? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(uint?)),
true,
null));
Func<bool?> f = e.Compile();
bool? expected = a > b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonGreaterThanNullableULong(ulong? a, ulong? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(ulong?)),
true,
null));
Func<bool?> f = e.Compile();
bool? expected = a > b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
private static void VerifyComparisonGreaterThanNullableUShort(ushort? a, ushort? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(ushort?)),
true,
null));
Func<bool?> f = e.Compile();
bool? expected = a > b;
bool? result = f();
Assert.Equal(a == null || b == null ? null : expected, result);
}
#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.IO;
using System.Threading;
namespace System.Net.Security
{
//
// This is a wrapping stream that does data encryption/decryption based on a successfully authenticated SSPI context.
// This file contains the private implementation.
//
public partial class NegotiateStream : AuthenticatedStream
{
private static AsyncCallback s_writeCallback = new AsyncCallback(WriteCallback);
private static AsyncProtocolCallback s_readCallback = new AsyncProtocolCallback(ReadCallback);
private int _NestedWrite;
private int _NestedRead;
private byte[] _ReadHeader;
// Never updated directly, special properties are used.
private byte[] _InternalBuffer;
private int _InternalOffset;
private int _InternalBufferCount;
private FixedSizeReader _FrameReader;
// TODO (Issue #3114): Implement using TPL instead of APM.
private StreamAsyncHelper _innerStreamAPM;
internal StreamAsyncHelper InnerStreamAPM
{
get
{
return _innerStreamAPM;
}
}
private void InitializeStreamPart()
{
_ReadHeader = new byte[4];
_FrameReader = new FixedSizeReader(InnerStream);
_innerStreamAPM = new StreamAsyncHelper(InnerStream);
}
private byte[] InternalBuffer
{
get
{
return _InternalBuffer;
}
}
private int InternalOffset
{
get
{
return _InternalOffset;
}
}
private int InternalBufferCount
{
get
{
return _InternalBufferCount;
}
}
private void DecrementInternalBufferCount(int decrCount)
{
_InternalOffset += decrCount;
_InternalBufferCount -= decrCount;
}
private void EnsureInternalBufferSize(int bytes)
{
_InternalBufferCount = bytes;
_InternalOffset = 0;
if (InternalBuffer == null || InternalBuffer.Length < bytes)
{
_InternalBuffer = new byte[bytes];
}
}
private void AdjustInternalBufferOffsetSize(int bytes, int offset)
{
_InternalBufferCount = bytes;
_InternalOffset = offset;
}
//
// Validates user parameters for all Read/Write methods.
//
private void ValidateParameters(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count");
}
if (count > buffer.Length - offset)
{
throw new ArgumentOutOfRangeException("count", SR.net_offset_plus_count);
}
}
//
// Combined sync/async write method. For sync request asyncRequest==null.
//
private void ProcessWrite(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
ValidateParameters(buffer, offset, count);
if (Interlocked.Exchange(ref _NestedWrite, 1) == 1)
{
throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, (asyncRequest != null ? "BeginWrite" : "Write"), "write"));
}
bool failed = false;
try
{
StartWriting(buffer, offset, count, asyncRequest);
}
catch (Exception e)
{
failed = true;
if (e is IOException)
{
throw;
}
throw new IOException(SR.net_io_write, e);
}
finally
{
if (asyncRequest == null || failed)
{
_NestedWrite = 0;
}
}
}
private void StartWriting(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
// We loop to this method from the callback.
// If the last chunk was just completed from async callback (count < 0), we complete user request.
if (count >= 0)
{
byte[] outBuffer = null;
do
{
int chunkBytes = Math.Min(count, NegoState.MaxWriteDataSize);
int encryptedBytes;
try
{
encryptedBytes = _negoState.EncryptData(buffer, offset, chunkBytes, ref outBuffer);
}
catch (Exception e)
{
throw new IOException(SR.net_io_encrypt, e);
}
if (asyncRequest != null)
{
// prepare for the next request
asyncRequest.SetNextRequest(buffer, offset + chunkBytes, count - chunkBytes, null);
IAsyncResult ar = InnerStreamAPM.BeginWrite(outBuffer, 0, encryptedBytes, s_writeCallback, asyncRequest);
if (!ar.CompletedSynchronously)
{
return;
}
InnerStreamAPM.EndWrite(ar);
}
else
{
InnerStream.Write(outBuffer, 0, encryptedBytes);
}
offset += chunkBytes;
count -= chunkBytes;
} while (count != 0);
}
if (asyncRequest != null)
{
asyncRequest.CompleteUser();
}
}
//
// Combined sync/async read method. For sync request asyncRequest==null.
// There is a little overhead because we need to pass buffer/offset/count used only in sync.
// Still the benefit is that we have a common sync/async code path.
//
private int ProcessRead(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
ValidateParameters(buffer, offset, count);
if (Interlocked.Exchange(ref _NestedRead, 1) == 1)
{
throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, (asyncRequest != null ? "BeginRead" : "Read"), "read"));
}
bool failed = false;
try
{
if (InternalBufferCount != 0)
{
int copyBytes = InternalBufferCount > count ? count : InternalBufferCount;
if (copyBytes != 0)
{
Buffer.BlockCopy(InternalBuffer, InternalOffset, buffer, offset, copyBytes);
DecrementInternalBufferCount(copyBytes);
}
if (asyncRequest != null)
{
asyncRequest.CompleteUser((object)copyBytes);
}
return copyBytes;
}
// Performing actual I/O.
return StartReading(buffer, offset, count, asyncRequest);
}
catch (Exception e)
{
failed = true;
if (e is IOException)
{
throw;
}
throw new IOException(SR.net_io_read, e);
}
finally
{
if (asyncRequest == null || failed)
{
_NestedRead = 0;
}
}
}
//
// To avoid recursion when 0 bytes have been decrypted, loop until decryption results in at least 1 byte.
//
private int StartReading(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
int result;
// When we read -1 bytes means we have decrypted 0 bytes, need looping.
while ((result = StartFrameHeader(buffer, offset, count, asyncRequest)) == -1);
return result;
}
private int StartFrameHeader(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
int readBytes = 0;
if (asyncRequest != null)
{
asyncRequest.SetNextRequest(_ReadHeader, 0, _ReadHeader.Length, s_readCallback);
_FrameReader.AsyncReadPacket(asyncRequest);
if (!asyncRequest.MustCompleteSynchronously)
{
return 0;
}
readBytes = asyncRequest.Result;
}
else
{
readBytes = _FrameReader.ReadPacket(_ReadHeader, 0, _ReadHeader.Length);
}
return StartFrameBody(readBytes, buffer, offset, count, asyncRequest);
}
private int StartFrameBody(int readBytes, byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
if (readBytes == 0)
{
//EOF
if (asyncRequest != null)
{
asyncRequest.CompleteUser((object)0);
}
return 0;
}
if (!(readBytes == _ReadHeader.Length))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.AssertFormat("NegoStream::ProcessHeader()|Frame size must be 4 but received {0} bytes.", readBytes);
}
Debug.Fail("NegoStream::ProcessHeader()|Frame size must be 4 but received " + readBytes + " bytes.");
}
// Replace readBytes with the body size recovered from the header content.
readBytes = _ReadHeader[3];
readBytes = (readBytes << 8) | _ReadHeader[2];
readBytes = (readBytes << 8) | _ReadHeader[1];
readBytes = (readBytes << 8) | _ReadHeader[0];
//
// The body carries 4 bytes for trailer size slot plus trailer, hence <=4 frame size is always an error.
// Additionally we'd like to restrict the read frame size to 64k.
//
if (readBytes <= 4 || readBytes > NegoState.MaxReadFrameSize)
{
throw new IOException(SR.net_frame_read_size);
}
//
// Always pass InternalBuffer for SSPI "in place" decryption.
// A user buffer can be shared by many threads in that case decryption/integrity check may fail cause of data corruption.
//
EnsureInternalBufferSize(readBytes);
if (asyncRequest != null)
{
asyncRequest.SetNextRequest(InternalBuffer, 0, readBytes, s_readCallback);
_FrameReader.AsyncReadPacket(asyncRequest);
if (!asyncRequest.MustCompleteSynchronously)
{
return 0;
}
readBytes = asyncRequest.Result;
}
else //Sync
{
readBytes = _FrameReader.ReadPacket(InternalBuffer, 0, readBytes);
}
return ProcessFrameBody(readBytes, buffer, offset, count, asyncRequest);
}
private int ProcessFrameBody(int readBytes, byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
if (readBytes == 0)
{
// We already checked that the frame body is bigger than 0 bytes
// Hence, this is an EOF ... fire.
throw new IOException(SR.net_io_eof);
}
// Decrypt into internal buffer, change "readBytes" to count now _Decrypted Bytes_
int internalOffset;
readBytes = _negoState.DecryptData(InternalBuffer, 0, readBytes, out internalOffset);
// Decrypted data start from zero offset, the size can be shrunk after decryption.
AdjustInternalBufferOffsetSize(readBytes, internalOffset);
if (readBytes == 0 && count != 0)
{
// Read again.
return -1;
}
if (readBytes > count)
{
readBytes = count;
}
Buffer.BlockCopy(InternalBuffer, InternalOffset, buffer, offset, readBytes);
// This will adjust both the remaining internal buffer count and the offset.
DecrementInternalBufferCount(readBytes);
if (asyncRequest != null)
{
asyncRequest.CompleteUser((object)readBytes);
}
return readBytes;
}
private static void WriteCallback(IAsyncResult transportResult)
{
if (transportResult.CompletedSynchronously)
{
return;
}
if (!(transportResult.AsyncState is AsyncProtocolRequest))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("NegotiateSteam::WriteCallback|State type is wrong, expected AsyncProtocolRequest.");
}
Debug.Fail("NegotiateSteam::WriteCallback|State type is wrong, expected AsyncProtocolRequest.");
}
AsyncProtocolRequest asyncRequest = (AsyncProtocolRequest)transportResult.AsyncState;
try
{
NegotiateStream negoStream = (NegotiateStream)asyncRequest.AsyncObject;
negoStream.InnerStreamAPM.EndWrite(transportResult);
if (asyncRequest.Count == 0)
{
// This was the last chunk.
asyncRequest.Count = -1;
}
negoStream.StartWriting(asyncRequest.Buffer, asyncRequest.Offset, asyncRequest.Count, asyncRequest);
}
catch (Exception e)
{
if (asyncRequest.IsUserCompleted)
{
// This will throw on a worker thread.
throw;
}
asyncRequest.CompleteWithError(e);
}
}
private static void ReadCallback(AsyncProtocolRequest asyncRequest)
{
// Async ONLY completion.
try
{
NegotiateStream negoStream = (NegotiateStream)asyncRequest.AsyncObject;
BufferAsyncResult bufferResult = (BufferAsyncResult)asyncRequest.UserAsyncResult;
// This is an optimization to avoid an additional callback.
if ((object)asyncRequest.Buffer == (object)negoStream._ReadHeader)
{
negoStream.StartFrameBody(asyncRequest.Result, bufferResult.Buffer, bufferResult.Offset, bufferResult.Count, asyncRequest);
}
else
{
if (-1 == negoStream.ProcessFrameBody(asyncRequest.Result, bufferResult.Buffer, bufferResult.Offset, bufferResult.Count, asyncRequest))
{
// In case we decrypted 0 bytes, start another reading.
negoStream.StartReading(bufferResult.Buffer, bufferResult.Offset, bufferResult.Count, asyncRequest);
}
}
}
catch (Exception e)
{
if (asyncRequest.IsUserCompleted)
{
// This will throw on a worker thread.
throw;
}
asyncRequest.CompleteWithError(e);
}
}
}
}
| |
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Composing;
using Umbraco.Cms.Core.Strings;
namespace Umbraco.Extensions
{
public static class TypeExtensions
{
public static object GetDefaultValue(this Type t)
{
return t.IsValueType
? Activator.CreateInstance(t)
: null;
}
internal static MethodInfo GetGenericMethod(this Type type, string name, params Type[] parameterTypes)
{
var methods = type.GetMethods().Where(method => method.Name == name);
foreach (var method in methods)
{
if (method.HasParameters(parameterTypes))
return method;
}
return null;
}
/// <summary>
/// Checks if the type is an anonymous type
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
/// <remarks>
/// reference: http://jclaes.blogspot.com/2011/05/checking-for-anonymous-types.html
/// </remarks>
public static bool IsAnonymousType(this Type type)
{
if (type == null) throw new ArgumentNullException("type");
return Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false)
&& type.IsGenericType && type.Name.Contains("AnonymousType")
&& (type.Name.StartsWith("<>") || type.Name.StartsWith("VB$"))
&& (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic;
}
/// <summary>
/// Determines whether the specified type is enumerable.
/// </summary>
/// <param name="method">The type.</param>
/// <param name="parameterTypes"></param>
internal static bool HasParameters(this MethodInfo method, params Type[] parameterTypes)
{
var methodParameters = method.GetParameters().Select(parameter => parameter.ParameterType).ToArray();
if (methodParameters.Length != parameterTypes.Length)
return false;
for (int i = 0; i < methodParameters.Length; i++)
if (methodParameters[i].ToString() != parameterTypes[i].ToString())
return false;
return true;
}
public static IEnumerable<Type> GetBaseTypes(this Type type, bool andSelf)
{
if (andSelf)
yield return type;
while ((type = type.BaseType) != null)
yield return type;
}
public static IEnumerable<MethodInfo> AllMethods(this Type target)
{
//var allTypes = target.AllInterfaces().ToList();
var allTypes = target.GetInterfaces().ToList(); // GetInterfaces is ok here
allTypes.Add(target);
return allTypes.SelectMany(t => t.GetMethods());
}
/// <returns>
/// <c>true</c> if the specified type is enumerable; otherwise, <c>false</c>.
/// </returns>
public static bool IsEnumerable(this Type type)
{
if (type.IsGenericType)
{
if (type.GetGenericTypeDefinition().GetInterfaces().Contains(typeof(IEnumerable)))
return true;
}
else
{
if (type.GetInterfaces().Contains(typeof(IEnumerable)))
return true;
}
return false;
}
/// <summary>
/// Determines whether [is of generic type] [the specified type].
/// </summary>
/// <param name="type">The type.</param>
/// <param name="genericType">Type of the generic.</param>
/// <returns>
/// <c>true</c> if [is of generic type] [the specified type]; otherwise, <c>false</c>.
/// </returns>
public static bool IsOfGenericType(this Type type, Type genericType)
{
Type[] args;
return type.TryGetGenericArguments(genericType, out args);
}
/// <summary>
/// Will find the generic type of the 'type' parameter passed in that is equal to the 'genericType' parameter passed in
/// </summary>
/// <param name="type"></param>
/// <param name="genericType"></param>
/// <param name="genericArgType"></param>
/// <returns></returns>
public static bool TryGetGenericArguments(this Type type, Type genericType, out Type[] genericArgType)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
if (genericType == null)
{
throw new ArgumentNullException("genericType");
}
if (genericType.IsGenericType == false)
{
throw new ArgumentException("genericType must be a generic type");
}
Func<Type, Type, Type[]> checkGenericType = (@int, t) =>
{
if (@int.IsGenericType)
{
var def = @int.GetGenericTypeDefinition();
if (def == t)
{
return @int.GetGenericArguments();
}
}
return null;
};
//first, check if the type passed in is already the generic type
genericArgType = checkGenericType(type, genericType);
if (genericArgType != null)
return true;
//if we're looking for interfaces, enumerate them:
if (genericType.IsInterface)
{
foreach (Type @interface in type.GetInterfaces())
{
genericArgType = checkGenericType(@interface, genericType);
if (genericArgType != null)
return true;
}
}
else
{
//loop back into the base types as long as they are generic
while (type.BaseType != null && type.BaseType != typeof(object))
{
genericArgType = checkGenericType(type.BaseType, genericType);
if (genericArgType != null)
return true;
type = type.BaseType;
}
}
return false;
}
/// <summary>
/// Gets all properties in a flat hierarchy
/// </summary>
/// <remarks>Includes both Public and Non-Public properties</remarks>
/// <param name="type"></param>
/// <returns></returns>
public static PropertyInfo[] GetAllProperties(this Type type)
{
if (type.IsInterface)
{
var propertyInfos = new List<PropertyInfo>();
var considered = new List<Type>();
var queue = new Queue<Type>();
considered.Add(type);
queue.Enqueue(type);
while (queue.Count > 0)
{
var subType = queue.Dequeue();
foreach (var subInterface in subType.GetInterfaces())
{
if (considered.Contains(subInterface)) continue;
considered.Add(subInterface);
queue.Enqueue(subInterface);
}
var typeProperties = subType.GetProperties(
BindingFlags.FlattenHierarchy
| BindingFlags.Public
| BindingFlags.NonPublic
| BindingFlags.Instance);
var newPropertyInfos = typeProperties
.Where(x => !propertyInfos.Contains(x));
propertyInfos.InsertRange(0, newPropertyInfos);
}
return propertyInfos.ToArray();
}
return type.GetProperties(BindingFlags.FlattenHierarchy
| BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
}
/// <summary>
/// Returns all public properties including inherited properties even for interfaces
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
/// <remarks>
/// taken from http://stackoverflow.com/questions/358835/getproperties-to-return-all-properties-for-an-interface-inheritance-hierarchy
/// </remarks>
public static PropertyInfo[] GetPublicProperties(this Type type)
{
if (type.IsInterface)
{
var propertyInfos = new List<PropertyInfo>();
var considered = new List<Type>();
var queue = new Queue<Type>();
considered.Add(type);
queue.Enqueue(type);
while (queue.Count > 0)
{
var subType = queue.Dequeue();
foreach (var subInterface in subType.GetInterfaces())
{
if (considered.Contains(subInterface)) continue;
considered.Add(subInterface);
queue.Enqueue(subInterface);
}
var typeProperties = subType.GetProperties(
BindingFlags.FlattenHierarchy
| BindingFlags.Public
| BindingFlags.Instance);
var newPropertyInfos = typeProperties
.Where(x => !propertyInfos.Contains(x));
propertyInfos.InsertRange(0, newPropertyInfos);
}
return propertyInfos.ToArray();
}
return type.GetProperties(BindingFlags.FlattenHierarchy
| BindingFlags.Public | BindingFlags.Instance);
}
/// <summary>
/// Determines whether the specified actual type is type.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="actualType">The actual type.</param>
/// <returns>
/// <c>true</c> if the specified actual type is type; otherwise, <c>false</c>.
/// </returns>
public static bool IsType<T>(this Type actualType)
{
return TypeHelper.IsTypeAssignableFrom<T>(actualType);
}
public static bool Inherits<TBase>(this Type type)
{
return typeof(TBase).IsAssignableFrom(type);
}
public static bool Inherits(this Type type, Type tbase)
{
return tbase.IsAssignableFrom(type);
}
public static bool Implements<TInterface>(this Type type)
{
return typeof(TInterface).IsAssignableFrom(type);
}
public static TAttribute FirstAttribute<TAttribute>(this Type type)
{
return type.FirstAttribute<TAttribute>(true);
}
public static TAttribute FirstAttribute<TAttribute>(this Type type, bool inherit)
{
var attrs = type.GetCustomAttributes(typeof(TAttribute), inherit);
return (TAttribute)(attrs.Length > 0 ? attrs[0] : null);
}
public static TAttribute FirstAttribute<TAttribute>(this PropertyInfo propertyInfo)
{
return propertyInfo.FirstAttribute<TAttribute>(true);
}
public static TAttribute FirstAttribute<TAttribute>(this PropertyInfo propertyInfo, bool inherit)
{
var attrs = propertyInfo.GetCustomAttributes(typeof(TAttribute), inherit);
return (TAttribute)(attrs.Length > 0 ? attrs[0] : null);
}
public static IEnumerable<TAttribute> MultipleAttribute<TAttribute>(this PropertyInfo propertyInfo)
{
return propertyInfo.MultipleAttribute<TAttribute>(true);
}
public static IEnumerable<TAttribute> MultipleAttribute<TAttribute>(this PropertyInfo propertyInfo, bool inherit)
{
var attrs = propertyInfo.GetCustomAttributes(typeof(TAttribute), inherit);
return (attrs.Length > 0 ? attrs.ToList().ConvertAll(input => (TAttribute)input) : null);
}
/// <summary>
/// Returns the full type name with the assembly but without all of the assembly specific version information.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
/// <remarks>
/// This method is like an 'in between' of Type.FullName and Type.AssemblyQualifiedName which returns the type and the assembly separated
/// by a comma.
/// </remarks>
/// <example>
/// The output of this class would be:
///
/// Umbraco.Core.TypeExtensions, Umbraco.Core
/// </example>
public static string GetFullNameWithAssembly(this Type type)
{
var assemblyName = type.Assembly.GetName();
return string.Concat(type.FullName, ", ",
assemblyName.FullName.StartsWith("App_Code.") ? "App_Code" : assemblyName.Name);
}
/// <summary>
/// Determines whether an instance of a specified type can be assigned to the current type instance.
/// </summary>
/// <param name="type">The current type.</param>
/// <param name="c">The type to compare with the current type.</param>
/// <returns>A value indicating whether an instance of the specified type can be assigned to the current type instance.</returns>
/// <remarks>This extended version supports the current type being a generic type definition, and will
/// consider that eg <c>List{int}</c> is "assignable to" <c>IList{}</c>.</remarks>
public static bool IsAssignableFromGtd(this Type type, Type c)
{
// type *can* be a generic type definition
// c is a real type, cannot be a generic type definition
if (type.IsGenericTypeDefinition == false)
return type.IsAssignableFrom(c);
if (c.IsInterface == false)
{
var t = c;
while (t != typeof(object))
{
if (t.IsGenericType && t.GetGenericTypeDefinition() == type) return true;
t = t.BaseType;
}
}
return c.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == type);
}
/// <summary>
/// If the given <paramref name="type"/> is an array or some other collection
/// comprised of 0 or more instances of a "subtype", get that type
/// </summary>
/// <param name="type">the source type</param>
/// <returns></returns>
public static Type GetEnumeratedType(this Type type)
{
if (typeof(IEnumerable).IsAssignableFrom(type) == false)
return null;
// provided by Array
var elType = type.GetElementType();
if (null != elType) return elType;
// otherwise provided by collection
var elTypes = type.GetGenericArguments();
if (elTypes.Length > 0) return elTypes[0];
// otherwise is not an 'enumerated' type
return null;
}
public static T GetCustomAttribute<T>(this Type type, bool inherit)
where T : Attribute
{
return type.GetCustomAttributes<T>(inherit).SingleOrDefault();
}
public static IEnumerable<T> GetCustomAttributes<T>(this Type type, bool inherited)
where T : Attribute
{
if (type == null) return Enumerable.Empty<T>();
return type.GetCustomAttributes(typeof(T), inherited).OfType<T>();
}
public static bool HasCustomAttribute<T>(this Type type, bool inherit)
where T : Attribute
{
return type.GetCustomAttribute<T>(inherit) != null;
}
/// <summary>
/// Tries to return a value based on a property name for an object but ignores case sensitivity
/// </summary>
/// <param name="type"></param>
/// <param name="shortStringHelper"></param>
/// <param name="target"></param>
/// <param name="memberName"></param>
/// <returns></returns>
/// <remarks>
/// Currently this will only work for ProperCase and camelCase properties, see the TODO below to enable complete case insensitivity
/// </remarks>
internal static Attempt<object> GetMemberIgnoreCase(this Type type, IShortStringHelper shortStringHelper, object target, string memberName)
{
Func<string, Attempt<object>> getMember =
memberAlias =>
{
try
{
return Attempt<object>.Succeed(
type.InvokeMember(memberAlias,
System.Reflection.BindingFlags.GetProperty |
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.Public,
null,
target,
null));
}
catch (MissingMethodException ex)
{
return Attempt<object>.Fail(ex);
}
};
//try with the current casing
var attempt = getMember(memberName);
if (attempt.Success == false)
{
//if we cannot get with the current alias, try changing it's case
attempt = memberName[0].IsUpperCase()
? getMember(memberName.ToCleanString(shortStringHelper, CleanStringType.Ascii | CleanStringType.ConvertCase | CleanStringType.CamelCase))
: getMember(memberName.ToCleanString(shortStringHelper, CleanStringType.Ascii | CleanStringType.ConvertCase | CleanStringType.PascalCase));
// TODO: If this still fails then we should get a list of properties from the object and then compare - doing the above without listing
// all properties will surely be faster than using reflection to get ALL properties first and then query against them.
}
return attempt;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.Framework.OptionsModel;
using OmniSharp.Models;
using OmniSharp.Options;
using Xunit;
namespace OmniSharp.Tests
{
public class FormattingFacts
{
[Fact]
public void FindFormatTargetAtCurly()
{
AssertFormatTargetKind(SyntaxKind.ClassDeclaration, @"class C {}$");
AssertFormatTargetKind(SyntaxKind.InterfaceDeclaration, @"interface I {}$");
AssertFormatTargetKind(SyntaxKind.EnumDeclaration, @"enum E {}$");
AssertFormatTargetKind(SyntaxKind.StructDeclaration, @"struct S {}$");
AssertFormatTargetKind(SyntaxKind.NamespaceDeclaration, @"namespace N {}$");
AssertFormatTargetKind(SyntaxKind.MethodDeclaration, @"
class C {
public void M(){}$
}");
AssertFormatTargetKind(SyntaxKind.ObjectInitializerExpression, @"
class C {
public void M(){
new T() {
A = 6,
B = 7
}$
}
}");
AssertFormatTargetKind(SyntaxKind.ForStatement, @"
class C {
public void M ()
{
for(;;){}$
}
}");
}
[Fact]
public void FindFormatTargetAtSemiColon()
{
AssertFormatTargetKind(SyntaxKind.FieldDeclaration, @"
class C {
private int F;$
}");
AssertFormatTargetKind(SyntaxKind.LocalDeclarationStatement, @"
class C {
public void M()
{
var a = 1234;$
}
}");
AssertFormatTargetKind(SyntaxKind.ReturnStatement, @"
class C {
public int M()
{
return 1234;$
}
}");
AssertFormatTargetKind(SyntaxKind.ForStatement, @"
class C {
public void M ()
{
for(var i = 0;$)
}
}");
AssertFormatTargetKind(SyntaxKind.ForStatement, @"
class C {
public void M ()
{
for(var i = 0;$) {}
}
}");
AssertFormatTargetKind(SyntaxKind.ForStatement, @"
class C {
public void M ()
{
for(var i = 0; i < 8;$)
}
}");
}
private void AssertFormatTargetKind(SyntaxKind kind, string source)
{
var tuple = GetTreeAndOffset(source);
var target = Formatting.FindFormatTarget(tuple.Item1, tuple.Item2);
if (target == null)
{
Assert.Null(kind);
}
else
{
Assert.Equal(kind, target.Kind());
}
}
private Tuple<SyntaxTree, int> GetTreeAndOffset(string value)
{
var idx = value.IndexOf('$');
if (idx <= 0)
{
Assert.True(false);
}
value = value.Remove(idx, 1);
idx = idx - 1;
return Tuple.Create(CSharpSyntaxTree.ParseText(value), idx);
}
[Fact]
public async Task TextChangesAreSortedLastFirst_SingleLine()
{
var source = new[]{
"class Program",
"{",
" public static void Main(){",
"> Thread.Sleep( 25000);<",
" }",
"}",
};
await AssertTextChanges(string.Join(Environment.NewLine, source),
new LinePositionSpanTextChange() { StartLine = 4, StartColumn = 21, EndLine = 4, EndColumn = 22, NewText = "" },
new LinePositionSpanTextChange() { StartLine = 4, StartColumn = 8, EndLine = 4, EndColumn = 8, NewText = " " });
}
[Fact]
public async Task TextChangesAreSortedLastFirst_MultipleLines()
{
var source = new[]{
"class Program",
"{",
" public static void Main()>{",
" Thread.Sleep( 25000);<",
" }",
"}",
};
await AssertTextChanges(string.Join(Environment.NewLine, source),
new LinePositionSpanTextChange() { StartLine = 4, StartColumn = 21, EndLine = 4, EndColumn = 22, NewText = "" },
new LinePositionSpanTextChange() { StartLine = 4, StartColumn = 8, EndLine = 4, EndColumn = 8, NewText = " " },
new LinePositionSpanTextChange() { StartLine = 3, StartColumn = 30, EndLine = 3, EndColumn = 30, NewText = "\r\n" });
}
private static FormatRangeRequest NewRequest(string source)
{
var startLoc = TestHelpers.GetLineAndColumnFromIndex(source, source.IndexOf(">"));
source = source.Replace(">", string.Empty);
var endLoc = TestHelpers.GetLineAndColumnFromIndex(source, source.IndexOf("<"));
source = source.Replace("<", string.Empty);
return new FormatRangeRequest() {
Buffer = source,
FileName = "a.cs",
Line = startLoc.Line,
Column = startLoc.Column,
EndLine = endLoc.Line,
EndColumn = endLoc.Column
};
}
private static async Task AssertTextChanges(string source, params LinePositionSpanTextChange[] expected)
{
var request = NewRequest(source);
var actual = await FormattingChangesForRange(request);
var enumer = actual.GetEnumerator();
for (var i = 0; enumer.MoveNext(); i++)
{
Assert.Equal(expected[i].NewText, enumer.Current.NewText);
Assert.Equal(expected[i].StartLine, enumer.Current.StartLine);
Assert.Equal(expected[i].StartColumn, enumer.Current.StartColumn);
Assert.Equal(expected[i].EndLine, enumer.Current.EndLine);
Assert.Equal(expected[i].EndColumn, enumer.Current.EndColumn);
}
}
private static async Task<IEnumerable<LinePositionSpanTextChange>> FormattingChangesForRange(FormatRangeRequest req)
{
var workspace = TestHelpers.CreateSimpleWorkspace(req.Buffer, req.FileName);
var controller = new OmnisharpController(workspace, null);
return (await controller.FormatRange(req)).Changes;
}
[Fact]
public async Task FormatRespectsIndentationSize()
{
var source = "namespace Bar\n{\n class Foo {}\n}";
var workspace = TestHelpers.CreateSimpleWorkspace(source);
var controller = new OmnisharpController(workspace, new FakeOmniSharpOptions
{
Options = new OmniSharpOptions
{
FormattingOptions = new FormattingOptions
{
NewLine = "\n",
IndentationSize = 1
}
}
});
var result = await controller.FormatDocument(new Request
{
FileName = "dummy.cs"
});
Assert.Equal("namespace Bar\n{\n class Foo { }\n}", result.Buffer);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
namespace System
{
/*
Customized format patterns:
P.S. Format in the table below is the internal number format used to display the pattern.
Patterns Format Description Example
========= ========== ===================================== ========
"h" "0" hour (12-hour clock)w/o leading zero 3
"hh" "00" hour (12-hour clock)with leading zero 03
"hh*" "00" hour (12-hour clock)with leading zero 03
"H" "0" hour (24-hour clock)w/o leading zero 8
"HH" "00" hour (24-hour clock)with leading zero 08
"HH*" "00" hour (24-hour clock) 08
"m" "0" minute w/o leading zero
"mm" "00" minute with leading zero
"mm*" "00" minute with leading zero
"s" "0" second w/o leading zero
"ss" "00" second with leading zero
"ss*" "00" second with leading zero
"f" "0" second fraction (1 digit)
"ff" "00" second fraction (2 digit)
"fff" "000" second fraction (3 digit)
"ffff" "0000" second fraction (4 digit)
"fffff" "00000" second fraction (5 digit)
"ffffff" "000000" second fraction (6 digit)
"fffffff" "0000000" second fraction (7 digit)
"F" "0" second fraction (up to 1 digit)
"FF" "00" second fraction (up to 2 digit)
"FFF" "000" second fraction (up to 3 digit)
"FFFF" "0000" second fraction (up to 4 digit)
"FFFFF" "00000" second fraction (up to 5 digit)
"FFFFFF" "000000" second fraction (up to 6 digit)
"FFFFFFF" "0000000" second fraction (up to 7 digit)
"t" first character of AM/PM designator A
"tt" AM/PM designator AM
"tt*" AM/PM designator PM
"d" "0" day w/o leading zero 1
"dd" "00" day with leading zero 01
"ddd" short weekday name (abbreviation) Mon
"dddd" full weekday name Monday
"dddd*" full weekday name Monday
"M" "0" month w/o leading zero 2
"MM" "00" month with leading zero 02
"MMM" short month name (abbreviation) Feb
"MMMM" full month name Febuary
"MMMM*" full month name Febuary
"y" "0" two digit year (year % 100) w/o leading zero 0
"yy" "00" two digit year (year % 100) with leading zero 00
"yyy" "D3" year 2000
"yyyy" "D4" year 2000
"yyyyy" "D5" year 2000
...
"z" "+0;-0" timezone offset w/o leading zero -8
"zz" "+00;-00" timezone offset with leading zero -08
"zzz" "+00;-00" for hour offset, "00" for minute offset full timezone offset -07:30
"zzz*" "+00;-00" for hour offset, "00" for minute offset full timezone offset -08:00
"K" -Local "zzz", e.g. -08:00
-Utc "'Z'", representing UTC
-Unspecified ""
-DateTimeOffset "zzzzz" e.g -07:30:15
"g*" the current era name A.D.
":" time separator : -- DEPRECATED - Insert separator directly into pattern (eg: "H.mm.ss")
"/" date separator /-- DEPRECATED - Insert separator directly into pattern (eg: "M-dd-yyyy")
"'" quoted string 'ABC' will insert ABC into the formatted string.
'"' quoted string "ABC" will insert ABC into the formatted string.
"%" used to quote a single pattern characters E.g.The format character "%y" is to print two digit year.
"\" escaped character E.g. '\d' insert the character 'd' into the format string.
other characters insert the character into the format string.
Pre-defined format characters:
(U) to indicate Universal time is used.
(G) to indicate Gregorian calendar is used.
Format Description Real format Example
========= ================================= ====================== =======================
"d" short date culture-specific 10/31/1999
"D" long data culture-specific Sunday, October 31, 1999
"f" full date (long date + short time) culture-specific Sunday, October 31, 1999 2:00 AM
"F" full date (long date + long time) culture-specific Sunday, October 31, 1999 2:00:00 AM
"g" general date (short date + short time) culture-specific 10/31/1999 2:00 AM
"G" general date (short date + long time) culture-specific 10/31/1999 2:00:00 AM
"m"/"M" Month/Day date culture-specific October 31
(G) "o"/"O" Round Trip XML "yyyy-MM-ddTHH:mm:ss.fffffffK" 1999-10-31 02:00:00.0000000Z
(G) "r"/"R" RFC 1123 date, "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'" Sun, 31 Oct 1999 10:00:00 GMT
(G) "s" Sortable format, based on ISO 8601. "yyyy-MM-dd'T'HH:mm:ss" 1999-10-31T02:00:00
('T' for local time)
"t" short time culture-specific 2:00 AM
"T" long time culture-specific 2:00:00 AM
(G) "u" Universal time with sortable format, "yyyy'-'MM'-'dd HH':'mm':'ss'Z'" 1999-10-31 10:00:00Z
based on ISO 8601.
(U) "U" Universal time with full culture-specific Sunday, October 31, 1999 10:00:00 AM
(long date + long time) format
"y"/"Y" Year/Month day culture-specific October, 1999
*/
//This class contains only static members and does not require the serializable attribute.
internal static
class DateTimeFormat
{
internal const int MaxSecondsFractionDigits = 7;
internal static readonly TimeSpan NullOffset = TimeSpan.MinValue;
internal static char[] allStandardFormats =
{
'd', 'D', 'f', 'F', 'g', 'G',
'm', 'M', 'o', 'O', 'r', 'R',
's', 't', 'T', 'u', 'U', 'y', 'Y',
};
internal const String RoundtripFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK";
internal const String RoundtripDateTimeUnfixed = "yyyy'-'MM'-'ddTHH':'mm':'ss zzz";
private const int DEFAULT_ALL_DATETIMES_SIZE = 132;
internal static readonly DateTimeFormatInfo InvariantFormatInfo = CultureInfo.InvariantCulture.DateTimeFormat;
internal static readonly string[] InvariantAbbreviatedMonthNames = InvariantFormatInfo.AbbreviatedMonthNames;
internal static readonly string[] InvariantAbbreviatedDayNames = InvariantFormatInfo.AbbreviatedDayNames;
internal const string Gmt = "GMT";
internal static String[] fixedNumberFormats = new String[] {
"0",
"00",
"000",
"0000",
"00000",
"000000",
"0000000",
};
////////////////////////////////////////////////////////////////////////////
//
// Format the positive integer value to a string and perfix with assigned
// length of leading zero.
//
// Parameters:
// value: The value to format
// len: The maximum length for leading zero.
// If the digits of the value is greater than len, no leading zero is added.
//
// Notes:
// The function can format to Int32.MaxValue.
//
////////////////////////////////////////////////////////////////////////////
internal static void FormatDigits(StringBuilder outputBuffer, int value, int len)
{
Debug.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0");
FormatDigits(outputBuffer, value, len, false);
}
internal unsafe static void FormatDigits(StringBuilder outputBuffer, int value, int len, bool overrideLengthLimit)
{
Debug.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0");
// Limit the use of this function to be two-digits, so that we have the same behavior
// as RTM bits.
if (!overrideLengthLimit && len > 2)
{
len = 2;
}
char* buffer = stackalloc char[16];
char* p = buffer + 16;
int n = value;
do
{
*--p = (char)(n % 10 + '0');
n /= 10;
} while ((n != 0) && (p > buffer));
int digits = (int)(buffer + 16 - p);
//If the repeat count is greater than 0, we're trying
//to emulate the "00" format, so we have to prepend
//a zero if the string only has one character.
while ((digits < len) && (p > buffer))
{
*--p = '0';
digits++;
}
outputBuffer.Append(p, digits);
}
private static void HebrewFormatDigits(StringBuilder outputBuffer, int digits)
{
outputBuffer.Append(HebrewNumber.ToString(digits));
}
internal static int ParseRepeatPattern(String format, int pos, char patternChar)
{
int len = format.Length;
int index = pos + 1;
while ((index < len) && (format[index] == patternChar))
{
index++;
}
return (index - pos);
}
private static String FormatDayOfWeek(int dayOfWeek, int repeat, DateTimeFormatInfo dtfi)
{
Debug.Assert(dayOfWeek >= 0 && dayOfWeek <= 6, "dayOfWeek >= 0 && dayOfWeek <= 6");
if (repeat == 3)
{
return (dtfi.GetAbbreviatedDayName((DayOfWeek)dayOfWeek));
}
// Call dtfi.GetDayName() here, instead of accessing DayNames property, because we don't
// want a clone of DayNames, which will hurt perf.
return (dtfi.GetDayName((DayOfWeek)dayOfWeek));
}
private static String FormatMonth(int month, int repeatCount, DateTimeFormatInfo dtfi)
{
Debug.Assert(month >= 1 && month <= 12, "month >=1 && month <= 12");
if (repeatCount == 3)
{
return (dtfi.GetAbbreviatedMonthName(month));
}
// Call GetMonthName() here, instead of accessing MonthNames property, because we don't
// want a clone of MonthNames, which will hurt perf.
return (dtfi.GetMonthName(month));
}
//
// FormatHebrewMonthName
//
// Action: Return the Hebrew month name for the specified DateTime.
// Returns: The month name string for the specified DateTime.
// Arguments:
// time the time to format
// month The month is the value of HebrewCalendar.GetMonth(time).
// repeat Return abbreviated month name if repeat=3, or full month name if repeat=4
// dtfi The DateTimeFormatInfo which uses the Hebrew calendars as its calendar.
// Exceptions: None.
//
/* Note:
If DTFI is using Hebrew calendar, GetMonthName()/GetAbbreviatedMonthName() will return month names like this:
1 Hebrew 1st Month
2 Hebrew 2nd Month
.. ...
6 Hebrew 6th Month
7 Hebrew 6th Month II (used only in a leap year)
8 Hebrew 7th Month
9 Hebrew 8th Month
10 Hebrew 9th Month
11 Hebrew 10th Month
12 Hebrew 11th Month
13 Hebrew 12th Month
Therefore, if we are in a regular year, we have to increment the month name if moth is greater or eqaul to 7.
*/
private static String FormatHebrewMonthName(DateTime time, int month, int repeatCount, DateTimeFormatInfo dtfi)
{
Debug.Assert(repeatCount != 3 || repeatCount != 4, "repeateCount should be 3 or 4");
if (dtfi.Calendar.IsLeapYear(dtfi.Calendar.GetYear(time)))
{
// This month is in a leap year
return (dtfi.internalGetMonthName(month, MonthNameStyles.LeapYear, (repeatCount == 3)));
}
// This is in a regular year.
if (month >= 7)
{
month++;
}
if (repeatCount == 3)
{
return (dtfi.GetAbbreviatedMonthName(month));
}
return (dtfi.GetMonthName(month));
}
//
// The pos should point to a quote character. This method will
// append to the result StringBuilder the string encloed by the quote character.
//
internal static int ParseQuoteString(String format, int pos, StringBuilder result)
{
//
// NOTE : pos will be the index of the quote character in the 'format' string.
//
int formatLen = format.Length;
int beginPos = pos;
char quoteChar = format[pos++]; // Get the character used to quote the following string.
bool foundQuote = false;
while (pos < formatLen)
{
char ch = format[pos++];
if (ch == quoteChar)
{
foundQuote = true;
break;
}
else if (ch == '\\')
{
// The following are used to support escaped character.
// Escaped character is also supported in the quoted string.
// Therefore, someone can use a format like "'minute:' mm\"" to display:
// minute: 45"
// because the second double quote is escaped.
if (pos < formatLen)
{
result.Append(format[pos++]);
}
else
{
//
// This means that '\' is at the end of the formatting string.
//
throw new FormatException(SR.Format_InvalidString);
}
}
else
{
result.Append(ch);
}
}
if (!foundQuote)
{
// Here we can't find the matching quote.
throw new FormatException(
String.Format(
CultureInfo.CurrentCulture,
SR.Format_BadQuote, quoteChar));
}
//
// Return the character count including the begin/end quote characters and enclosed string.
//
return (pos - beginPos);
}
//
// Get the next character at the index of 'pos' in the 'format' string.
// Return value of -1 means 'pos' is already at the end of the 'format' string.
// Otherwise, return value is the int value of the next character.
//
internal static int ParseNextChar(String format, int pos)
{
if (pos >= format.Length - 1)
{
return (-1);
}
return ((int)format[pos + 1]);
}
//
// IsUseGenitiveForm
//
// Actions: Check the format to see if we should use genitive month in the formatting.
// Starting at the position (index) in the (format) string, look back and look ahead to
// see if there is "d" or "dd". In the case like "d MMMM" or "MMMM dd", we can use
// genitive form. Genitive form is not used if there is more than two "d".
// Arguments:
// format The format string to be scanned.
// index Where we should start the scanning. This is generally where "M" starts.
// tokenLen The len of the current pattern character. This indicates how many "M" that we have.
// patternToMatch The pattern that we want to search. This generally uses "d"
//
private static bool IsUseGenitiveForm(String format, int index, int tokenLen, char patternToMatch)
{
int i;
int repeat = 0;
//
// Look back to see if we can find "d" or "ddd"
//
// Find first "d".
for (i = index - 1; i >= 0 && format[i] != patternToMatch; i--) { /*Do nothing here */ };
if (i >= 0)
{
// Find a "d", so look back to see how many "d" that we can find.
while (--i >= 0 && format[i] == patternToMatch)
{
repeat++;
}
//
// repeat == 0 means that we have one (patternToMatch)
// repeat == 1 means that we have two (patternToMatch)
//
if (repeat <= 1)
{
return (true);
}
// Note that we can't just stop here. We may find "ddd" while looking back, and we have to look
// ahead to see if there is "d" or "dd".
}
//
// If we can't find "d" or "dd" by looking back, try look ahead.
//
// Find first "d"
for (i = index + tokenLen; i < format.Length && format[i] != patternToMatch; i++) { /* Do nothing here */ };
if (i < format.Length)
{
repeat = 0;
// Find a "d", so contine the walk to see how may "d" that we can find.
while (++i < format.Length && format[i] == patternToMatch)
{
repeat++;
}
//
// repeat == 0 means that we have one (patternToMatch)
// repeat == 1 means that we have two (patternToMatch)
//
if (repeat <= 1)
{
return (true);
}
}
return (false);
}
//
// FormatCustomized
//
// Actions: Format the DateTime instance using the specified format.
//
private static String FormatCustomized(DateTime dateTime, String format, DateTimeFormatInfo dtfi, TimeSpan offset)
{
Calendar cal = dtfi.Calendar;
StringBuilder result = StringBuilderCache.Acquire();
// This is a flag to indicate if we are format the dates using Hebrew calendar.
bool isHebrewCalendar = (cal.ID == CalendarId.HEBREW);
// This is a flag to indicate if we are formating hour/minute/second only.
bool bTimeOnly = true;
int i = 0;
int tokenLen, hour12;
while (i < format.Length)
{
char ch = format[i];
int nextChar;
switch (ch)
{
case 'g':
tokenLen = ParseRepeatPattern(format, i, ch);
result.Append(dtfi.GetEraName(cal.GetEra(dateTime)));
break;
case 'h':
tokenLen = ParseRepeatPattern(format, i, ch);
hour12 = dateTime.Hour % 12;
if (hour12 == 0)
{
hour12 = 12;
}
FormatDigits(result, hour12, tokenLen);
break;
case 'H':
tokenLen = ParseRepeatPattern(format, i, ch);
FormatDigits(result, dateTime.Hour, tokenLen);
break;
case 'm':
tokenLen = ParseRepeatPattern(format, i, ch);
FormatDigits(result, dateTime.Minute, tokenLen);
break;
case 's':
tokenLen = ParseRepeatPattern(format, i, ch);
FormatDigits(result, dateTime.Second, tokenLen);
break;
case 'f':
case 'F':
tokenLen = ParseRepeatPattern(format, i, ch);
if (tokenLen <= MaxSecondsFractionDigits)
{
long fraction = (dateTime.Ticks % Calendar.TicksPerSecond);
fraction = fraction / (long)Math.Pow(10, 7 - tokenLen);
if (ch == 'f')
{
result.Append(((int)fraction).ToString(fixedNumberFormats[tokenLen - 1], CultureInfo.InvariantCulture));
}
else
{
int effectiveDigits = tokenLen;
while (effectiveDigits > 0)
{
if (fraction % 10 == 0)
{
fraction = fraction / 10;
effectiveDigits--;
}
else
{
break;
}
}
if (effectiveDigits > 0)
{
result.Append(((int)fraction).ToString(fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture));
}
else
{
// No fraction to emit, so see if we should remove decimal also.
if (result.Length > 0 && result[result.Length - 1] == '.')
{
result.Remove(result.Length - 1, 1);
}
}
}
}
else
{
throw new FormatException(SR.Format_InvalidString);
}
break;
case 't':
tokenLen = ParseRepeatPattern(format, i, ch);
if (tokenLen == 1)
{
if (dateTime.Hour < 12)
{
if (dtfi.AMDesignator.Length >= 1)
{
result.Append(dtfi.AMDesignator[0]);
}
}
else
{
if (dtfi.PMDesignator.Length >= 1)
{
result.Append(dtfi.PMDesignator[0]);
}
}
}
else
{
result.Append((dateTime.Hour < 12 ? dtfi.AMDesignator : dtfi.PMDesignator));
}
break;
case 'd':
//
// tokenLen == 1 : Day of month as digits with no leading zero.
// tokenLen == 2 : Day of month as digits with leading zero for single-digit months.
// tokenLen == 3 : Day of week as a three-leter abbreviation.
// tokenLen >= 4 : Day of week as its full name.
//
tokenLen = ParseRepeatPattern(format, i, ch);
if (tokenLen <= 2)
{
int day = cal.GetDayOfMonth(dateTime);
if (isHebrewCalendar)
{
// For Hebrew calendar, we need to convert numbers to Hebrew text for yyyy, MM, and dd values.
HebrewFormatDigits(result, day);
}
else
{
FormatDigits(result, day, tokenLen);
}
}
else
{
int dayOfWeek = (int)cal.GetDayOfWeek(dateTime);
result.Append(FormatDayOfWeek(dayOfWeek, tokenLen, dtfi));
}
bTimeOnly = false;
break;
case 'M':
//
// tokenLen == 1 : Month as digits with no leading zero.
// tokenLen == 2 : Month as digits with leading zero for single-digit months.
// tokenLen == 3 : Month as a three-letter abbreviation.
// tokenLen >= 4 : Month as its full name.
//
tokenLen = ParseRepeatPattern(format, i, ch);
int month = cal.GetMonth(dateTime);
if (tokenLen <= 2)
{
if (isHebrewCalendar)
{
// For Hebrew calendar, we need to convert numbers to Hebrew text for yyyy, MM, and dd values.
HebrewFormatDigits(result, month);
}
else
{
FormatDigits(result, month, tokenLen);
}
}
else
{
if (isHebrewCalendar)
{
result.Append(FormatHebrewMonthName(dateTime, month, tokenLen, dtfi));
}
else
{
if ((dtfi.FormatFlags & DateTimeFormatFlags.UseGenitiveMonth) != 0 && tokenLen >= 4)
{
result.Append(
dtfi.internalGetMonthName(
month,
IsUseGenitiveForm(format, i, tokenLen, 'd') ? MonthNameStyles.Genitive : MonthNameStyles.Regular,
false));
}
else
{
result.Append(FormatMonth(month, tokenLen, dtfi));
}
}
}
bTimeOnly = false;
break;
case 'y':
// Notes about OS behavior:
// y: Always print (year % 100). No leading zero.
// yy: Always print (year % 100) with leading zero.
// yyy/yyyy/yyyyy/... : Print year value. No leading zero.
int year = cal.GetYear(dateTime);
tokenLen = ParseRepeatPattern(format, i, ch);
if (dtfi.HasForceTwoDigitYears)
{
FormatDigits(result, year, tokenLen <= 2 ? tokenLen : 2);
}
else if (cal.ID == CalendarId.HEBREW)
{
HebrewFormatDigits(result, year);
}
else
{
if (tokenLen <= 2)
{
FormatDigits(result, year % 100, tokenLen);
}
else
{
String fmtPattern = "D" + tokenLen.ToString();
result.Append(year.ToString(fmtPattern, CultureInfo.InvariantCulture));
}
}
bTimeOnly = false;
break;
case 'z':
tokenLen = ParseRepeatPattern(format, i, ch);
FormatCustomizedTimeZone(dateTime, offset, format, tokenLen, bTimeOnly, result);
break;
case 'K':
tokenLen = 1;
FormatCustomizedRoundripTimeZone(dateTime, offset, result);
break;
case ':':
result.Append(dtfi.TimeSeparator);
tokenLen = 1;
break;
case '/':
result.Append(dtfi.DateSeparator);
tokenLen = 1;
break;
case '\'':
case '\"':
tokenLen = ParseQuoteString(format, i, result);
break;
case '%':
// Optional format character.
// For example, format string "%d" will print day of month
// without leading zero. Most of the cases, "%" can be ignored.
nextChar = ParseNextChar(format, i);
// nextChar will be -1 if we already reach the end of the format string.
// Besides, we will not allow "%%" appear in the pattern.
if (nextChar >= 0 && nextChar != (int)'%')
{
result.Append(FormatCustomized(dateTime, ((char)nextChar).ToString(), dtfi, offset));
tokenLen = 2;
}
else
{
//
// This means that '%' is at the end of the format string or
// "%%" appears in the format string.
//
throw new FormatException(SR.Format_InvalidString);
}
break;
case '\\':
// Escaped character. Can be used to insert character into the format string.
// For exmple, "\d" will insert the character 'd' into the string.
//
// NOTENOTE : we can remove this format character if we enforce the enforced quote
// character rule.
// That is, we ask everyone to use single quote or double quote to insert characters,
// then we can remove this character.
//
nextChar = ParseNextChar(format, i);
if (nextChar >= 0)
{
result.Append(((char)nextChar));
tokenLen = 2;
}
else
{
//
// This means that '\' is at the end of the formatting string.
//
throw new FormatException(SR.Format_InvalidString);
}
break;
default:
// NOTENOTE : we can remove this rule if we enforce the enforced quote
// character rule.
// That is, if we ask everyone to use single quote or double quote to insert characters,
// then we can remove this default block.
result.Append(ch);
tokenLen = 1;
break;
}
i += tokenLen;
}
return StringBuilderCache.GetStringAndRelease(result);
}
// output the 'z' famliy of formats, which output a the offset from UTC, e.g. "-07:30"
private static void FormatCustomizedTimeZone(DateTime dateTime, TimeSpan offset, String format, Int32 tokenLen, Boolean timeOnly, StringBuilder result)
{
// See if the instance already has an offset
Boolean dateTimeFormat = (offset == NullOffset);
if (dateTimeFormat)
{
// No offset. The instance is a DateTime and the output should be the local time zone
if (timeOnly && dateTime.Ticks < Calendar.TicksPerDay)
{
// For time only format and a time only input, the time offset on 0001/01/01 is less
// accurate than the system's current offset because of daylight saving time.
offset = TimeZoneInfo.GetLocalUtcOffset(DateTime.Now, TimeZoneInfoOptions.NoThrowOnInvalidTime);
}
else if (dateTime.Kind == DateTimeKind.Utc)
{
offset = TimeSpan.Zero;
}
else
{
offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
}
}
if (offset >= TimeSpan.Zero)
{
result.Append('+');
}
else
{
result.Append('-');
// get a positive offset, so that you don't need a separate code path for the negative numbers.
offset = offset.Negate();
}
if (tokenLen <= 1)
{
// 'z' format e.g "-7"
result.AppendFormat(CultureInfo.InvariantCulture, "{0:0}", offset.Hours);
}
else
{
// 'zz' or longer format e.g "-07"
result.AppendFormat(CultureInfo.InvariantCulture, "{0:00}", offset.Hours);
if (tokenLen >= 3)
{
// 'zzz*' or longer format e.g "-07:30"
result.AppendFormat(CultureInfo.InvariantCulture, ":{0:00}", offset.Minutes);
}
}
}
// output the 'K' format, which is for round-tripping the data
private static void FormatCustomizedRoundripTimeZone(DateTime dateTime, TimeSpan offset, StringBuilder result)
{
// The objective of this format is to round trip the data in the type
// For DateTime it should round-trip the Kind value and preserve the time zone.
// DateTimeOffset instance, it should do so by using the internal time zone.
if (offset == NullOffset)
{
// source is a date time, so behavior depends on the kind.
switch (dateTime.Kind)
{
case DateTimeKind.Local:
// This should output the local offset, e.g. "-07:30"
offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
// fall through to shared time zone output code
break;
case DateTimeKind.Utc:
// The 'Z' constant is a marker for a UTC date
result.Append("Z");
return;
default:
// If the kind is unspecified, we output nothing here
return;
}
}
if (offset >= TimeSpan.Zero)
{
result.Append('+');
}
else
{
result.Append('-');
// get a positive offset, so that you don't need a separate code path for the negative numbers.
offset = offset.Negate();
}
AppendNumber(result, offset.Hours, 2);
result.Append(':');
AppendNumber(result, offset.Minutes, 2);
}
internal static String GetRealFormat(String format, DateTimeFormatInfo dtfi)
{
String realFormat = null;
switch (format[0])
{
case 'd': // Short Date
realFormat = dtfi.ShortDatePattern;
break;
case 'D': // Long Date
realFormat = dtfi.LongDatePattern;
break;
case 'f': // Full (long date + short time)
realFormat = dtfi.LongDatePattern + " " + dtfi.ShortTimePattern;
break;
case 'F': // Full (long date + long time)
realFormat = dtfi.FullDateTimePattern;
break;
case 'g': // General (short date + short time)
realFormat = dtfi.GeneralShortTimePattern;
break;
case 'G': // General (short date + long time)
realFormat = dtfi.GeneralLongTimePattern;
break;
case 'm':
case 'M': // Month/Day Date
realFormat = dtfi.MonthDayPattern;
break;
case 'o':
case 'O':
realFormat = RoundtripFormat;
break;
case 'r':
case 'R': // RFC 1123 Standard
realFormat = dtfi.RFC1123Pattern;
break;
case 's': // Sortable without Time Zone Info
realFormat = dtfi.SortableDateTimePattern;
break;
case 't': // Short Time
realFormat = dtfi.ShortTimePattern;
break;
case 'T': // Long Time
realFormat = dtfi.LongTimePattern;
break;
case 'u': // Universal with Sortable format
realFormat = dtfi.UniversalSortableDateTimePattern;
break;
case 'U': // Universal with Full (long date + long time) format
realFormat = dtfi.FullDateTimePattern;
break;
case 'y':
case 'Y': // Year/Month Date
realFormat = dtfi.YearMonthPattern;
break;
default:
throw new FormatException(SR.Format_InvalidString);
}
return (realFormat);
}
// Expand a pre-defined format string (like "D" for long date) to the real format that
// we are going to use in the date time parsing.
// This method also convert the dateTime if necessary (e.g. when the format is in Universal time),
// and change dtfi if necessary (e.g. when the format should use invariant culture).
//
private static String ExpandPredefinedFormat(String format, ref DateTime dateTime, ref DateTimeFormatInfo dtfi, ref TimeSpan offset)
{
switch (format[0])
{
case 'o':
case 'O': // Round trip format
dtfi = DateTimeFormatInfo.InvariantInfo;
break;
case 'r':
case 'R': // RFC 1123 Standard
if (offset != NullOffset)
{
// Convert to UTC invariants mean this will be in range
dateTime = dateTime - offset;
}
else if (dateTime.Kind == DateTimeKind.Local)
{
InvalidFormatForLocal(format, dateTime);
}
dtfi = DateTimeFormatInfo.InvariantInfo;
break;
case 's': // Sortable without Time Zone Info
dtfi = DateTimeFormatInfo.InvariantInfo;
break;
case 'u': // Universal time in sortable format.
if (offset != NullOffset)
{
// Convert to UTC invariants mean this will be in range
dateTime = dateTime - offset;
}
else if (dateTime.Kind == DateTimeKind.Local)
{
InvalidFormatForLocal(format, dateTime);
}
dtfi = DateTimeFormatInfo.InvariantInfo;
break;
case 'U': // Universal time in culture dependent format.
if (offset != NullOffset)
{
// This format is not supported by DateTimeOffset
throw new FormatException(SR.Format_InvalidString);
}
// Universal time is always in Greogrian calendar.
//
// Change the Calendar to be Gregorian Calendar.
//
dtfi = (DateTimeFormatInfo)dtfi.Clone();
if (dtfi.Calendar.GetType() != typeof(GregorianCalendar))
{
dtfi.Calendar = GregorianCalendar.GetDefaultInstance();
}
dateTime = dateTime.ToUniversalTime();
break;
}
format = GetRealFormat(format, dtfi);
return (format);
}
internal static String Format(DateTime dateTime, String format, DateTimeFormatInfo dtfi)
{
return Format(dateTime, format, dtfi, NullOffset);
}
internal static String Format(DateTime dateTime, String format, DateTimeFormatInfo dtfi, TimeSpan offset)
{
Debug.Assert(dtfi != null);
if (format == null || format.Length == 0)
{
Boolean timeOnlySpecialCase = false;
if (dateTime.Ticks < Calendar.TicksPerDay)
{
// If the time is less than 1 day, consider it as time of day.
// Just print out the short time format.
//
// This is a workaround for VB, since they use ticks less then one day to be
// time of day. In cultures which use calendar other than Gregorian calendar, these
// alternative calendar may not support ticks less than a day.
// For example, Japanese calendar only supports date after 1868/9/8.
// This will pose a problem when people in VB get the time of day, and use it
// to call ToString(), which will use the general format (short date + long time).
// Since Japanese calendar does not support Gregorian year 0001, an exception will be
// thrown when we try to get the Japanese year for Gregorian year 0001.
// Therefore, the workaround allows them to call ToString() for time of day from a DateTime by
// formatting as ISO 8601 format.
switch (dtfi.Calendar.ID)
{
case CalendarId.JAPAN:
case CalendarId.TAIWAN:
case CalendarId.HIJRI:
case CalendarId.HEBREW:
case CalendarId.JULIAN:
case CalendarId.UMALQURA:
case CalendarId.PERSIAN:
timeOnlySpecialCase = true;
dtfi = DateTimeFormatInfo.InvariantInfo;
break;
}
}
if (offset == NullOffset)
{
// Default DateTime.ToString case.
if (timeOnlySpecialCase)
{
format = "s";
}
else
{
format = "G";
}
}
else
{
// Default DateTimeOffset.ToString case.
if (timeOnlySpecialCase)
{
format = RoundtripDateTimeUnfixed;
}
else
{
format = dtfi.DateTimeOffsetPattern;
}
}
}
if (format.Length == 1)
{
switch (format[0])
{
case 'O':
case 'o':
return FastFormatRoundtrip(dateTime, offset);
case 'R':
case 'r':
return FastFormatRfc1123(dateTime, offset, dtfi);
}
format = ExpandPredefinedFormat(format, ref dateTime, ref dtfi, ref offset);
}
return (FormatCustomized(dateTime, format, dtfi, offset));
}
internal static string FastFormatRfc1123(DateTime dateTime, TimeSpan offset, DateTimeFormatInfo dtfi)
{
// ddd, dd MMM yyyy HH:mm:ss GMT
const int Rfc1123FormatLength = 29;
StringBuilder result = StringBuilderCache.Acquire(Rfc1123FormatLength);
if (offset != NullOffset)
{
// Convert to UTC invariants
dateTime = dateTime - offset;
}
dateTime.GetDatePart(out int year, out int month, out int day);
result.Append(InvariantAbbreviatedDayNames[(int)dateTime.DayOfWeek]);
result.Append(',');
result.Append(' ');
AppendNumber(result, day, 2);
result.Append(' ');
result.Append(InvariantAbbreviatedMonthNames[month - 1]);
result.Append(' ');
AppendNumber(result, year, 4);
result.Append(' ');
AppendHHmmssTimeOfDay(result, dateTime);
result.Append(' ');
result.Append(Gmt);
return StringBuilderCache.GetStringAndRelease(result);
}
internal static string FastFormatRoundtrip(DateTime dateTime, TimeSpan offset)
{
// yyyy-MM-ddTHH:mm:ss.fffffffK
const int roundTripFormatLength = 28;
StringBuilder result = StringBuilderCache.Acquire(roundTripFormatLength);
dateTime.GetDatePart(out int year, out int month, out int day);
AppendNumber(result, year, 4);
result.Append('-');
AppendNumber(result, month, 2);
result.Append('-');
AppendNumber(result, day, 2);
result.Append('T');
AppendHHmmssTimeOfDay(result, dateTime);
result.Append('.');
long fraction = dateTime.Ticks % TimeSpan.TicksPerSecond;
AppendNumber(result, fraction, 7);
FormatCustomizedRoundripTimeZone(dateTime, offset, result);
return StringBuilderCache.GetStringAndRelease(result);
}
private static void AppendHHmmssTimeOfDay(StringBuilder result, DateTime dateTime)
{
// HH:mm:ss
AppendNumber(result, dateTime.Hour, 2);
result.Append(':');
AppendNumber(result, dateTime.Minute, 2);
result.Append(':');
AppendNumber(result, dateTime.Second, 2);
}
internal static void AppendNumber(StringBuilder builder, long val, int digits)
{
for (int i = 0; i < digits; i++)
{
builder.Append('0');
}
int index = 1;
while (val > 0 && index <= digits)
{
builder[builder.Length - index] = (char)('0' + (val % 10));
val = val / 10;
index++;
}
Debug.Assert(val == 0, "DateTimeFormat.AppendNumber(): digits less than size of val");
}
internal static String[] GetAllDateTimes(DateTime dateTime, char format, DateTimeFormatInfo dtfi)
{
Debug.Assert(dtfi != null);
String[] allFormats = null;
String[] results = null;
switch (format)
{
case 'd':
case 'D':
case 'f':
case 'F':
case 'g':
case 'G':
case 'm':
case 'M':
case 't':
case 'T':
case 'y':
case 'Y':
allFormats = dtfi.GetAllDateTimePatterns(format);
results = new String[allFormats.Length];
for (int i = 0; i < allFormats.Length; i++)
{
results[i] = Format(dateTime, allFormats[i], dtfi);
}
break;
case 'U':
DateTime universalTime = dateTime.ToUniversalTime();
allFormats = dtfi.GetAllDateTimePatterns(format);
results = new String[allFormats.Length];
for (int i = 0; i < allFormats.Length; i++)
{
results[i] = Format(universalTime, allFormats[i], dtfi);
}
break;
//
// The following ones are special cases because these patterns are read-only in
// DateTimeFormatInfo.
//
case 'r':
case 'R':
case 'o':
case 'O':
case 's':
case 'u':
results = new String[] { Format(dateTime, new String(format, 1), dtfi) };
break;
default:
throw new FormatException(SR.Format_InvalidString);
}
return (results);
}
internal static String[] GetAllDateTimes(DateTime dateTime, DateTimeFormatInfo dtfi)
{
List<String> results = new List<String>(DEFAULT_ALL_DATETIMES_SIZE);
for (int i = 0; i < allStandardFormats.Length; i++)
{
String[] strings = GetAllDateTimes(dateTime, allStandardFormats[i], dtfi);
for (int j = 0; j < strings.Length; j++)
{
results.Add(strings[j]);
}
}
String[] value = new String[results.Count];
results.CopyTo(0, value, 0, results.Count);
return (value);
}
// This is a placeholder for an MDA to detect when the user is using a
// local DateTime with a format that will be interpreted as UTC.
internal static void InvalidFormatForLocal(String format, DateTime dateTime)
{
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft 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.Management.Automation;
using Microsoft.WindowsAzure.Commands.Common;
using Microsoft.Azure.Common.Authentication.Models;
using Microsoft.WindowsAzure.Commands.SqlDatabase.Properties;
using Microsoft.WindowsAzure.Commands.SqlDatabase.Services.Common;
using Microsoft.WindowsAzure.Commands.SqlDatabase.Services.Server;
using Microsoft.WindowsAzure.Commands.Utilities.Common;
using Microsoft.Azure.Common.Authentication;
namespace Microsoft.WindowsAzure.Commands.SqlDatabase.Database.Cmdlet
{
/// <summary>
/// Update settings for an existing Microsoft Azure SQL Database in the given server context.
/// </summary>
[Cmdlet(VerbsCommon.Remove, "AzureSqlDatabase", SupportsShouldProcess = true,
ConfirmImpact = ConfirmImpact.High)]
public class RemoveAzureSqlDatabase : AzureSMCmdlet
{
#region Parameter sets
/// <summary>
/// The name of the parameter set for removing a database by name with a connection context
/// </summary>
internal const string ByNameWithConnectionContext =
"ByNameWithConnectionContext";
/// <summary>
/// The name of the parameter set for removing a database by name using azure subscription
/// </summary>
internal const string ByNameWithServerName =
"ByNameWithServerName";
/// <summary>
/// The name of the parameter set for removing a database by input
/// object with a connection context
/// </summary>
internal const string ByObjectWithConnectionContext =
"ByObjectWithConnectionContext";
/// <summary>
/// The name of the parameter set for removing a database by input
/// object using azure subscription
/// </summary>
internal const string ByObjectWithServerName =
"ByObjectWithServerName";
#endregion
#region Parameters
/// <summary>
/// Gets or sets the server connection context.
/// </summary>
[Alias("Context")]
[Parameter(Mandatory = true, Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = ByNameWithConnectionContext,
HelpMessage = "The connection context to the specified server.")]
[Parameter(Mandatory = true, Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = ByObjectWithConnectionContext,
HelpMessage = "The connection context to the specified server.")]
[ValidateNotNull]
public IServerDataServiceContext ConnectionContext { get; set; }
/// <summary>
/// Gets or sets the name of the server to connect to
/// </summary>
[Parameter(Mandatory = true, Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = ByNameWithServerName,
HelpMessage = "The name of the server to connect to")]
[Parameter(Mandatory = true, Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = ByObjectWithServerName,
HelpMessage = "The name of the server to connect to")]
[ValidateNotNullOrEmpty]
public string ServerName { get; set; }
/// <summary>
/// Gets or sets the database.
/// </summary>
[Alias("InputObject")]
[Parameter(Mandatory = true, Position = 1, ValueFromPipeline = true,
ParameterSetName = ByObjectWithConnectionContext,
HelpMessage = "The database object you want to remove")]
[Parameter(Mandatory = true, Position = 1, ValueFromPipeline = true,
ParameterSetName = ByObjectWithServerName,
HelpMessage = "The database object you want to remove")]
[ValidateNotNull]
public Services.Server.Database Database { get; set; }
/// <summary>
/// Gets or sets the database name.
/// </summary>
[Parameter(Mandatory = true, Position = 1,
ParameterSetName = ByNameWithConnectionContext,
HelpMessage = "The name of the database to remove")]
[Parameter(Mandatory = true, Position = 1,
ParameterSetName = ByNameWithServerName,
HelpMessage = "The name of the database to remove")]
[ValidateNotNullOrEmpty]
public string DatabaseName { get; set; }
/// <summary>
/// Gets or sets the switch to not confirm on the removal of the database.
/// </summary>
[Parameter(HelpMessage = "Do not confirm on the removal of the database")]
public SwitchParameter Force { get; set; }
#endregion
/// <summary>
/// Process the command.
/// </summary>
public override void ExecuteCmdlet()
{
// Obtain the database name from the given parameters.
string databaseName = null;
if (this.MyInvocation.BoundParameters.ContainsKey("Database"))
{
databaseName = this.Database.Name;
}
else if (this.MyInvocation.BoundParameters.ContainsKey("DatabaseName"))
{
databaseName = this.DatabaseName;
}
// Determine the name of the server we are connecting to
string serverName = null;
if (this.MyInvocation.BoundParameters.ContainsKey("ServerName"))
{
serverName = this.ServerName;
}
else
{
serverName = this.ConnectionContext.ServerName;
}
string actionDescription = string.Format(
CultureInfo.InvariantCulture,
Resources.RemoveAzureSqlDatabaseDescription,
serverName,
databaseName);
string actionWarning = string.Format(
CultureInfo.InvariantCulture,
Resources.RemoveAzureSqlDatabaseWarning,
serverName,
databaseName);
this.WriteVerbose(actionDescription);
// Do nothing if force is not specified and user cancelled the operation
if (!this.Force.IsPresent &&
!this.ShouldProcess(
actionDescription,
actionWarning,
Resources.ShouldProcessCaption))
{
return;
}
switch (this.ParameterSetName)
{
case ByNameWithConnectionContext:
case ByObjectWithConnectionContext:
this.ProcessWithConnectionContext(databaseName);
break;
case ByNameWithServerName:
case ByObjectWithServerName:
this.ProcessWithServerName(databaseName);
break;
}
}
/// <summary>
/// Process the request using a temporary connection context.
/// </summary>
/// <param name="databaseName">The name of the database to remove</param>
private void ProcessWithServerName(string databaseName)
{
Func<string> GetClientRequestId = () => string.Empty;
try
{
// Get the current subscription data.
AzureSubscription subscription = Profile.Context.Subscription;
// Create a temporary context
ServerDataServiceCertAuth context =
ServerDataServiceCertAuth.Create(this.ServerName, Profile, subscription);
GetClientRequestId = () => context.ClientRequestId;
// Remove the database with the specified name
context.RemoveDatabase(databaseName);
}
catch (Exception ex)
{
SqlDatabaseExceptionHandler.WriteErrorDetails(
this,
GetClientRequestId(),
ex);
}
}
/// <summary>
/// Process the request with the connection context
/// </summary>
/// <param name="databaseName">The name of the database to remove</param>
private void ProcessWithConnectionContext(string databaseName)
{
try
{
// Remove the database with the specified name
this.ConnectionContext.RemoveDatabase(databaseName);
}
catch (Exception ex)
{
SqlDatabaseExceptionHandler.WriteErrorDetails(
this,
this.ConnectionContext.ClientRequestId,
ex);
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="MobileControlsSection.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System.Collections;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.Globalization;
namespace System.Web.UI.MobileControls
{
[Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")]
public sealed class MobileControlsSection : ConfigurationSection
{
private ControlsConfig _controlConfig;
private object _lock = new object();
internal static readonly TypeConverter StdTypeNameConverter = new MobileTypeNameConverter();
internal static readonly ConfigurationValidatorBase NonEmptyStringValidator = new StringValidator( 1 );
private static ConfigurationPropertyCollection _properties;
#region Property Declarations
private static readonly ConfigurationProperty _propHistorySize =
new ConfigurationProperty( "sessionStateHistorySize",
typeof( int ),
Constants.DefaultSessionsStateHistorySize,
null,
new IntegerValidator( 0 ,int.MaxValue),
ConfigurationPropertyOptions.None );
private static readonly ConfigurationProperty _propDictType =
new ConfigurationProperty( "cookielessDataDictionaryType",
typeof( Type ),
typeof( System.Web.Mobile.CookielessData ),
MobileControlsSection.StdTypeNameConverter,
new SubclassTypeValidator( typeof( IDictionary ) ),
ConfigurationPropertyOptions.None );
private static readonly ConfigurationProperty _propAllowCustomAttributes =
new ConfigurationProperty( "allowCustomAttributes",
typeof( bool ),
false,
ConfigurationPropertyOptions.None );
private static readonly ConfigurationProperty _propDevices =
new ConfigurationProperty( null,
typeof( DeviceElementCollection ),
null,
ConfigurationPropertyOptions.IsDefaultCollection );
#endregion
static MobileControlsSection()
{
// Property initialization
_properties = new ConfigurationPropertyCollection();
_properties.Add( _propHistorySize );
_properties.Add( _propDevices );
_properties.Add( _propDictType );
_properties.Add( _propAllowCustomAttributes );
}
public MobileControlsSection()
{
}
// VSWhidbey 450801. Only create one ControlsConfig per MobileControlsSection instance.
internal ControlsConfig GetControlsConfig() {
if (_controlConfig == null) {
lock (_lock) {
if (_controlConfig == null) {
_controlConfig = MobileControlsSectionHelper.CreateControlsConfig(this);
}
}
}
return _controlConfig;
}
protected override ConfigurationPropertyCollection Properties
{
get
{
return _properties;
}
}
[ConfigurationProperty("sessionStateHistorySize", DefaultValue = 6)]
[IntegerValidator(MinValue = 0)]
public int SessionStateHistorySize
{
get
{
return (int)base[ _propHistorySize ];
}
set
{
base[ _propHistorySize ] = value;
}
}
[ConfigurationProperty("cookielessDataDictionaryType", DefaultValue = typeof(System.Web.Mobile.CookielessData))]
[TypeConverter(typeof(MobileTypeNameConverter))]
[SubclassTypeValidator(typeof(IDictionary))]
public Type CookielessDataDictionaryType
{
get
{
return (Type)base[ _propDictType ];
}
set
{
base[ _propDictType ] = value;
}
}
[ConfigurationProperty("allowCustomAttributes", DefaultValue = false)]
public bool AllowCustomAttributes
{
get
{
return (bool)base[ _propAllowCustomAttributes ];
}
set
{
base[ _propAllowCustomAttributes ] = value;
}
}
[ConfigurationProperty("", IsDefaultCollection = true)]
public DeviceElementCollection Devices
{
get
{
return (DeviceElementCollection)base[ _propDevices ];
}
}
}
[ConfigurationCollection(typeof(DeviceElement), AddItemName="device")]
[Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")]
public sealed class DeviceElementCollection : ConfigurationElementCollection
{
private static readonly ConfigurationPropertyCollection _properties;
static DeviceElementCollection()
{
_properties = new ConfigurationPropertyCollection();
}
public DeviceElementCollection()
{
}
protected override ConfigurationPropertyCollection Properties
{
get
{
return _properties;
}
}
public object[] AllKeys
{
get
{
return BaseGetAllKeys();
}
}
public void Add( DeviceElement deviceElement )
{
BaseAdd( deviceElement );
}
public void Remove( string name )
{
BaseRemove( name );
}
public void Remove( DeviceElement deviceElement )
{
BaseRemove( GetElementKey( deviceElement ) );
}
public void RemoveAt( int index )
{
BaseRemoveAt( index );
}
public new DeviceElement this[ string name ]
{
get
{
return (DeviceElement)BaseGet( name );
}
}
public DeviceElement this[ int index ]
{
get
{
return (DeviceElement)BaseGet( index );
}
set
{
if ( BaseGet( index ) != null)
{
BaseRemoveAt( index );
}
BaseAdd( index, value );
}
}
public void Clear()
{
BaseClear();
}
protected override ConfigurationElement CreateNewElement()
{
return new DeviceElement();
}
protected override Object GetElementKey( ConfigurationElement element )
{
return ( (DeviceElement)element ).Name;
}
protected override string ElementName
{
get
{
return "device";
}
}
protected override bool ThrowOnDuplicate
{
get
{
return true;
}
}
public override ConfigurationElementCollectionType CollectionType
{
get
{
return ConfigurationElementCollectionType.BasicMapAlternate;
}
}
}
[Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")]
public sealed class DeviceElement : ConfigurationElement
{
private static readonly ConfigurationElementProperty s_elemProperty = new ConfigurationElementProperty( new CallbackValidator( typeof( DeviceElement ), ValidateElement ) );
private static ConfigurationPropertyCollection _properties;
#region Property Declarations
private static readonly ConfigurationProperty _propName =
new ConfigurationProperty( "name",
typeof( string ),
null,
null,
MobileControlsSection.NonEmptyStringValidator,
ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey );
private static readonly ConfigurationProperty _propInheritsFrom =
new ConfigurationProperty( "inheritsFrom",
typeof( string ),
null,
null,
MobileControlsSection.NonEmptyStringValidator,
ConfigurationPropertyOptions.None );
private static readonly ConfigurationProperty _propPredicateClass =
new ConfigurationProperty( "predicateClass",
typeof( Type ),
null,
MobileControlsSection.StdTypeNameConverter,
null,
ConfigurationPropertyOptions.None );
private static readonly ConfigurationProperty _propPredicateMethod =
new ConfigurationProperty( "predicateMethod",
typeof( string ),
null,
null,
MobileControlsSection.NonEmptyStringValidator,
ConfigurationPropertyOptions.None );
private static readonly ConfigurationProperty _propPageAdapter =
new ConfigurationProperty( "pageAdapter",
typeof( Type ),
null,
MobileControlsSection.StdTypeNameConverter,
new SubclassTypeValidator( typeof( IPageAdapter ) ),
ConfigurationPropertyOptions.None );
private static readonly ConfigurationProperty _propControls =
new ConfigurationProperty( null,
typeof(ControlElementCollection),
null,
ConfigurationPropertyOptions.IsDefaultCollection );
#endregion
static DeviceElement()
{
// Property initialization
_properties = new ConfigurationPropertyCollection();
_properties.Add( _propName );
_properties.Add( _propInheritsFrom );
_properties.Add( _propPredicateClass );
_properties.Add( _propPredicateMethod );
_properties.Add( _propPageAdapter );
_properties.Add( _propControls );
}
internal DeviceElement()
{
}
public DeviceElement( string name, string inheritsFrom )
{
base[ _propName ] = name;
base[ _propInheritsFrom ] = inheritsFrom;
}
public DeviceElement( string name, Type predicateClass, string predicateMethod, Type pageAdapter )
{
base[ _propName] = name;
base[ _propPredicateClass] = predicateClass;
base[ _propPredicateMethod] = predicateMethod;
base[ _propPageAdapter ] = pageAdapter;
}
public DeviceElement(string name, string inheritsFrom, Type predicateClass,
string predicateMethod, Type pageAdapter)
{
base[ _propName] = name;
base[ _propInheritsFrom ] = inheritsFrom;
base[ _propPredicateClass] = predicateClass;
base[ _propPredicateMethod] = predicateMethod;
base[ _propPageAdapter ] = pageAdapter;
}
protected override ConfigurationPropertyCollection Properties
{
get
{
return _properties;
}
}
[ConfigurationProperty("name", IsRequired = true, IsKey = true)]
[StringValidator(MinLength = 1)]
public string Name
{
get
{
return (string)base[ _propName ];
}
set
{
base[ _propName ] = value;
}
}
[ConfigurationProperty("inheritsFrom")]
[StringValidator(MinLength = 1)]
public string InheritsFrom
{
get
{
return (string)base[ _propInheritsFrom ];
}
set
{
base[ _propInheritsFrom ] = value;
}
}
[ConfigurationProperty("predicateClass")]
[TypeConverter(typeof(MobileTypeNameConverter))]
public Type PredicateClass
{
get
{
return (Type)base[ _propPredicateClass ];
}
set
{
base[ _propPredicateClass ] = value;
}
}
[ConfigurationProperty("predicateMethod")]
[StringValidator(MinLength = 1)]
public string PredicateMethod
{
get
{
return (string)base[ _propPredicateMethod ];
}
set
{
base[ _propPredicateMethod ] = value;
}
}
[ConfigurationProperty("pageAdapter")]
[TypeConverter(typeof(MobileTypeNameConverter))]
[SubclassTypeValidator(typeof(IPageAdapter))]
public Type PageAdapter
{
get
{
return (Type)base[_propPageAdapter];
}
set
{
base[_propPageAdapter] = value;
}
}
[ConfigurationProperty("", IsDefaultCollection = true)]
public ControlElementCollection Controls
{
get
{
return (ControlElementCollection)base[ _propControls ];
}
}
protected override ConfigurationElementProperty ElementProperty
{
get
{
return s_elemProperty;
}
}
internal IndividualDeviceConfig.DeviceQualifiesDelegate GetDelegate()
{
try
{
return (IndividualDeviceConfig.DeviceQualifiesDelegate)IndividualDeviceConfig.DeviceQualifiesDelegate.CreateDelegate(
typeof(IndividualDeviceConfig.DeviceQualifiesDelegate),
PredicateClass,
PredicateMethod );
}
catch
{
throw new ConfigurationErrorsException(
SR.GetString(SR.MobileControlsSectionHandler_CantCreateMethodOnClass, PredicateMethod, PredicateClass.FullName),
ElementInformation.Source, ElementInformation.LineNumber);
}
}
static private void ValidateElement( object value )
{
Debug.Assert( ( value != null ) && ( value is DeviceElement ) );
DeviceElement elem = (DeviceElement)value;
// If there is no inheritance the properties must exists and be valid
if ( string.IsNullOrEmpty(elem.InheritsFrom) )
{
if ( elem.PredicateClass == null )
{
throw new ConfigurationErrorsException( SR.GetString(SR.ConfigSect_MissingValue, "predicateClass"),
elem.ElementInformation.Source,
elem.ElementInformation.LineNumber );
}
if ( elem.PageAdapter == null )
{
throw new ConfigurationErrorsException( SR.GetString(SR.ConfigSect_MissingValue, "pageAdapter"),
elem.ElementInformation.Source,
elem.ElementInformation.LineNumber );
}
// Resolve the method
elem.GetDelegate();
}
}
}
[ConfigurationCollection(typeof(ControlElement), AddItemName = "control")]
[Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")]
public sealed class ControlElementCollection : ConfigurationElementCollection
{
private static readonly ConfigurationPropertyCollection _properties;
static ControlElementCollection()
{
_properties = new ConfigurationPropertyCollection();
}
public ControlElementCollection()
{
}
protected override ConfigurationPropertyCollection Properties
{
get
{
return _properties;
}
}
public object[] AllKeys
{
get
{
return BaseGetAllKeys();
}
}
public void Add( ControlElement controlElement )
{
BaseAdd( controlElement );
}
public void Remove( string name )
{
BaseRemove( name );
}
public void Remove( ControlElement controlElement )
{
BaseRemove( GetElementKey( controlElement ) );
}
public void RemoveAt( int index )
{
BaseRemoveAt( index );
}
public new ControlElement this[ string name ]
{
get
{
return (ControlElement)BaseGet( name );
}
}
public ControlElement this[ int index ]
{
get
{
return (ControlElement)BaseGet( index );
}
set
{
if ( BaseGet( index ) != null)
{
BaseRemoveAt( index );
}
BaseAdd( index, value );
}
}
public void Clear()
{
BaseClear();
}
protected override ConfigurationElement CreateNewElement()
{
return new ControlElement();
}
protected override Object GetElementKey( ConfigurationElement element )
{
return ( (ControlElement)element ).Name;
}
protected override string ElementName
{
get
{
return "control";
}
}
protected override bool ThrowOnDuplicate
{
get
{
return true;
}
}
public override ConfigurationElementCollectionType CollectionType
{
get
{
return ConfigurationElementCollectionType.BasicMap;
}
}
}
[Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")]
public sealed class ControlElement : ConfigurationElement
{
private static readonly ConfigurationElementProperty s_elemProperty = new ConfigurationElementProperty( new CallbackValidator( typeof( ControlElement ), ValidateElement ) );
private static readonly ConfigurationValidatorBase s_SubclassTypeValidator = new SubclassTypeValidator( typeof( MobileControl ) );
private static ConfigurationPropertyCollection _properties;
#region Property Declarations
private static readonly ConfigurationProperty _propName =
new ConfigurationProperty( "name",
typeof( string ),
null,
null,
MobileControlsSection.NonEmptyStringValidator,
ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey );
private static readonly ConfigurationProperty _propAdapter =
new ConfigurationProperty( "adapter",
typeof( Type ),
null,
MobileControlsSection.StdTypeNameConverter,
new SubclassTypeValidator( typeof( IControlAdapter ) ),
ConfigurationPropertyOptions.IsRequired );
#endregion
static ControlElement()
{
// Property initialization
_properties = new ConfigurationPropertyCollection();
_properties.Add( _propName );
_properties.Add( _propAdapter );
}
internal ControlElement()
{
}
public ControlElement( string name, Type adapter )
{
base[ _propName] = name;
base[ _propAdapter ] = adapter;
}
protected override ConfigurationPropertyCollection Properties
{
get
{
return _properties;
}
}
[ConfigurationProperty("name", IsRequired = true, IsKey = true)]
[StringValidator(MinLength = 1)]
public string Name
{
get
{
return (string)base[ _propName ];
}
set
{
base[ _propName ] = value;
}
}
public Type Control
{
get
{
return Type.GetType( Name );
}
set
{
if ( value == null )
{
throw new ArgumentNullException( "value" );
}
s_SubclassTypeValidator.Validate( value );
Name = value.FullName;
}
}
[ConfigurationProperty("adapter", IsRequired = true)]
[TypeConverter(typeof(MobileTypeNameConverter))]
[SubclassTypeValidator(typeof(IControlAdapter))]
public Type Adapter
{
get
{
return (Type)base[ _propAdapter ];
}
set
{
base[ _propAdapter ] = value;
}
}
protected override ConfigurationElementProperty ElementProperty
{
get
{
return s_elemProperty;
}
}
static private void ValidateElement( object value )
{
Debug.Assert( ( value != null ) && ( value is ControlElement ) );
ControlElement elem = (ControlElement)value;
// Make sure Name is a valid type
// This will throw if the type cannot be resolved
Type tp = MobileControlsSection.StdTypeNameConverter.ConvertFromInvariantString( elem.Name ) as Type;
// Validate that tp inherits from MobileControl
s_SubclassTypeValidator.Validate( tp );
}
}
// From old versions the default type names specified in mobile control config
// section do not associate with assembly names. So we cannot use
// System.Configuration.TypeNameConverter as it wouldn't look up the type
// names in the mobile assembly. To workaround it, we create the same
// converter here to be used in the mobile assembly.
[Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")]
public sealed class MobileTypeNameConverter : ConfigurationConverterBase {
public override object ConvertTo(ITypeDescriptorContext ctx, CultureInfo ci,
object value, Type targetType) {
Debug.Assert(targetType != null);
Type valueType = value as Type;
if (valueType == null) {
throw new ArgumentException(SR.GetString(SR.MobileTypeNameConverter_UnsupportedValueType,
((value == null) ? String.Empty : value.ToString()),
targetType.FullName));
}
return valueType.FullName;
}
public override object ConvertFrom(ITypeDescriptorContext ctx, CultureInfo ci, object data) {
Debug.Assert(data is string);
Type result = Type.GetType((string)data);
if (result == null) {
throw new ConfigurationErrorsException(
SR.GetString(SR.MobileTypeNameConverter_TypeNotResolved, (string)data));
}
return result;
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using Orleans.Runtime;
using Orleans.Concurrency;
namespace Orleans.Serialization
{
using System.Runtime.CompilerServices;
internal static class TypeUtilities
{
internal static bool IsOrleansPrimitive(this Type t)
{
var typeInfo = t.GetTypeInfo();
return typeInfo.IsPrimitive || typeInfo.IsEnum || t == typeof(string) || t == typeof(DateTime) || t == typeof(Decimal) || (typeInfo.IsArray && typeInfo.GetElementType().IsOrleansPrimitive());
}
static readonly ConcurrentDictionary<Type, bool> shallowCopyableTypes = new ConcurrentDictionary<Type, bool>();
static readonly ConcurrentDictionary<Type, string> typeNameCache = new ConcurrentDictionary<Type, string>();
static readonly ConcurrentDictionary<Type, string> typeKeyStringCache = new ConcurrentDictionary<Type, string>();
static readonly ConcurrentDictionary<Type, byte[]> typeKeyCache = new ConcurrentDictionary<Type, byte[]>();
static TypeUtilities()
{
shallowCopyableTypes[typeof(Decimal)] = true;
shallowCopyableTypes[typeof(DateTime)] = true;
shallowCopyableTypes[typeof(TimeSpan)] = true;
shallowCopyableTypes[typeof(IPAddress)] = true;
shallowCopyableTypes[typeof(IPEndPoint)] = true;
shallowCopyableTypes[typeof(SiloAddress)] = true;
shallowCopyableTypes[typeof(GrainId)] = true;
shallowCopyableTypes[typeof(ActivationId)] = true;
shallowCopyableTypes[typeof(ActivationAddress)] = true;
shallowCopyableTypes[typeof(CorrelationId)] = true;
shallowCopyableTypes[typeof(string)] = true;
shallowCopyableTypes[typeof(Immutable<>)] = true;
shallowCopyableTypes[typeof(CancellationToken)] = true;
}
internal static bool IsOrleansShallowCopyable(this Type t)
{
bool result;
if (shallowCopyableTypes.TryGetValue(t, out result))
{
return result;
}
var typeInfo = t.GetTypeInfo();
if (typeInfo.IsPrimitive || typeInfo.IsEnum)
{
shallowCopyableTypes[t] = true;
return true;
}
if (typeInfo.GetCustomAttributes(typeof(ImmutableAttribute), false).Length > 0)
{
shallowCopyableTypes[t] = true;
return true;
}
if (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(Immutable<>))
{
shallowCopyableTypes[t] = true;
return true;
}
if (typeInfo.IsValueType && !typeInfo.IsGenericType && !typeInfo.IsGenericTypeDefinition)
{
result = typeInfo.GetFields().All(f => !(f.FieldType == t) && IsOrleansShallowCopyable(f.FieldType));
shallowCopyableTypes[t] = result;
return result;
}
shallowCopyableTypes[t] = false;
return false;
}
internal static bool IsSpecializationOf(this Type t, Type match)
{
var typeInfo = t.GetTypeInfo();
return typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == match;
}
internal static string OrleansTypeName(this Type t)
{
string name;
if (typeNameCache.TryGetValue(t, out name))
return name;
name = TypeUtils.GetTemplatedName(t, _ => !_.IsGenericParameter);
typeNameCache[t] = name;
return name;
}
public static byte[] OrleansTypeKey(this Type t)
{
byte[] key;
if (typeKeyCache.TryGetValue(t, out key))
return key;
key = Encoding.UTF8.GetBytes(t.OrleansTypeKeyString());
typeKeyCache[t] = key;
return key;
}
public static string OrleansTypeKeyString(this Type t)
{
string key;
if (typeKeyStringCache.TryGetValue(t, out key))
return key;
var typeInfo = t.GetTypeInfo();
var sb = new StringBuilder();
if (typeInfo.IsGenericTypeDefinition)
{
sb.Append(GetBaseTypeKey(t));
sb.Append('\'');
sb.Append(typeInfo.GetGenericArguments().Length);
}
else if (typeInfo.IsGenericType)
{
sb.Append(GetBaseTypeKey(t));
sb.Append('<');
var first = true;
foreach (var genericArgument in t.GetGenericArguments())
{
if (!first)
{
sb.Append(',');
}
first = false;
sb.Append(OrleansTypeKeyString(genericArgument));
}
sb.Append('>');
}
else if (t.IsArray)
{
sb.Append(OrleansTypeKeyString(t.GetElementType()));
sb.Append('[');
if (t.GetArrayRank() > 1)
{
sb.Append(',', t.GetArrayRank() - 1);
}
sb.Append(']');
}
else
{
sb.Append(GetBaseTypeKey(t));
}
key = sb.ToString();
typeKeyStringCache[t] = key;
return key;
}
private static string GetBaseTypeKey(Type t)
{
var typeInfo = t.GetTypeInfo();
string namespacePrefix = "";
if ((typeInfo.Namespace != null) && !typeInfo.Namespace.StartsWith("System.") && !typeInfo.Namespace.Equals("System"))
{
namespacePrefix = typeInfo.Namespace + '.';
}
if (typeInfo.IsNestedPublic)
{
return namespacePrefix + OrleansTypeKeyString(typeInfo.DeclaringType) + "." + typeInfo.Name;
}
return namespacePrefix + typeInfo.Name;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public static string GetLocationSafe(this Assembly a)
{
if (a.IsDynamic)
{
return "dynamic";
}
try
{
return a.Location;
}
catch (Exception)
{
return "unknown";
}
}
public static bool IsTypeIsInaccessibleForSerialization(Type type, Module fromModule, Assembly fromAssembly)
{
var typeInfo = type.GetTypeInfo();
if (typeInfo.IsGenericTypeDefinition)
{
// Guard against invalid type constraints, which appear when generating code for some languages.
foreach (var parameter in typeInfo.GenericTypeParameters)
{
if (parameter.GetGenericParameterConstraints().Any(IsSpecialClass))
{
return true;
}
}
}
if (!typeInfo.IsVisible && typeInfo.IsConstructedGenericType)
{
foreach (var inner in typeInfo.GetGenericArguments())
{
if (IsTypeIsInaccessibleForSerialization(inner, fromModule, fromAssembly))
{
return true;
}
}
if (IsTypeIsInaccessibleForSerialization(typeInfo.GetGenericTypeDefinition(), fromModule, fromAssembly))
{
return true;
}
}
if ((typeInfo.IsNotPublic || !typeInfo.IsVisible) && !AreInternalsVisibleTo(typeInfo.Assembly, fromAssembly))
{
// subtype is defined in a different assembly from the outer type
if (!typeInfo.Module.Equals(fromModule))
{
return true;
}
// subtype defined in a different assembly from the one we are generating serializers for.
if (!typeInfo.Assembly.Equals(fromAssembly))
{
return true;
}
}
// For arrays, check the element type.
if (typeInfo.IsArray)
{
if (IsTypeIsInaccessibleForSerialization(typeInfo.GetElementType(), fromModule, fromAssembly))
{
return true;
}
}
// For nested types, check that the declaring type is accessible.
if (typeInfo.IsNested)
{
if (IsTypeIsInaccessibleForSerialization(typeInfo.DeclaringType, fromModule, fromAssembly))
{
return true;
}
}
return typeInfo.IsNestedPrivate || typeInfo.IsNestedFamily || type.IsPointer;
}
/// <summary>
/// Returns true if <paramref name="fromAssembly"/> has exposed its internals to <paramref name="toAssembly"/>, false otherwise.
/// </summary>
/// <param name="fromAssembly">The assembly containing internal types.</param>
/// <param name="toAssembly">The assembly requiring access to internal types.</param>
/// <returns>
/// true if <paramref name="fromAssembly"/> has exposed its internals to <paramref name="toAssembly"/>, false otherwise
/// </returns>
private static bool AreInternalsVisibleTo(Assembly fromAssembly, Assembly toAssembly)
{
// If the to-assembly is null, it cannot have internals visible to it.
if (toAssembly == null)
{
return false;
}
// Check InternalsVisibleTo attributes on the from-assembly, pointing to the to-assembly.
var serializationAssemblyName = toAssembly.GetName().FullName;
var internalsVisibleTo = fromAssembly.GetCustomAttributes<InternalsVisibleToAttribute>();
return internalsVisibleTo.Any(_ => _.AssemblyName == serializationAssemblyName);
}
private static bool IsSpecialClass(Type type)
{
return type == typeof (object) || type == typeof (Array) || type == typeof (Delegate) ||
type == typeof (Enum) || type == typeof (ValueType);
}
}
}
| |
// 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 TestSupport;
using TestSupport.Collections.Common_GenericIEnumerableTest;
using TestSupport.Common_TestSupport;
using TestSupport.Collections.Common_IEnumerableTest;
namespace TestSupport.Collections
{
namespace Common_GenericIEnumerableTest
{
public delegate TOutput Converter<in TInput, out TOutput>(TInput input);
public class IEnumerable_T_Test<T>
{
protected Test m_test;
private IEnumerable<T> _collection;
protected ModifyUnderlyingCollection_T<T> _modifyCollection;
protected T[] _items;
protected IEqualityComparer<T> _comparer;
protected VerificationLevel _verificationLevel;
protected CollectionOrder _collectionOrder;
protected Converter<Object, T> _converter;
protected bool _isResetNotSupported;
protected bool _moveNextAtEndThrowsOnModifiedCollection;
private IEnumerable_T_Test() { }
/// <summary>
/// Initializes a new instance of the IEnumerable_T_Test.
/// </summary>
/// <param name="collection">The collection to run the tests on.</param>
/// <param name="items">The items currently in the collection.</param>
public IEnumerable_T_Test(Test test, IEnumerable<T> collection, T[] items) : this(test, collection, items, null) { }
/// <summary>
/// Initializes a new instance of the IEnumerable_T_Test.
/// </summary>
/// <param name="collection">The collection to run the tests on.</param>
/// <param name="items"></param>
/// <param name="modifyCollection"></param>
public IEnumerable_T_Test(Test test, IEnumerable<T> collection, T[] items, ModifyUnderlyingCollection_T<T> modifyCollection)
{
m_test = test;
_collection = collection;
_modifyCollection = modifyCollection;
_verificationLevel = VerificationLevel.Extensive;
_collectionOrder = CollectionOrder.Sequential;
_converter = null;
_isResetNotSupported = false;
_moveNextAtEndThrowsOnModifiedCollection = true;
if (items == null)
_items = new T[0];
else
_items = items;
_comparer = EqualityComparer<T>.Default;
}
/// <summary>
/// If true specifes that IEnumerator.Reset is not supported on the
/// IEnumerator returned from Collection and will throw NotSupportedException.
/// </summary>
public bool IsResetNotSupported
{
get
{
return _isResetNotSupported;
}
set
{
_isResetNotSupported = value;
}
}
/// <summary>
/// Specifies if the MoveNext will throw when the eumerator is positioneda t
/// the end of the collection when the collection has been modified.
/// </summary>
public bool MoveNextAtEndThrowsOnModifiedCollection
{
get
{
return _moveNextAtEndThrowsOnModifiedCollection;
}
set
{
_moveNextAtEndThrowsOnModifiedCollection = value;
}
}
/// <summary>
/// Runs all of the IEnumerable<T> tests.
/// </summary>
/// <returns>true if all of the tests passed else false</returns>
public bool RunAllTests()
{
bool retValue = true;
retValue &= MoveNext_Tests();
retValue &= Current_Tests();
retValue &= ModifiedCollection_Test();
retValue &= NonGenericIEnumerable_Test();
return retValue;
}
/// <summary>
/// The collection to run the tests on.
/// </summary>
/// <value>The collection to run the tests on.</value>
public IEnumerable<T> Collection
{
get
{
return _collection;
}
set
{
if (null == value)
{
throw new ArgumentNullException("value");
}
_collection = value;
}
}
/// <summary>
/// The items in the Collection
/// </summary>
/// <value>The items in the Collection</value>
public T[] Items
{
get
{
return _items;
}
set
{
if (null == value)
{
throw new ArgumentNullException("value");
}
_items = value;
}
}
/// <summary>
/// Modifies the collection. If null the test that verify that enumerating a
/// collection that has been modified since the enumerator has been created
/// will not be run.
/// </summary>
/// <value>Modifies the collection.</value>
public ModifyUnderlyingCollection_T<T> ModifyCollection
{
get
{
return _modifyCollection;
}
set
{
_modifyCollection = value;
}
}
/// <summary>
/// The IComparer used to compare the items. If null Comparer<Object>.Defualt will be used.
/// </summary>
/// <value>The IComparer used to compare the items.</value>
public IEqualityComparer<T> Comparer
{
get
{
return _comparer;
}
set
{
if (null == value)
_comparer = EqualityComparer<T>.Default;
else
_comparer = value;
}
}
/// <summary>
/// The Verification level to use. If VerificationLevel is Extensize the collection
/// will be verified after argument checking (invalid) tests.
/// </summary>
/// <value>The Verification level to use.</value>
public VerificationLevel VerificationLevel
{
get
{
return _verificationLevel;
}
set
{
_verificationLevel = value;
}
}
/// <summary>
/// This specifies where Add places an item at the beginning of the collection,
/// the end of the collection, or unspecifed. Items is expected to be in the
/// smae order as the enumerator unless AddOrder.Unspecified is used.
/// </summary>
/// <value>This specifies where Add places an item.</value>
public CollectionOrder CollectionOrder
{
get
{
return _collectionOrder;
}
set
{
_collectionOrder = value;
}
}
/// <summary>
/// This converts the Object retruned from the non generic IEnumerator to T.
/// </summary>
/// <value>Converts the Object retruned from the non generic IEnumerator to T.</value>
public Converter<Object, T> Converter
{
get
{
return _converter;
}
set
{
_converter = value;
}
}
/// <summary>
/// Runs all of the tests on MoveNext().
/// </summary>
/// <returns>true if all of the test passed else false.</returns>
public bool MoveNext_Tests()
{
bool retValue = true;
int iterations = 0;
IEnumerator<T> enumerator = _collection.GetEnumerator();
String testDescription = "No description of test available";
try
{
//[] Call MoveNext() untill the end of the collection has been reached
testDescription = "1082ahhd Call MoveNext() untill the end of the collection has been reached";
while (enumerator.MoveNext())
{
iterations++;
}
retValue &= m_test.Eval(_items.Length, iterations, "Err_64897adhs Number of items to iterate through");
//[] Call MoveNext() several times after the end of the collection has been reached
testDescription = "78083adshp Call MoveNext() several times after the end of the collection has been reached";
for (int j = 0; j < 3; j++)
{
try
{
T tempCurrent = enumerator.Current;
}
catch (Exception) { }//Behavior of Current here is undefined
retValue &= m_test.Eval(!enumerator.MoveNext(),
"Err_1081adohs Expected MoveNext() to return false on the {0} after the end of the collection has been reached\n", j + 1);
}
}
catch (Exception e)
{
retValue &= m_test.Eval(false, "The following test: \n{0} threw the following exception: \n {1}\n", testDescription, e);
}
return retValue;
}
/// <summary>
/// Runs all of the tests on Current.
/// </summary>
/// <returns>true if all of the test passed else false.</returns>
public bool Current_Tests()
{
bool retValue = true;
IEnumerator<T> enumerator;
String testDescription = "No description of test available";
try
{
//[] Call MoveNext() untill the end of the collection has been reached
testDescription = "1082ahhd Call MoveNext() untill the end of the collection has been reached";
enumerator = _collection.GetEnumerator();
retValue &= m_test.Eval(VerifyEnumerator(enumerator, _items), "Err_" + testDescription + " FAILED\n");
//[] Enumerate only part of the collection
testDescription = "64589eahps Enumerate only part of the collection ";
enumerator = _collection.GetEnumerator();
retValue &= m_test.Eval(VerifyEnumerator(enumerator, _items, 0, _items.Length / 2, ExpectedEnumeratorRange.Start, true),
"Err_" + testDescription + " FAILED\n");
}
catch (Exception e)
{
retValue &= m_test.Eval(false, "The following test: \n{0} threw the following exception: \n {1}\n", testDescription, e);
}
return retValue;
}
/// <summary>
/// Runs tests when the collection has been modified after
/// the enumerator was created.
/// </summary>
/// <returns>true if all of the test passed else false.</returns>
public bool ModifiedCollection_Test()
{
bool retValue = true;
IEnumerator<T> enumerator;
String testDescription = "No description of test available";
bool atEnd;
try
{
if (null == _modifyCollection)
{
//We have no way to modify the collection so we will just have to return true;
return true;
}
//[] Verify Modifying collecton with new Enumerator
testDescription = "7885huad Verify Modifying collecton with new Enumerator";
enumerator = _collection.GetEnumerator();
atEnd = _items.Length <= 1;
_items = _modifyCollection(_collection, _items);
retValue &= m_test.Eval(VerifyModifiedEnumerator(enumerator, atEnd), "Err_" + testDescription + " FAILED\n");
//[] Verify enumerating to the first item
if (0 != _items.Length)
{
testDescription = "3158eadf Verify enumerating to the first item";
enumerator = _collection.GetEnumerator();
atEnd = 1 == _items.Length;
retValue &= m_test.Eval(VerifyEnumerator(enumerator, _items, 0, 1, ExpectedEnumeratorRange.Start, true),
"Err_" + testDescription + " FAILED\n");
//[] Verify Modifying collection on an enumerator that has enumerated to the first item in the collection
testDescription = "9434hhk Verify Modifying collection on an enumerator that has enumerated to the first item in the collection";
_items = _modifyCollection(_collection, _items);
retValue &= m_test.Eval(VerifyModifiedEnumerator(enumerator, atEnd), "Err_" + testDescription + " FAILED\n");
}
//[] Verify enumerating part of the collection
if (0 != _items.Length)
{
testDescription = "128uhkh Verify enumerating part of the collection";
enumerator = _collection.GetEnumerator();
retValue &= m_test.Eval(VerifyEnumerator(enumerator, _items, 0, _items.Length / 2, ExpectedEnumeratorRange.Start, true),
"Err_" + testDescription + " FAILED\n");
//[] Verify Modifying collection on an enumerator that has enumerated part of the collection
testDescription = "3549hkhu Verify Modifying collection on an enumerator that has enumerated part of the collection";
_items = _modifyCollection(_collection, _items);
retValue &= m_test.Eval(VerifyModifiedEnumerator(enumerator, false), "Err_" + testDescription + " FAILED\n");
}
//[] Verify enumerating the entire collection
if (0 != _items.Length)
{
testDescription = "3874khlerd Verify enumerating the entire collection";
enumerator = _collection.GetEnumerator();
retValue &= m_test.Eval(VerifyEnumerator(enumerator, _items), "Err_" + testDescription + " FAILED\n");
//[] Verify Modifying collection on an enumerator that has enumerated the entire collection
testDescription = "55403hoa Verify Modifying collection on an enumerator that has enumerated the entire collection";
_items = _modifyCollection(_collection, _items);
retValue &= m_test.Eval(VerifyModifiedEnumerator(enumerator, true), "Err_" + testDescription + " FAILED\n");
}
//[] Verify enumerating past the end of the collection
if (0 != _items.Length)
{
testDescription = "77564hklu Verify enumerating past the end of the collection";
enumerator = _collection.GetEnumerator();
retValue &= m_test.Eval(VerifyEnumerator(enumerator, _items), "Err_" + testDescription + " FAILED\n");
//[] Verify Modifying collection on an enumerator that has enumerated past the end of the collection
testDescription = "984uhluh Verify Modifying collection on an enumerator that has enumerated past the end of the collection";
_items = _modifyCollection(_collection, _items);
retValue &= m_test.Eval(VerifyModifiedEnumerator(enumerator, true), "Err_" + testDescription + " FAILED\n");
}
}
catch (Exception e)
{
retValue &= m_test.Eval(false, "The following test: \n{0} threw the following exception: \n {1}", testDescription, e);
}
return retValue;
}
public bool NonGenericIEnumerable_Test()
{
bool retValue = true;
IEnumerable_Test nonGenericTests;
object[] objectItems = new object[_items.Length];
_items.CopyTo(objectItems, 0);
if (_modifyCollection == null)
{
nonGenericTests = new IEnumerable_Test(_collection, objectItems, null);
}
else
{
nonGenericTests = new IEnumerable_Test(_collection, objectItems, NonGenericModifyCollection);
}
nonGenericTests.IsGenericCompatibility = true;
nonGenericTests.VerificationLevel = _verificationLevel;
nonGenericTests.CollectionOrder = _collectionOrder;
nonGenericTests.IsResetNotSupported = _isResetNotSupported;
nonGenericTests.MoveNextAtEndThrowsOnModifiedCollection = _moveNextAtEndThrowsOnModifiedCollection;
if (_converter == null)
{
nonGenericTests.Comparer = new ObjectComparer<T>(_comparer);
}
else
{
nonGenericTests.Comparer = new ObjectComparerWithConverter<T>(_comparer, _converter);
}
retValue &= nonGenericTests.RunAllTests();
return retValue;
}
private bool VerifyModifiedEnumerator(IEnumerator<T> enumerator, bool atEnd)
{
bool retValue = true;
//[] Verify Current
try
{
T currentItem = enumerator.Current;
}
catch (Exception) { }
//[] Verify MoveNext()
if (!atEnd || _moveNextAtEndThrowsOnModifiedCollection)
{
try
{
enumerator.MoveNext();
retValue &= m_test.Eval(false, "Err_2507poaq: MoveNext() should have thrown an exception on a modified collection");
}
catch (InvalidOperationException) { }
catch (Exception e)
{
retValue &= m_test.Eval(false,
"Err_6186pypa: MoveNext() should have thrown an InvalidOperationException on a modified collection but {0} was thrown", e.GetType());
}
}
else
{
// The eumerator is positioned at the end of the collection and it shouldn't throw
retValue &= m_test.Eval(!enumerator.MoveNext(), "Err_3923lgtk: MoveNext() should have returned false at the end of the collection");
}
return retValue;
}
protected bool VerifyCollection(IEnumerable<T> collection, T[] expectedItems)
{
return VerifyCollection(collection, expectedItems, 0, expectedItems.Length);
}
protected bool VerifyCollection(IEnumerable<T> collection, T[] expectedItems, int startIndex, int count)
{
return VerifyEnumerator(collection.GetEnumerator(), expectedItems, startIndex, count, ExpectedEnumeratorRange.Start | ExpectedEnumeratorRange.End);
}
private bool VerifyEnumerator(IEnumerator<T> enumerator, T[] expectedItems)
{
return VerifyEnumerator(enumerator, expectedItems, 0, expectedItems.Length, ExpectedEnumeratorRange.Start | ExpectedEnumeratorRange.End);
}
private bool VerifyEnumerator(IEnumerator<T> enumerator, T[] expectedItems, int startIndex, int count, ExpectedEnumeratorRange expectedEnumeratorRange)
{
return VerifyEnumerator(enumerator, expectedItems, startIndex, count, expectedEnumeratorRange, false);
}
private bool VerifyEnumerator(
IEnumerator<T> enumerator,
T[] expectedItems,
int startIndex,
int count,
ExpectedEnumeratorRange expectedEnumeratorRange,
bool looseMatchingUnspecifiedOrder)
{
bool retValue = true;
int iterations = 0;
if ((expectedEnumeratorRange & ExpectedEnumeratorRange.Start) != 0)
{
//[] Verify non deterministic behavior of current every time it is called before a call to MoveNext() has been made
for (int i = 0; i < 3; i++)
{
try
{
T tempCurrent = enumerator.Current;
}
catch (Exception) { }
}
}
if (_collectionOrder == CollectionOrder.Unspecified)
{
System.Collections.BitArray itemsVisited;
bool itemFound;
if (looseMatchingUnspecifiedOrder)
{
itemsVisited = new System.Collections.BitArray(expectedItems.Length, false);
}
else
{
itemsVisited = new System.Collections.BitArray(count, false);
}
while ((iterations < count) && enumerator.MoveNext())
{
T currentItem = enumerator.Current;
T tempItem;
//[] Verify we have not gotten more items then we expected
retValue &= m_test.Eval(iterations < count, "Err_9844awpa More items have been returned fromt the enumerator({0} items) then are " +
"in the expectedElements({1} items)", iterations, count);
//[] Verify Current returned the correct value
itemFound = false;
for (int i = 0; i < itemsVisited.Length; ++i)
{
if (!itemsVisited[i] && _comparer.Equals(currentItem, expectedItems[startIndex + i]))
{
itemsVisited[i] = true;
itemFound = true;
break;
}
}
retValue &= m_test.Eval(itemFound, "Err_1432pauy Current returned unexpected value={0}", currentItem);
//[] Verify Current always returns the same value every time it is called
for (int i = 0; i < 3; i++)
{
tempItem = enumerator.Current;
retValue &= m_test.Eval(_comparer.Equals(currentItem, tempItem),
"Err_8776phaw Current is returning inconsistant results Current returned={0} expected={1}", tempItem, currentItem);
}
iterations++;
}
if (looseMatchingUnspecifiedOrder)
{
int visitedItemsCount = 0;
for (int i = 0; i < itemsVisited.Length; ++i)
{
if (itemsVisited[i])
{
++visitedItemsCount;
}
}
m_test.Eval(count, visitedItemsCount, "Err_2398289aheid Number of items enumerator returned");
}
else
{
for (int i = 0; i < count; ++i)
{
retValue &= m_test.Eval(itemsVisited[i], "Err_052848ahiedoi Expected Current to return {0}", expectedItems[startIndex + i]);
}
}
}
else
{
while ((iterations < count) && enumerator.MoveNext())
{
T currentItem = enumerator.Current;
T tempItem;
//[] Verify we have not gotten more items then we expected
retValue &= m_test.Eval(iterations < count, "Err_9844awpa More items have been returned fromt the enumerator({0} items) then are " +
"in the expectedElements({1} items)", iterations, count);
//[] Verify Current returned the correct value
retValue &= m_test.Eval(_comparer.Equals(currentItem, expectedItems[startIndex + iterations]),
"Err_1432pauy Current returned unexpected value={0} expected={1}", currentItem, expectedItems[startIndex + iterations]);
//[] Verify Current always returns the same value every time it is called
for (int i = 0; i < 3; i++)
{
tempItem = enumerator.Current;
retValue &= m_test.Eval(_comparer.Equals(currentItem, tempItem),
"Err_8776phaw Current is returning inconsistant results Current returned={0} expected={1}", tempItem, currentItem);
}
iterations++;
}
}
retValue &= m_test.Eval(count, iterations, "Err_658805eauz Number of items to iterate through");
if ((expectedEnumeratorRange & ExpectedEnumeratorRange.End) != 0)
{
for (int i = 0; i < 3; i++)
{
retValue &= m_test.Eval(!enumerator.MoveNext(), "Err_2929ahiea Expected MoveNext to return false after {0} iterations", iterations);
}
//[] Verify non deterministic behavior of current every time it is called after the enumerator is positioned after the last item
for (int i = 0; i < 3; i++)
{
try
{
T tempCurrent = enumerator.Current;
}
catch (Exception) { }
}
}
return retValue;
}
private object[] NonGenericModifyCollection(IEnumerable collection, Object[] expectedItems)
{
T[] stronglyTypedExpectedItems = new T[expectedItems.Length];
T[] stronglyTypedResult;
Object[] result;
Array.Copy(expectedItems, 0, stronglyTypedExpectedItems, 0, expectedItems.Length);
stronglyTypedResult = _modifyCollection((IEnumerable<T>)collection, stronglyTypedExpectedItems);
result = new Object[stronglyTypedResult.Length];
Array.Copy(stronglyTypedResult, 0, result, 0, stronglyTypedResult.Length);
return result;
}
}
public class ObjectComparer<T> : IEqualityComparer<Object>
{
private IEqualityComparer<T> _comparer;
public ObjectComparer(IEqualityComparer<T> comparer)
{
_comparer = comparer;
}
public new bool Equals(object x, object y) { return _comparer.Equals((T)x, (T)y); }
public int GetHashCode(object x) { return _comparer.GetHashCode((T)x); }
}
public class ObjectComparerWithConverter<T> : IEqualityComparer<Object>
{
private IEqualityComparer<T> _comparer;
private Converter<Object, T> _converter;
public ObjectComparerWithConverter(IEqualityComparer<T> comparer, Converter<Object, T> converter)
{
_comparer = comparer;
_converter = converter;
}
public new bool Equals(object x, object y) { return _comparer.Equals(Convert(x), Convert(y)); }
public int GetHashCode(object x) { return _comparer.GetHashCode(Convert(x)); }
private T Convert(Object item)
{
if (item is T)
{
return (T)item;
}
else
{
return _converter(item);
}
}
}
public class ConverterHelper
{
public static System.Collections.Generic.KeyValuePair<K, V> DictionaryEntryToKeyValuePairConverter<K, V>(Object item)
{
System.Collections.DictionaryEntry dictionaryEntry = (System.Collections.DictionaryEntry)item;
return new System.Collections.Generic.KeyValuePair<K, V>((K)dictionaryEntry.Key, (V)dictionaryEntry.Value);
}
}
}
}
| |
/**
* Copyright 2015 d-fens GmbH
*
* 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 biz.dfch.CS.Web.Utilities.Rest;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Net.Http;
using System.Net.Http.Headers;
using Telerik.JustMock;
using HttpMethod = biz.dfch.CS.Web.Utilities.Rest.HttpMethod;
namespace biz.dfch.CS.Web.Utilities.Tests.Rest
{
[TestClass]
public class RestCallExecutorTest
{
private const string URI = "http://test/api/entities";
private const string CONTENT_TYPE_KEY = "Content-Type";
private const string CONTENT_TYPE_VALUE = "application/vnd.abiquo.acceptedrequest+json; version=3.8";
private const string USER_AGENT_KEY = "User-Agent";
private const string AUTHORIZATION_HEADER_KEY = "Authorization";
private const string ACCEPT_HEADER_KEY = "Accept";
private const string ACCEPT_HEADER_VALUE = "application/arb.itrary+json;version=1.0";
private const string TEST_USER_AGENT = "test-agent";
private const string SAMPLE_REQUEST_BODY = "{\"Property\":\"value\"}";
private const string SAMPLE_RESPONSE_BODY = "{\"Property2\":\"value2\"}";
private const string BEARER_AUTH_SCHEME = "Bearer";
private const string SAMPLE_BEARER_TOKEN = "AbCdEf123456";
private HttpClient HttpClient;
[TestInitialize]
public void TestInitilize()
{
HttpClient = Mock.Create<HttpClient>();
}
[TestMethod]
public void RestCallExecutorConstructorSetsProperties()
{
// Arrange
// Act
var restCallExecutor = new RestCallExecutor();
// Assert
Assert.AreEqual(true, restCallExecutor.EnsureSuccessStatusCode);
Assert.AreEqual(ContentType.ApplicationJson, restCallExecutor.ContentType);
Assert.AreEqual(90, restCallExecutor.Timeout);
}
[TestMethod]
public void RestCallExecutorConstructorSetsEnsureSuccessCodePropertyAccordingConstructorParameter()
{
// Arrange
// Act
var restCallExecutor = new RestCallExecutor(false);
// Assert
Assert.AreEqual(false, restCallExecutor.EnsureSuccessStatusCode);
Assert.AreEqual(ContentType.ApplicationJson, restCallExecutor.ContentType);
Assert.AreEqual(90, restCallExecutor.Timeout);
}
[TestMethod]
[ExpectedException(typeof(UriFormatException))]
public void InvokeWithInvalidUriThrowsUriFormatException1()
{
// Arrange
var invalidUri = "abc";
RestCallExecutor restCallExecutor = new RestCallExecutor();
// Act
restCallExecutor.Invoke(invalidUri);
// Assert
}
[TestMethod]
[ExpectedException(typeof(UriFormatException))]
public void InvokeWithInvalidUriThrowsUriFormatException2()
{
// Arrange
var invalidUri = "abc";
RestCallExecutor restCallExecutor = new RestCallExecutor();
// Act
restCallExecutor.Invoke(invalidUri, null);
// Assert
}
[TestMethod]
[ExpectedException(typeof(UriFormatException))]
public void InvokeWithInvalidUriThrowsUriFormatException3()
{
// Arrange
var invalidUri = "abc";
RestCallExecutor restCallExecutor = new RestCallExecutor();
// Act
restCallExecutor.Invoke(HttpMethod.Head, invalidUri, null, null);
// Assert
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void InvokeWithNullUriThrowsArgumentException1()
{
// Arrange
string nullUri = null;
RestCallExecutor restCallExecutor = new RestCallExecutor();
// Act
restCallExecutor.Invoke(nullUri);
// Assert
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void InvokeWithNullUriThrowsArgumentException2()
{
// Arrange
string nullUri = null;
RestCallExecutor restCallExecutor = new RestCallExecutor();
// Act
restCallExecutor.Invoke(nullUri, null);
// Assert
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void InvokeWithNullUriThrowsArgumentException3()
{
// Arrange
string nullUri = null;
RestCallExecutor restCallExecutor = new RestCallExecutor();
// Act
restCallExecutor.Invoke(HttpMethod.Head, nullUri, null, null);
// Assert
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void InvokeWithWhitespaceUriThrowsArgumentException1()
{
// Arrange
var whitespaceUri = " ";
RestCallExecutor restCallExecutor = new RestCallExecutor();
// Act
restCallExecutor.Invoke(whitespaceUri);
// Assert
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void InvokeWithWhitespaceUriThrowsArgumentException2()
{
// Arrange
var whitespaceUri = " ";
RestCallExecutor restCallExecutor = new RestCallExecutor();
// Act
restCallExecutor.Invoke(whitespaceUri, null);
// Assert
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void InvokeWithWhitespaceUriThrowsArgumentException3()
{
// Arrange
var whitespaceUri = " ";
RestCallExecutor restCallExecutor = new RestCallExecutor();
// Act
restCallExecutor.Invoke(HttpMethod.Head, whitespaceUri, null, null);
// Assert
}
[TestMethod]
public void InvokeGetExecutesGetRequestOnUriWithProvidedHeadersEnsuresSuccessStatusCodeAndReturnsResponseContent()
{
// Arrange
var mockedResponseMessage = Mock.Create<HttpResponseMessage>();
var mockedRequestHeaders = Mock.Create<HttpRequestHeaders>();
Mock.Arrange(() => HttpClient.DefaultRequestHeaders)
.IgnoreInstance()
.Returns(mockedRequestHeaders)
.Occurs(3);
Mock.Arrange(() => mockedRequestHeaders.Add(USER_AGENT_KEY, TEST_USER_AGENT))
.OccursOnce();
Mock.Arrange(() => mockedRequestHeaders.TryAddWithoutValidation(ACCEPT_HEADER_KEY, ACCEPT_HEADER_VALUE))
.OccursOnce();
Mock.Arrange(() => HttpClient.GetAsync(Arg.Is(new Uri(URI))).Result)
.IgnoreInstance()
.Returns(mockedResponseMessage)
.OccursOnce();
Mock.Arrange(() => mockedResponseMessage.EnsureSuccessStatusCode())
.OccursOnce();
Mock.Arrange(() => mockedResponseMessage.Content.ReadAsStringAsync().Result)
.Returns(SAMPLE_RESPONSE_BODY)
.OccursOnce();
RestCallExecutor restCallExecutor = new RestCallExecutor();
// Act
var result = restCallExecutor.Invoke(URI, CreateSampleHeaders());
// Assert
Assert.AreEqual(SAMPLE_RESPONSE_BODY, result);
Mock.Assert(HttpClient);
Mock.Assert(mockedRequestHeaders);
Mock.Assert(mockedResponseMessage);
}
[TestMethod]
public void InvokeGetExecutesGetRequestOnUriWithProvidedHeadersNotEnsuringSuccessStatusCodeReturnsResponseContent()
{
// Arrange
var mockedResponseMessage = Mock.Create<HttpResponseMessage>();
var mockedRequestHeaders = Mock.Create<HttpRequestHeaders>();
Mock.Arrange(() => HttpClient.DefaultRequestHeaders)
.IgnoreInstance()
.Returns(mockedRequestHeaders)
.Occurs(3);
Mock.Arrange(() => mockedRequestHeaders.Add(USER_AGENT_KEY, TEST_USER_AGENT))
.OccursOnce();
Mock.Arrange(() => mockedRequestHeaders.TryAddWithoutValidation(ACCEPT_HEADER_KEY, ACCEPT_HEADER_VALUE))
.OccursOnce();
Mock.Arrange(() => HttpClient.GetAsync(Arg.Is(new Uri(URI))).Result)
.IgnoreInstance()
.Returns(mockedResponseMessage)
.OccursOnce();
Mock.Arrange(() => mockedResponseMessage.Content.ReadAsStringAsync().Result)
.Returns(SAMPLE_RESPONSE_BODY)
.OccursOnce();
RestCallExecutor restCallExecutor = new RestCallExecutor(false);
// Act
var result = restCallExecutor.Invoke(URI, CreateSampleHeaders());
Assert.AreEqual(SAMPLE_RESPONSE_BODY, result);
// Assert
Mock.Assert(HttpClient);
Mock.Assert(mockedRequestHeaders);
Mock.Assert(mockedResponseMessage);
}
[TestMethod]
[ExpectedException(typeof(HttpRequestException))]
public void InvokeExecutesThrowsHttpRequestExceptionIfEnsureSuccessStatusCodeFails()
{
// Arrange
var mockedResponseMessage = Mock.Create<HttpResponseMessage>();
var mockedRequestHeaders = Mock.Create<HttpRequestHeaders>();
Mock.Arrange(() => HttpClient.DefaultRequestHeaders)
.IgnoreInstance()
.Returns(mockedRequestHeaders)
.Occurs(3);
Mock.Arrange(() => mockedRequestHeaders.Add(USER_AGENT_KEY, TEST_USER_AGENT))
.OccursOnce();
Mock.Arrange(() => mockedRequestHeaders.TryAddWithoutValidation(ACCEPT_HEADER_KEY, ACCEPT_HEADER_VALUE))
.OccursOnce();
Mock.Arrange(() => HttpClient.GetAsync(Arg.Is(new Uri(URI))).Result)
.IgnoreInstance()
.Returns(mockedResponseMessage)
.OccursOnce();
Mock.Arrange(() => mockedResponseMessage.EnsureSuccessStatusCode())
.Throws<HttpRequestException>()
.OccursOnce();
RestCallExecutor restCallExecutor = new RestCallExecutor();
// Act
restCallExecutor.Invoke(URI, CreateSampleHeaders());
// Assert
Mock.Assert(HttpClient);
Mock.Assert(mockedRequestHeaders);
Mock.Assert(mockedResponseMessage);
}
[TestMethod]
public void InvokeSetsDefaultUserAgentHeaderIfNoCustomUserAgentHeaderProvided()
{
// Arrange
var mockedResponseMessage = Mock.Create<HttpResponseMessage>();
var mockedRequestHeaders = Mock.Create<HttpRequestHeaders>();
Mock.Arrange(() => HttpClient.DefaultRequestHeaders)
.IgnoreInstance()
.Returns(mockedRequestHeaders)
.Occurs(2);
Mock.Arrange(() => mockedRequestHeaders.Add(USER_AGENT_KEY, "RestCallExecutor"))
.OccursOnce();
Mock.Arrange(() => HttpClient.GetAsync(Arg.Is(new Uri(URI))).Result)
.IgnoreInstance()
.Returns(mockedResponseMessage)
.OccursOnce();
Mock.Arrange(() => mockedResponseMessage.EnsureSuccessStatusCode())
.OccursOnce();
Mock.Arrange(() => mockedResponseMessage.Content.ReadAsStringAsync().Result)
.Returns(SAMPLE_RESPONSE_BODY)
.OccursOnce();
RestCallExecutor restCallExecutor = new RestCallExecutor();
var result = restCallExecutor.Invoke(URI);
// Act
Assert.AreEqual(SAMPLE_RESPONSE_BODY, result);
// Assert
Mock.Assert(HttpClient);
Mock.Assert(mockedRequestHeaders);
Mock.Assert(mockedResponseMessage);
}
[TestMethod]
public void InvokePostOverwritesDefaultContentTypeHeaderIfCustomContentTypeHeaderProvided()
{
// Arrange
var mockedResponseMessage = Mock.Create<HttpResponseMessage>();
var mockedRequestHeaders = Mock.Create<HttpRequestHeaders>();
Mock.Arrange(() => HttpClient.DefaultRequestHeaders)
.IgnoreInstance()
.Returns(mockedRequestHeaders)
.Occurs(4);
Mock.Arrange(() => mockedRequestHeaders.Add(USER_AGENT_KEY, TEST_USER_AGENT))
.OccursOnce();
Mock.Arrange(() => mockedRequestHeaders.TryAddWithoutValidation(ACCEPT_HEADER_KEY, ACCEPT_HEADER_VALUE))
.OccursOnce();
var content = new StringContent(SAMPLE_REQUEST_BODY);
Mock.Arrange(() => HttpClient.PostAsync(Arg.Is(new Uri(URI)), Arg.Is(content)).Result)
.IgnoreInstance()
.Returns(mockedResponseMessage)
.OccursOnce();
Mock.Arrange(() => mockedResponseMessage.EnsureSuccessStatusCode())
.OccursOnce();
Mock.Arrange(() => mockedResponseMessage.Content.ReadAsStringAsync().Result)
.Returns(SAMPLE_RESPONSE_BODY)
.OccursOnce();
RestCallExecutor restCallExecutor = new RestCallExecutor();
var headers = CreateSampleHeaders();
headers.Add(CONTENT_TYPE_KEY, CONTENT_TYPE_VALUE);
// Act
var result = restCallExecutor.Invoke(HttpMethod.Post, URI, headers, SAMPLE_RESPONSE_BODY);
// Assert
Assert.AreEqual(SAMPLE_RESPONSE_BODY, result);
Mock.Assert(HttpClient);
Mock.Assert(mockedRequestHeaders);
Mock.Assert(mockedResponseMessage);
}
[TestMethod]
public void InvokeHeadExecutesHeadRequestOnUriWithProvidedHeadersEnsuresSuccessStatusCodeAndReturnsResponseContent()
{
// Arrange
var mockedResponseMessage = Mock.Create<HttpResponseMessage>();
var mockedRequestHeaders = Mock.Create<HttpRequestHeaders>();
Mock.Arrange(() => HttpClient.DefaultRequestHeaders)
.IgnoreInstance()
.Returns(mockedRequestHeaders)
.Occurs(3);
Mock.Arrange(() => mockedRequestHeaders.Add(USER_AGENT_KEY, TEST_USER_AGENT))
.OccursOnce();
Mock.Arrange(() => mockedRequestHeaders.TryAddWithoutValidation(ACCEPT_HEADER_KEY, ACCEPT_HEADER_VALUE))
.OccursOnce();
Mock.Arrange(() => HttpClient.GetAsync(Arg.Is(new Uri(URI))).Result)
.IgnoreInstance()
.Returns(mockedResponseMessage)
.OccursOnce();
Mock.Arrange(() => mockedResponseMessage.EnsureSuccessStatusCode())
.OccursOnce();
Mock.Arrange(() => mockedResponseMessage.Content.ReadAsStringAsync().Result)
.Returns(SAMPLE_RESPONSE_BODY)
.OccursOnce();
RestCallExecutor restCallExecutor = new RestCallExecutor();
// Act
var result = restCallExecutor.Invoke(HttpMethod.Get, URI, CreateSampleHeaders(), null);
// Assert
Assert.AreEqual(SAMPLE_RESPONSE_BODY, result);
Mock.Assert(HttpClient);
Mock.Assert(mockedRequestHeaders);
Mock.Assert(mockedResponseMessage);
}
[TestMethod]
public void InvokePostExecutesPostRequestOnUriWithProvidedHeadersAndBodyEnsuresSuccessStatusCodeAndReturnsResponseContent()
{
// Arrange
var mockedResponseMessage = Mock.Create<HttpResponseMessage>();
var mockedRequestHeaders = Mock.Create<HttpRequestHeaders>();
Mock.Arrange(() => HttpClient.DefaultRequestHeaders)
.IgnoreInstance()
.Returns(mockedRequestHeaders)
.Occurs(3);
Mock.Arrange(() => mockedRequestHeaders.Add(USER_AGENT_KEY, TEST_USER_AGENT))
.OccursOnce();
Mock.Arrange(() => mockedRequestHeaders.TryAddWithoutValidation(ACCEPT_HEADER_KEY, ACCEPT_HEADER_VALUE))
.OccursOnce();
HttpContent content = new StringContent(SAMPLE_REQUEST_BODY);
Mock.Arrange(() => HttpClient.PostAsync(Arg.Is(new Uri(URI)), Arg.Is(content)).Result)
.IgnoreInstance()
.Returns(mockedResponseMessage)
.OccursOnce();
Mock.Arrange(() => mockedResponseMessage.EnsureSuccessStatusCode())
.OccursOnce();
Mock.Arrange(() => mockedResponseMessage.Content.ReadAsStringAsync().Result)
.Returns(SAMPLE_RESPONSE_BODY)
.OccursOnce();
RestCallExecutor restCallExecutor = new RestCallExecutor();
// Act
var result = restCallExecutor.Invoke(HttpMethod.Post, URI, CreateSampleHeaders(), SAMPLE_REQUEST_BODY);
// Assert
Assert.AreEqual(SAMPLE_RESPONSE_BODY, result);
Assert.AreEqual(ContentType.ApplicationJson, restCallExecutor.ContentType);
Mock.Assert(HttpClient);
Mock.Assert(mockedRequestHeaders);
Mock.Assert(mockedResponseMessage);
}
[TestMethod]
public void InvokeDeleteExecutesDeleteRequestOnUriWithProvidedHeadersAndBodyEnsuresSuccessStatusCodeAndReturnsResponseContent()
{
// Arrange
var mockedResponseMessage = Mock.Create<HttpResponseMessage>();
var mockedRequestHeaders = Mock.Create<HttpRequestHeaders>();
Mock.Arrange(() => HttpClient.DefaultRequestHeaders)
.IgnoreInstance()
.Returns(mockedRequestHeaders)
.Occurs(3);
Mock.Arrange(() => mockedRequestHeaders.Add(USER_AGENT_KEY, TEST_USER_AGENT))
.OccursOnce();
Mock.Arrange(() => mockedRequestHeaders.TryAddWithoutValidation(ACCEPT_HEADER_KEY, ACCEPT_HEADER_VALUE))
.Returns(true)
.OccursOnce();
Mock.Arrange(() => HttpClient.DeleteAsync(Arg.Is(new Uri(URI))).Result)
.IgnoreInstance()
.Returns(mockedResponseMessage)
.OccursOnce();
Mock.Arrange(() => mockedResponseMessage.EnsureSuccessStatusCode())
.OccursOnce();
Mock.Arrange(() => mockedResponseMessage.Content.ReadAsStringAsync().Result)
.Returns(SAMPLE_RESPONSE_BODY)
.OccursOnce();
RestCallExecutor restCallExecutor = new RestCallExecutor();
// Act
var result = restCallExecutor.Invoke(HttpMethod.Delete, URI, CreateSampleHeaders(), SAMPLE_REQUEST_BODY);
Assert.AreEqual(SAMPLE_RESPONSE_BODY, result);
// Assert
Mock.Assert(HttpClient);
Mock.Assert(mockedRequestHeaders);
Mock.Assert(mockedResponseMessage);
}
[TestMethod]
public void InvokePutExecutesPutRequestOnUriWithProvidedHeadersAndBodyEnsuresSuccessStatusCodeAndReturnsResponseContent()
{
// Arrange
var mockedResponseMessage = Mock.Create<HttpResponseMessage>();
var mockedRequestHeaders = Mock.Create<HttpRequestHeaders>();
Mock.Arrange(() => HttpClient.DefaultRequestHeaders)
.IgnoreInstance()
.Returns(mockedRequestHeaders)
.Occurs(3);
Mock.Arrange(() => mockedRequestHeaders.Add(USER_AGENT_KEY, TEST_USER_AGENT))
.OccursOnce();
Mock.Arrange(() => mockedRequestHeaders.TryAddWithoutValidation(ACCEPT_HEADER_KEY, ACCEPT_HEADER_VALUE))
.OccursOnce();
HttpContent content = new StringContent(SAMPLE_REQUEST_BODY);
Mock.Arrange(() => HttpClient.PutAsync(Arg.Is(new Uri(URI)), Arg.Is(content)).Result)
.IgnoreInstance()
.Returns(mockedResponseMessage)
.OccursOnce();
Mock.Arrange(() => mockedResponseMessage.EnsureSuccessStatusCode())
.OccursOnce();
Mock.Arrange(() => mockedResponseMessage.Content.ReadAsStringAsync().Result)
.Returns(SAMPLE_RESPONSE_BODY)
.OccursOnce();
RestCallExecutor restCallExecutor = new RestCallExecutor();
// Act
var result = restCallExecutor.Invoke(HttpMethod.Put, URI, CreateSampleHeaders(), SAMPLE_REQUEST_BODY);
// Assert
Assert.AreEqual(SAMPLE_RESPONSE_BODY, result);
Assert.AreEqual(ContentType.ApplicationJson, restCallExecutor.ContentType);
Mock.Assert(HttpClient);
Mock.Assert(mockedRequestHeaders);
Mock.Assert(mockedResponseMessage);
}
[TestMethod]
public void InvokeWhenAuthSchemeIsSetSetsAuthorizationHeaderAccordingAuthScheme()
{
// Arrange
var mockedResponseMessage = Mock.Create<HttpResponseMessage>();
var mockedRequestHeaders = Mock.Create<HttpRequestHeaders>();
Mock.Arrange(() => HttpClient.DefaultRequestHeaders)
.IgnoreInstance()
.Returns(mockedRequestHeaders)
.Occurs(4);
Mock.ArrangeSet(() => mockedRequestHeaders.Authorization = Arg.Is(new AuthenticationHeaderValue(BEARER_AUTH_SCHEME, SAMPLE_BEARER_TOKEN)))
.OccursOnce();
Mock.Arrange(() => mockedRequestHeaders.Add(USER_AGENT_KEY, TEST_USER_AGENT))
.OccursOnce();
Mock.Arrange(() => mockedRequestHeaders.TryAddWithoutValidation(ACCEPT_HEADER_KEY, ACCEPT_HEADER_VALUE))
.OccursOnce();
Mock.Arrange(() => HttpClient.GetAsync(Arg.Is(new Uri(URI))).Result)
.IgnoreInstance()
.Returns(mockedResponseMessage)
.OccursOnce();
Mock.Arrange(() => mockedResponseMessage.EnsureSuccessStatusCode())
.OccursOnce();
Mock.Arrange(() => mockedResponseMessage.Content.ReadAsStringAsync().Result)
.Returns(SAMPLE_RESPONSE_BODY)
.OccursOnce();
RestCallExecutor restCallExecutor = new RestCallExecutor();
restCallExecutor.AuthScheme = BEARER_AUTH_SCHEME;
var headers = CreateSampleHeaders();
headers.Add(AUTHORIZATION_HEADER_KEY, SAMPLE_BEARER_TOKEN);
// Act
var result = restCallExecutor.Invoke(HttpMethod.Get, URI, headers, null);
Assert.AreEqual(SAMPLE_RESPONSE_BODY, result);
// Assert
Mock.Assert(HttpClient);
Mock.Assert(mockedRequestHeaders);
Mock.AssertSet(() => mockedRequestHeaders.Authorization = Arg.Is(new AuthenticationHeaderValue(BEARER_AUTH_SCHEME, SAMPLE_BEARER_TOKEN)));
Mock.Assert(mockedResponseMessage);
}
[TestMethod]
public void InvokeSetsAuthorizationHeaderAccordingHeadersDictionaryWhenAuthSchemeIsNotSet()
{
// Arrange
var mockedResponseMessage = Mock.Create<HttpResponseMessage>();
var mockedRequestHeaders = Mock.Create<HttpRequestHeaders>();
Mock.Arrange(() => HttpClient.DefaultRequestHeaders)
.IgnoreInstance()
.Returns(mockedRequestHeaders)
.Occurs(4);
Mock.ArrangeSet(() => mockedRequestHeaders.Authorization = new AuthenticationHeaderValue(BEARER_AUTH_SCHEME, SAMPLE_BEARER_TOKEN))
.OccursNever();
Mock.Arrange(() => mockedRequestHeaders.TryAddWithoutValidation(AUTHORIZATION_HEADER_KEY, SAMPLE_BEARER_TOKEN))
.OccursOnce();
Mock.Arrange(() => mockedRequestHeaders.Add(USER_AGENT_KEY, TEST_USER_AGENT))
.OccursOnce();
Mock.Arrange(() => mockedRequestHeaders.TryAddWithoutValidation(ACCEPT_HEADER_KEY, ACCEPT_HEADER_VALUE))
.OccursOnce();
Mock.Arrange(() => HttpClient.GetAsync(Arg.Is(new Uri(URI))).Result)
.IgnoreInstance()
.Returns(mockedResponseMessage)
.OccursOnce();
Mock.Arrange(() => mockedResponseMessage.EnsureSuccessStatusCode())
.OccursOnce();
Mock.Arrange(() => mockedResponseMessage.Content.ReadAsStringAsync().Result)
.Returns(SAMPLE_RESPONSE_BODY)
.OccursOnce();
RestCallExecutor restCallExecutor = new RestCallExecutor();
var headers = CreateSampleHeaders();
headers.Add(AUTHORIZATION_HEADER_KEY, SAMPLE_BEARER_TOKEN);
// Act
var result = restCallExecutor.Invoke(HttpMethod.Get, URI, headers, null);
// Assert
Assert.AreEqual(SAMPLE_RESPONSE_BODY, result);
Mock.Assert(HttpClient);
Mock.Assert(mockedRequestHeaders);
Mock.AssertSet(() => mockedRequestHeaders.Authorization = Arg.Is(new AuthenticationHeaderValue(BEARER_AUTH_SCHEME, SAMPLE_BEARER_TOKEN)));
Mock.Assert(mockedResponseMessage);
}
private IDictionary<string, string> CreateSampleHeaders()
{
var headers = new Dictionary<string, string>();
headers.Add(USER_AGENT_KEY, TEST_USER_AGENT);
headers.Add(ACCEPT_HEADER_KEY, ACCEPT_HEADER_VALUE);
return headers;
}
}
}
| |
//
// redis-sharp.cs: ECMA CLI Binding to the Redis key-value storage system
//
// Authors:
// Miguel de Icaza (miguel@gnome.org)
//
// Copyright 2010 Novell, Inc.
//
// Licensed under the same terms of Redis: new BSD license.
//
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using NServiceKit.Text;
namespace NServiceKit.Redis
{
public partial class RedisNativeClient
{
private void Connect()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) {
SendTimeout = SendTimeout,
ReceiveTimeout = ReceiveTimeout
};
try
{
if (ConnectTimeout == 0)
{
socket.Connect(Host, Port);
}
else
{
var connectResult = socket.BeginConnect(Host, Port, null, null);
connectResult.AsyncWaitHandle.WaitOne(ConnectTimeout, true);
}
if (!socket.Connected)
{
socket.Close();
socket = null;
HadExceptions = true;
return;
}
Bstream = new BufferedStream(new NetworkStream(socket), 16 * 1024);
if (Password != null)
SendExpectSuccess(Commands.Auth, Password.ToUtf8Bytes());
if (db != 0)
SendExpectSuccess(Commands.Select, db.ToUtf8Bytes());
var ipEndpoint = socket.LocalEndPoint as IPEndPoint;
clientPort = ipEndpoint != null ? ipEndpoint.Port : -1;
lastCommand = null;
lastSocketException = null;
LastConnectedAtTimestamp = Stopwatch.GetTimestamp();
if (ConnectionFilter != null)
{
ConnectionFilter(this);
}
}
catch (SocketException ex)
{
if (socket != null)
socket.Close();
socket = null;
HadExceptions = true;
var throwEx = new RedisException("could not connect to redis Instance at " + Host + ":" + Port, ex);
log.Error(throwEx.Message, ex);
throw throwEx;
}
}
protected string ReadLine()
{
var sb = new StringBuilder();
int c;
while ((c = Bstream.ReadByte()) != -1)
{
if (c == '\r')
continue;
if (c == '\n')
break;
sb.Append((char)c);
}
return sb.ToString();
}
public bool IsSocketConnected()
{
var part1 = socket.Poll(1000, SelectMode.SelectRead);
var part2 = (socket.Available == 0);
return !(part1 & part2);
}
private bool AssertConnectedSocket()
{
if (LastConnectedAtTimestamp > 0)
{
var now = Stopwatch.GetTimestamp();
var elapsedSecs = (now - LastConnectedAtTimestamp) / Stopwatch.Frequency;
if (socket == null || (elapsedSecs > IdleTimeOutSecs && !socket.IsConnected()))
{
return Reconnect();
}
LastConnectedAtTimestamp = now;
}
if (socket == null)
{
Connect();
}
var isConnected = socket != null;
return isConnected;
}
private bool Reconnect()
{
var previousDb = db;
SafeConnectionClose();
Connect(); //sets db to 0
if (previousDb != DefaultDb) this.Db = previousDb;
return socket != null;
}
private bool HandleSocketException(SocketException ex)
{
HadExceptions = true;
log.Error("SocketException: ", ex);
lastSocketException = ex;
// timeout?
socket.Close();
socket = null;
return false;
}
private RedisResponseException CreateResponseError(string error)
{
HadExceptions = true;
var throwEx = new RedisResponseException(
string.Format("{0}, sPort: {1}, LastCommand: {2}",
error, clientPort, lastCommand));
log.Error(throwEx.Message);
throw throwEx;
}
private RedisException CreateConnectionError()
{
HadExceptions = true;
var throwEx = new RedisException(
string.Format("Unable to Connect: sPort: {0}",
clientPort), lastSocketException);
log.Error(throwEx.Message);
throw throwEx;
}
private static byte[] GetCmdBytes(char cmdPrefix, int noOfLines)
{
var strLines = noOfLines.ToString();
var strLinesLength = strLines.Length;
var cmdBytes = new byte[1 + strLinesLength + 2];
cmdBytes[0] = (byte)cmdPrefix;
for (var i = 0; i < strLinesLength; i++)
cmdBytes[i + 1] = (byte)strLines[i];
cmdBytes[1 + strLinesLength] = 0x0D; // \r
cmdBytes[2 + strLinesLength] = 0x0A; // \n
return cmdBytes;
}
/// <summary>
/// Command to set multuple binary safe arguments
/// </summary>
/// <param name="cmdWithBinaryArgs"></param>
/// <returns></returns>
protected bool SendCommand(params byte[][] cmdWithBinaryArgs)
{
if (!AssertConnectedSocket()) return false;
try
{
CmdLog(cmdWithBinaryArgs);
//Total command lines count
WriteAllToSendBuffer(cmdWithBinaryArgs);
//pipeline will handle flush, if pipelining is turned on
if (Pipeline == null)
FlushSendBuffer();
}
catch (SocketException ex)
{
cmdBuffer.Clear();
return HandleSocketException(ex);
}
return true;
}
public void WriteAllToSendBuffer(params byte[][] cmdWithBinaryArgs)
{
WriteToSendBuffer(GetCmdBytes('*', cmdWithBinaryArgs.Length));
foreach (var safeBinaryValue in cmdWithBinaryArgs)
{
WriteToSendBuffer(GetCmdBytes('$', safeBinaryValue.Length));
WriteToSendBuffer(safeBinaryValue);
WriteToSendBuffer(endData);
}
}
readonly System.Collections.Generic.IList<ArraySegment<byte>> cmdBuffer = new System.Collections.Generic.List<ArraySegment<byte>>();
byte[] currentBuffer = BufferPool.GetBuffer();
int currentBufferIndex;
public void WriteToSendBuffer(byte[] cmdBytes)
{
if (CouldAddToCurrentBuffer(cmdBytes)) return;
PushCurrentBuffer();
if (CouldAddToCurrentBuffer(cmdBytes)) return;
var bytesCopied = 0;
while (bytesCopied < cmdBytes.Length)
{
var copyOfBytes = BufferPool.GetBuffer();
var bytesToCopy = Math.Min(cmdBytes.Length - bytesCopied, copyOfBytes.Length);
Buffer.BlockCopy(cmdBytes, bytesCopied, copyOfBytes, 0, bytesToCopy);
cmdBuffer.Add(new ArraySegment<byte>(copyOfBytes, 0, bytesToCopy));
bytesCopied += bytesToCopy;
}
}
private bool CouldAddToCurrentBuffer(byte[] cmdBytes)
{
if (cmdBytes.Length + currentBufferIndex < BufferPool.BufferLength)
{
Buffer.BlockCopy(cmdBytes, 0, currentBuffer, currentBufferIndex, cmdBytes.Length);
currentBufferIndex += cmdBytes.Length;
return true;
}
return false;
}
private void PushCurrentBuffer()
{
cmdBuffer.Add(new ArraySegment<byte>(currentBuffer, 0, currentBufferIndex));
currentBuffer = BufferPool.GetBuffer();
currentBufferIndex = 0;
}
public void FlushSendBuffer()
{
if (currentBufferIndex > 0)
PushCurrentBuffer();
if (!Env.IsMono)
{
socket.Send(cmdBuffer); //Optimized for Windows
}
else
{
//Sendling IList<ArraySegment> Throws 'Message to Large' SocketException in Mono
foreach (var segment in cmdBuffer)
{
var buffer = segment.Array;
socket.Send(buffer, segment.Offset, segment.Count, SocketFlags.None);
}
}
ResetSendBuffer();
}
/// <summary>
/// reset buffer index in send buffer
/// </summary>
public void ResetSendBuffer()
{
currentBufferIndex = 0;
for (int i = cmdBuffer.Count - 1; i >= 0; i--)
{
var buffer = cmdBuffer[i].Array;
BufferPool.ReleaseBufferToPool(ref buffer);
cmdBuffer.RemoveAt(i);
}
}
private int SafeReadByte()
{
return Bstream.ReadByte();
}
protected void SendExpectSuccess(params byte[][] cmdWithBinaryArgs)
{
if (!SendCommand(cmdWithBinaryArgs))
throw CreateConnectionError();
if (Pipeline != null)
{
Pipeline.CompleteVoidQueuedCommand(ExpectSuccess);
return;
}
ExpectSuccess();
}
protected long SendExpectLong(params byte[][] cmdWithBinaryArgs)
{
if (!SendCommand(cmdWithBinaryArgs))
throw CreateConnectionError();
if (Pipeline != null)
{
Pipeline.CompleteLongQueuedCommand(ReadInt);
return default(long);
}
return ReadLong();
}
protected byte[] SendExpectData(params byte[][] cmdWithBinaryArgs)
{
if (!SendCommand(cmdWithBinaryArgs))
throw CreateConnectionError();
if (Pipeline != null)
{
Pipeline.CompleteBytesQueuedCommand(ReadData);
return null;
}
return ReadData();
}
protected string SendExpectString(params byte[][] cmdWithBinaryArgs)
{
var bytes = SendExpectData(cmdWithBinaryArgs);
return bytes.FromUtf8Bytes();
}
protected double SendExpectDouble(params byte[][] cmdWithBinaryArgs)
{
if (!SendCommand(cmdWithBinaryArgs))
throw CreateConnectionError();
if (Pipeline != null)
{
Pipeline.CompleteDoubleQueuedCommand(ReadDouble);
return Double.NaN;
}
return ReadDouble();
}
public double ReadDouble()
{
var bytes = ReadData();
return (bytes == null) ? double.NaN : ParseDouble(bytes);
}
public static double ParseDouble(byte[] doubleBytes)
{
var doubleString = Encoding.UTF8.GetString(doubleBytes);
double d;
double.TryParse(doubleString, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out d);
return d;
}
protected string SendExpectCode(params byte[][] cmdWithBinaryArgs)
{
if (!SendCommand(cmdWithBinaryArgs))
throw CreateConnectionError();
if (Pipeline != null)
{
Pipeline.CompleteStringQueuedCommand(ExpectCode);
return null;
}
return ExpectCode();
}
protected byte[][] SendExpectMultiData(params byte[][] cmdWithBinaryArgs)
{
if (!SendCommand(cmdWithBinaryArgs))
throw CreateConnectionError();
if (Pipeline != null)
{
Pipeline.CompleteMultiBytesQueuedCommand(ReadMultiData);
return new byte[0][];
}
return ReadMultiData();
}
protected object[] SendExpectDeeplyNestedMultiData(params byte[][] cmdWithBinaryArgs)
{
if (!SendCommand(cmdWithBinaryArgs))
throw CreateConnectionError();
if (Pipeline != null)
{
throw new NotSupportedException("Pipeline is not supported.");
}
return ReadDeeplyNestedMultiData();
}
[Conditional("DEBUG")]
protected void Log(string fmt, params object[] args)
{
log.DebugFormat("{0}", string.Format(fmt, args).Trim());
}
[Conditional("DEBUG")]
protected void CmdLog(byte[][] args)
{
var sb = new StringBuilder();
foreach (var arg in args)
{
if (sb.Length > 0)
sb.Append(" ");
sb.Append(arg.FromUtf8Bytes());
}
this.lastCommand = sb.ToString();
if (this.lastCommand.Length > 100)
{
this.lastCommand = this.lastCommand.Substring(0, 100) + "...";
}
log.Debug("S: " + this.lastCommand);
}
protected void ExpectSuccess()
{
int c = SafeReadByte();
if (c == -1)
throw CreateResponseError("No more data");
var s = ReadLine();
Log((char)c + s);
if (c == '-')
throw CreateResponseError(s.StartsWith("ERR") && s.Length >= 4 ? s.Substring(4) : s);
}
private void ExpectWord(string word)
{
int c = SafeReadByte();
if (c == -1)
throw CreateResponseError("No more data");
var s = ReadLine();
Log((char)c + s);
if (c == '-')
throw CreateResponseError(s.StartsWith("ERR") ? s.Substring(4) : s);
if (s != word)
throw CreateResponseError(string.Format("Expected '{0}' got '{1}'", word, s));
}
private string ExpectCode()
{
int c = SafeReadByte();
if (c == -1)
throw CreateResponseError("No more data");
var s = ReadLine();
Log((char)c + s);
if (c == '-')
throw CreateResponseError(s.StartsWith("ERR") ? s.Substring(4) : s);
return s;
}
internal void ExpectOk()
{
ExpectWord("OK");
}
internal void ExpectQueued()
{
ExpectWord("QUEUED");
}
public long ReadInt()
{
int c = SafeReadByte();
if (c == -1)
throw CreateResponseError("No more data");
var s = ReadLine();
Log("R: {0}", s);
if (c == '-')
throw CreateResponseError(s.StartsWith("ERR") ? s.Substring(4) : s);
if (c == ':' || c == '$')//really strange why ZRANK needs the '$' here
{
int i;
if (int.TryParse(s, out i))
return i;
}
throw CreateResponseError("Unknown reply on integer response: " + c + s);
}
public long ReadLong()
{
int c = SafeReadByte();
if (c == -1)
throw CreateResponseError("No more data");
var s = ReadLine();
Log("R: {0}", s);
if (c == '-')
throw CreateResponseError(s.StartsWith("ERR") ? s.Substring(4) : s);
if (c == ':' || c == '$')//really strange why ZRANK needs the '$' here
{
long i;
if (long.TryParse(s, out i))
return i;
}
throw CreateResponseError("Unknown reply on integer response: " + c + s);
}
private byte[] ReadData()
{
var r = ReadLine();
return ParseSingleLine(r);
}
private byte[] ParseSingleLine(string r)
{
Log("R: {0}", r);
if (r.Length == 0)
throw CreateResponseError("Zero length respose");
char c = r[0];
if (c == '-')
throw CreateResponseError(r.StartsWith("-ERR") ? r.Substring(5) : r.Substring(1));
if (c == '$')
{
if (r == "$-1")
return null;
int count;
if (Int32.TryParse(r.Substring(1), out count))
{
var retbuf = new byte[count];
var offset = 0;
while (count > 0)
{
var readCount = Bstream.Read(retbuf, offset, count);
if (readCount <= 0)
throw CreateResponseError("Unexpected end of Stream");
offset += readCount;
count -= readCount;
}
if (Bstream.ReadByte() != '\r' || Bstream.ReadByte() != '\n')
throw CreateResponseError("Invalid termination");
return retbuf;
}
throw CreateResponseError("Invalid length");
}
if (c == ':')
{
//match the return value
return r.Substring(1).ToUtf8Bytes();
}
throw CreateResponseError("Unexpected reply: " + r);
}
private byte[][] ReadMultiData()
{
int c = SafeReadByte();
if (c == -1)
throw CreateResponseError("No more data");
var s = ReadLine();
Log("R: {0}", s);
switch (c)
{
// Some commands like BRPOPLPUSH may return Bulk Reply instead of Multi-bulk
case '$':
var t = new byte[2][];
t[1] = ParseSingleLine(string.Concat(char.ToString((char)c), s));
return t;
case '-':
throw CreateResponseError(s.StartsWith("ERR") ? s.Substring(4) : s);
case '*':
int count;
if (int.TryParse(s, out count))
{
if (count == -1)
{
//redis is in an invalid state
return new byte[0][];
}
var result = new byte[count][];
for (int i = 0; i < count; i++)
result[i] = ReadData();
return result;
}
break;
}
throw CreateResponseError("Unknown reply on multi-request: " + c + s);
}
private object[] ReadDeeplyNestedMultiData()
{
return (object[])ReadDeeplyNestedMultiDataItem();
}
private object ReadDeeplyNestedMultiDataItem()
{
int c = SafeReadByte();
if (c == -1)
throw CreateResponseError("No more data");
var s = ReadLine();
Log("R: {0}", s);
switch (c)
{
case '$':
return ParseSingleLine(string.Concat(char.ToString((char)c), s));
case '-':
throw CreateResponseError(s.StartsWith("ERR") ? s.Substring(4) : s);
case '*':
int count;
if (int.TryParse(s, out count))
{
var array = new object[count];
for (int i = 0; i < count; i++)
{
array[i] = ReadDeeplyNestedMultiDataItem();
}
return array;
}
break;
default:
return s;
}
throw CreateResponseError("Unknown reply on multi-request: " + c + s);
}
internal int ReadMultiDataResultCount()
{
int c = SafeReadByte();
if (c == -1)
throw CreateResponseError("No more data");
var s = ReadLine();
Log("R: {0}", s);
if (c == '-')
throw CreateResponseError(s.StartsWith("ERR") ? s.Substring(4) : s);
if (c == '*')
{
int count;
if (int.TryParse(s, out count))
{
return count;
}
}
throw CreateResponseError("Unknown reply on multi-request: " + c + s);
}
private static void AssertListIdAndValue(string listId, byte[] value)
{
if (listId == null)
throw new ArgumentNullException("listId");
if (value == null)
throw new ArgumentNullException("value");
}
private static byte[][] MergeCommandWithKeysAndValues(byte[] cmd, byte[][] keys, byte[][] values)
{
var firstParams = new[] { cmd };
return MergeCommandWithKeysAndValues(firstParams, keys, values);
}
private static byte[][] MergeCommandWithKeysAndValues(byte[] cmd, byte[] firstArg, byte[][] keys, byte[][] values)
{
var firstParams = new[] { cmd, firstArg };
return MergeCommandWithKeysAndValues(firstParams, keys, values);
}
private static byte[][] MergeCommandWithKeysAndValues(byte[][] firstParams,
byte[][] keys, byte[][] values)
{
if (keys == null || keys.Length == 0)
throw new ArgumentNullException("keys");
if (values == null || values.Length == 0)
throw new ArgumentNullException("values");
if (keys.Length != values.Length)
throw new ArgumentException("The number of values must be equal to the number of keys");
var keyValueStartIndex = (firstParams != null) ? firstParams.Length : 0;
var keysAndValuesLength = keys.Length * 2 + keyValueStartIndex;
var keysAndValues = new byte[keysAndValuesLength][];
for (var i = 0; i < keyValueStartIndex; i++)
{
keysAndValues[i] = firstParams[i];
}
var j = 0;
for (var i = keyValueStartIndex; i < keysAndValuesLength; i += 2)
{
keysAndValues[i] = keys[j];
keysAndValues[i + 1] = values[j];
j++;
}
return keysAndValues;
}
private static byte[][] MergeCommandWithArgs(byte[] cmd, params string[] args)
{
var byteArgs = args.ToMultiByteArray();
return MergeCommandWithArgs(cmd, byteArgs);
}
private static byte[][] MergeCommandWithArgs(byte[] cmd, params byte[][] args)
{
var mergedBytes = new byte[1 + args.Length][];
mergedBytes[0] = cmd;
for (var i = 0; i < args.Length; i++)
{
mergedBytes[i + 1] = args[i];
}
return mergedBytes;
}
private static byte[][] MergeCommandWithArgs(byte[] cmd, byte[] firstArg, params byte[][] args)
{
var mergedBytes = new byte[2 + args.Length][];
mergedBytes[0] = cmd;
mergedBytes[1] = firstArg;
for (var i = 0; i < args.Length; i++)
{
mergedBytes[i + 2] = args[i];
}
return mergedBytes;
}
protected byte[][] ConvertToBytes(string[] keys)
{
var keyBytes = new byte[keys.Length][];
for (var i = 0; i < keys.Length; i++)
{
var key = keys[i];
keyBytes[i] = key != null ? key.ToUtf8Bytes() : new byte[0];
}
return keyBytes;
}
protected byte[][] MergeAndConvertToBytes(string[] keys, string[] args)
{
if (keys == null)
keys = new string[0];
if (args == null)
args = new string[0];
var keysLength = keys.Length;
var merged = new string[keysLength + args.Length];
for (var i = 0; i < merged.Length; i++)
{
merged[i] = i < keysLength ? keys[i] : args[i - keysLength];
}
return ConvertToBytes(merged);
}
public long EvalInt(string luaBody, int numberKeysInArgs, params byte[][] keys)
{
if (luaBody == null)
throw new ArgumentNullException("luaBody");
var cmdArgs = MergeCommandWithArgs(Commands.Eval, luaBody.ToUtf8Bytes(), keys.PrependInt(numberKeysInArgs));
return SendExpectLong(cmdArgs);
}
public long EvalShaInt(string sha1, int numberKeysInArgs, params byte[][] keys)
{
if (sha1 == null)
throw new ArgumentNullException("sha1");
var cmdArgs = MergeCommandWithArgs(Commands.EvalSha, sha1.ToUtf8Bytes(), keys.PrependInt(numberKeysInArgs));
return SendExpectLong(cmdArgs);
}
public string EvalStr(string luaBody, int numberKeysInArgs, params byte[][] keys)
{
if (luaBody == null)
throw new ArgumentNullException("luaBody");
var cmdArgs = MergeCommandWithArgs(Commands.Eval, luaBody.ToUtf8Bytes(), keys.PrependInt(numberKeysInArgs));
return SendExpectData(cmdArgs).FromUtf8Bytes();
}
public string EvalShaStr(string sha1, int numberKeysInArgs, params byte[][] keys)
{
if (sha1 == null)
throw new ArgumentNullException("sha1");
var cmdArgs = MergeCommandWithArgs(Commands.EvalSha, sha1.ToUtf8Bytes(), keys.PrependInt(numberKeysInArgs));
return SendExpectData(cmdArgs).FromUtf8Bytes();
}
public byte[][] Eval(string luaBody, int numberKeysInArgs, params byte[][] keys)
{
if (luaBody == null)
throw new ArgumentNullException("luaBody");
var cmdArgs = MergeCommandWithArgs(Commands.Eval, luaBody.ToUtf8Bytes(), keys.PrependInt(numberKeysInArgs));
return SendExpectMultiData(cmdArgs);
}
public byte[][] EvalSha(string sha1, int numberKeysInArgs, params byte[][] keys)
{
if (sha1 == null)
throw new ArgumentNullException("sha1");
var cmdArgs = MergeCommandWithArgs(Commands.EvalSha, sha1.ToUtf8Bytes(), keys.PrependInt(numberKeysInArgs));
return SendExpectMultiData(cmdArgs);
}
public string CalculateSha1(string luaBody)
{
if (luaBody == null)
throw new ArgumentNullException("luaBody");
byte[] buffer = Encoding.UTF8.GetBytes(luaBody);
var cryptoTransformSHA1 = new SHA1CryptoServiceProvider();
return BitConverter.ToString(cryptoTransformSHA1.ComputeHash(buffer)).Replace("-", "");
}
public byte[] ScriptLoad(string luaBody)
{
if (luaBody == null)
throw new ArgumentNullException("luaBody");
var cmdArgs = MergeCommandWithArgs(Commands.Script, Commands.Load, luaBody.ToUtf8Bytes());
return SendExpectData(cmdArgs);
}
public byte[][] ScriptExists(params byte[][] sha1Refs)
{
var keysAndValues = MergeCommandWithArgs(Commands.Script, Commands.Exists, sha1Refs);
return SendExpectMultiData(keysAndValues);
}
public void ScriptFlush()
{
SendExpectSuccess(Commands.Script, Commands.Flush);
}
public void ScriptKill()
{
SendExpectSuccess(Commands.Script, Commands.Kill);
}
}
}
| |
/* ****************************************************************************
*
* 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.
*
*
* ***************************************************************************/
#if FEATURE_CORE_DLR
using System.Linq.Expressions;
#else
using Microsoft.Scripting.Ast;
#endif
#if CLR45
using System.Collections.ObjectModel;
#endif
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
namespace Microsoft.Scripting.Actions {
/// <summary>
/// A TypeCollision is used when we have a collision between
/// two types with the same name. Currently this is only possible w/ generic
/// methods that should logically have arity as a portion of their name. For eg:
/// System.EventHandler and System.EventHandler[T]
/// System.Nullable and System.Nullable[T]
/// System.IComparable and System.IComparable[T]
///
/// The TypeCollision provides an indexer but also is a real type. When used
/// as a real type it is the non-generic form of the type.
///
/// The indexer allows the user to disambiguate between the generic and
/// non-generic versions. Therefore users must always provide additional
/// information to get the generic version.
/// </summary>
public sealed class TypeGroup : TypeTracker {
private readonly Dictionary<int, Type> _typesByArity;
private readonly string _name;
private TypeGroup(Type t1, int arity1, Type t2, int arity2) {
// TODO: types of different arities might be inherited, but we don't support that yet:
Debug.Assert(t1.DeclaringType == t2.DeclaringType);
Debug.Assert(arity1 != arity2);
_typesByArity = new Dictionary<int, Type>();
_typesByArity[arity1] = t1;
_typesByArity[arity2] = t2;
_name = ReflectionUtils.GetNormalizedTypeName(t1);
Debug.Assert(_name == ReflectionUtils.GetNormalizedTypeName(t2));
}
private TypeGroup(Type t1, TypeGroup existingTypes) {
// TODO: types of different arities might be inherited, but we don't support that yet:
Debug.Assert(t1.DeclaringType == existingTypes.DeclaringType);
Debug.Assert(ReflectionUtils.GetNormalizedTypeName(t1) == existingTypes.Name);
_typesByArity = new Dictionary<int, Type>(existingTypes._typesByArity);
_typesByArity[GetGenericArity(t1)] = t1;
_name = existingTypes.Name;
}
public override string ToString() {
StringBuilder repr = new StringBuilder(base.ToString());
repr.Append(":" + Name + "(");
bool pastFirstType = false;
foreach (Type type in Types) {
if (pastFirstType) {
repr.Append(", ");
}
repr.Append(type.Name);
pastFirstType = true;
}
repr.Append(")");
return repr.ToString();
}
public override IList<string> GetMemberNames() {
HashSet<string> members = new HashSet<string>();
foreach (Type type in this.Types) {
GetMemberNames(type, members);
}
return members.ToArray();
}
public TypeTracker GetTypeForArity(int arity) {
Type typeWithMatchingArity;
if (!_typesByArity.TryGetValue(arity, out typeWithMatchingArity)) {
return null;
}
return TypeTracker.GetTypeTracker(typeWithMatchingArity);
}
/// <param name="existingTypeEntity">The merged list so far. Could be null</param>
/// <param name="newType">The new type(s) to add to the merged list</param>
/// <returns>The merged list. Could be a TypeTracker or TypeGroup</returns>
public static TypeTracker UpdateTypeEntity(TypeTracker existingTypeEntity, TypeTracker newType) {
Debug.Assert(newType != null);
Debug.Assert(existingTypeEntity == null || (existingTypeEntity is NestedTypeTracker) || (existingTypeEntity is TypeGroup));
if (existingTypeEntity == null) {
return newType;
}
NestedTypeTracker existingType = existingTypeEntity as NestedTypeTracker;
TypeGroup existingTypeCollision = existingTypeEntity as TypeGroup;
if (existingType != null) {
int existingArity = GetGenericArity(existingType.Type);
int newArity = GetGenericArity(newType.Type);
if (existingArity == newArity) {
return newType;
}
return new TypeGroup(existingType.Type, existingArity, newType.Type, newArity);
}
return new TypeGroup(newType.Type, existingTypeCollision);
}
/// <summary> Gets the arity of generic parameters</summary>
private static int GetGenericArity(Type type) {
if (!type.IsGenericType()) {
return 0;
}
Debug.Assert(type.IsGenericTypeDefinition());
return type.GetGenericArguments().Length;
}
/// <exception cref="TypeLoadException">No non-generic type is represented by this group.</exception>
public Type GetNonGenericType() {
Type nonGenericType;
if (TryGetNonGenericType(out nonGenericType)) {
return nonGenericType;
}
throw Error.NonGenericWithGenericGroup(Name);
}
public bool TryGetNonGenericType(out Type nonGenericType) {
return _typesByArity.TryGetValue(0, out nonGenericType);
}
private Type SampleType {
get {
IEnumerator<Type> e = Types.GetEnumerator();
e.MoveNext();
return e.Current;
}
}
public IEnumerable<Type> Types {
get {
return _typesByArity.Values;
}
}
public IDictionary<int, Type> TypesByArity {
get {
return new ReadOnlyDictionary<int, Type>(_typesByArity);
}
}
#region MemberTracker overrides
public override TrackerTypes MemberType {
get {
return TrackerTypes.TypeGroup;
}
}
/// <summary>
/// This returns the DeclaringType of all the types in the TypeGroup
/// </summary>
public override Type DeclaringType {
get {
return SampleType.DeclaringType;
}
}
/// <summary>
/// This returns the base name of the TypeGroup (the name shared by all types minus arity)
/// </summary>
public override string Name {
get {
return _name;
}
}
/// <summary>
/// This will return the result only for the non-generic type if one exists, and will throw
/// an exception if all types in the TypeGroup are generic
/// </summary>
public override Type Type {
get { return GetNonGenericType(); }
}
public override bool IsGenericType {
get { return _typesByArity.Count > 0; }
}
/// <summary>
/// This will return the result only for the non-generic type if one exists, and will throw
/// an exception if all types in the TypeGroup are generic
/// </summary>
public override bool IsPublic {
get { return GetNonGenericType().IsPublic(); }
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using Orleans.Configuration;
using System.Threading.Tasks;
using System.Threading;
using Microsoft.Extensions.Options;
using System.Linq;
namespace Orleans.Runtime.MembershipService
{
/// <summary>
/// Responsible for updating membership table with details about the local silo.
/// </summary>
internal class MembershipAgent : ILifecycleParticipant<ISiloLifecycle>, IDisposable, MembershipAgent.ITestAccessor
{
private readonly CancellationTokenSource cancellation = new CancellationTokenSource();
private readonly MembershipTableManager tableManager;
private readonly ClusterHealthMonitor clusterHealthMonitor;
private readonly ILocalSiloDetails localSilo;
private readonly IFatalErrorHandler fatalErrorHandler;
private readonly ClusterMembershipOptions clusterMembershipOptions;
private readonly ILogger<MembershipAgent> log;
private readonly IAsyncTimer iAmAliveTimer;
private Func<DateTime> getUtcDateTime = () => DateTime.UtcNow;
public MembershipAgent(
MembershipTableManager tableManager,
ClusterHealthMonitor clusterHealthMonitor,
ILocalSiloDetails localSilo,
IFatalErrorHandler fatalErrorHandler,
IOptions<ClusterMembershipOptions> options,
ILogger<MembershipAgent> log,
IAsyncTimerFactory timerFactory)
{
this.tableManager = tableManager;
this.clusterHealthMonitor = clusterHealthMonitor;
this.localSilo = localSilo;
this.fatalErrorHandler = fatalErrorHandler;
this.clusterMembershipOptions = options.Value;
this.log = log;
this.iAmAliveTimer = timerFactory.Create(
this.clusterMembershipOptions.IAmAliveTablePublishTimeout,
nameof(UpdateIAmAlive));
}
internal interface ITestAccessor
{
Action OnUpdateIAmAlive { get; set; }
Func<DateTime> GetDateTime { get; set; }
}
Action ITestAccessor.OnUpdateIAmAlive { get; set; }
Func<DateTime> ITestAccessor.GetDateTime { get => this.getUtcDateTime; set => this.getUtcDateTime = value ?? throw new ArgumentNullException(nameof(value)); }
private async Task UpdateIAmAlive()
{
if (this.log.IsEnabled(LogLevel.Debug)) this.log.LogDebug("Starting periodic membership liveness timestamp updates");
try
{
TimeSpan? onceOffDelay = default;
while (await this.iAmAliveTimer.NextTick(onceOffDelay) && !this.tableManager.CurrentStatus.IsTerminating())
{
onceOffDelay = default;
try
{
var stopwatch = ValueStopwatch.StartNew();
((ITestAccessor)this).OnUpdateIAmAlive?.Invoke();
await this.tableManager.UpdateIAmAlive();
if (this.log.IsEnabled(LogLevel.Trace)) this.log.LogTrace("Updating IAmAlive took {Elapsed}", stopwatch.Elapsed);
}
catch (Exception exception)
{
this.log.LogError(
(int)ErrorCode.MembershipUpdateIAmAliveFailure,
"Failed to update table entry for this silo, will retry shortly: {Exception}",
exception);
// Retry quickly
onceOffDelay = TimeSpan.FromMilliseconds(200);
}
}
}
catch (Exception exception) when (this.fatalErrorHandler.IsUnexpected(exception))
{
this.log.LogError("Error updating liveness timestamp: {Exception}", exception);
this.fatalErrorHandler.OnFatalException(this, nameof(UpdateIAmAlive), exception);
}
finally
{
if (this.log.IsEnabled(LogLevel.Debug)) this.log.LogDebug("Stopping periodic membership liveness timestamp updates");
}
}
private async Task BecomeActive()
{
this.log.LogInformation(
(int)ErrorCode.MembershipBecomeActive,
"-BecomeActive");
if (this.clusterMembershipOptions.ValidateInitialConnectivity)
{
await this.ValidateInitialConnectivity();
}
else
{
this.log.LogWarning(
(int)ErrorCode.MembershipSendingPreJoinPing,
$"{nameof(ClusterMembershipOptions)}.{nameof(ClusterMembershipOptions.ValidateInitialConnectivity)} is set to false. This is NOT recommended for a production environment.");
}
try
{
await this.UpdateStatus(SiloStatus.Active);
this.log.LogInformation(
(int)ErrorCode.MembershipFinishBecomeActive,
"-Finished BecomeActive.");
}
catch (Exception exception)
{
this.log.LogInformation(
(int)ErrorCode.MembershipFailedToBecomeActive,
"BecomeActive failed: {Exception}",
exception);
throw;
}
}
private async Task ValidateInitialConnectivity()
{
// Continue attempting to validate connectivity until some reasonable timeout.
var maxAttemptTime = this.clusterMembershipOptions.ProbeTimeout.Multiply(5 * this.clusterMembershipOptions.NumMissedProbesLimit);
var attemptNumber = 1;
var now = this.getUtcDateTime();
var attemptUntil = now + maxAttemptTime;
var canContinue = true;
while (true)
{
try
{
var activeSilos = new List<SiloAddress>();
foreach (var item in this.tableManager.MembershipTableSnapshot.Entries)
{
var entry = item.Value;
if (entry.Status != SiloStatus.Active) continue;
if (entry.SiloAddress.IsSameLogicalSilo(this.localSilo.SiloAddress)) continue;
if (entry.HasMissedIAmAlivesSince(this.clusterMembershipOptions, now) != default) continue;
activeSilos.Add(entry.SiloAddress);
}
var failedSilos = await this.clusterHealthMonitor.CheckClusterConnectivity(activeSilos.ToArray());
var successfulSilos = activeSilos.Where(s => !failedSilos.Contains(s)).ToList();
// If there were no failures, terminate the loop and return without error.
if (failedSilos.Count == 0) break;
this.log.LogError(
(int)ErrorCode.MembershipJoiningPreconditionFailure,
"Failed to get ping responses from {FailedCount} of {ActiveCount} active silos. "
+ "Newly joining silos validate connectivity with all active silos that have recently updated their 'I Am Alive' value before joining the cluster. "
+ "Successfully contacted: {SuccessfulSilos}. Silos which did not respond successfully are: {FailedSilos}. "
+ "Will continue attempting to validate connectivity until {Timeout}. Attempt #{Attempt}",
failedSilos.Count,
activeSilos.Count,
Utils.EnumerableToString(successfulSilos),
Utils.EnumerableToString(failedSilos),
attemptUntil,
attemptNumber);
if (now + TimeSpan.FromSeconds(5) > attemptUntil)
{
canContinue = false;
var msg = $"Failed to get ping responses from {failedSilos.Count} of {activeSilos.Count} active silos. "
+ "Newly joining silos validate connectivity with all active silos that have recently updated their 'I Am Alive' value before joining the cluster. "
+ $"Successfully contacted: {Utils.EnumerableToString(successfulSilos)}. Failed to get response from: {Utils.EnumerableToString(failedSilos)}";
throw new OrleansClusterConnectivityCheckFailedException(msg);
}
// Refresh membership after some delay and retry.
await Task.Delay(TimeSpan.FromSeconds(5));
await this.tableManager.Refresh();
}
catch (Exception exception) when (canContinue)
{
this.log.LogError("Failed to validate initial cluster connectivity: {Exception}", exception);
await Task.Delay(TimeSpan.FromSeconds(1));
}
++attemptNumber;
now = this.getUtcDateTime();
}
}
private async Task BecomeJoining()
{
this.log.Info(ErrorCode.MembershipJoining, "-Joining");
try
{
await this.UpdateStatus(SiloStatus.Joining);
}
catch (Exception exc)
{
this.log.Error(ErrorCode.MembershipFailedToJoin, "Error updating status to Joining", exc);
throw;
}
}
private async Task BecomeShuttingDown()
{
this.log.Info(ErrorCode.MembershipShutDown, "-Shutdown");
try
{
await this.UpdateStatus(SiloStatus.ShuttingDown);
}
catch (Exception exc)
{
this.log.Error(ErrorCode.MembershipFailedToShutdown, "Error updating status to ShuttingDown", exc);
throw;
}
}
private async Task BecomeStopping()
{
log.Info(ErrorCode.MembershipStop, "-Stop");
try
{
await this.UpdateStatus(SiloStatus.Stopping);
}
catch (Exception exc)
{
log.Error(ErrorCode.MembershipFailedToStop, "Error updating status to Stopping", exc);
throw;
}
}
private async Task BecomeDead()
{
this.log.LogInformation(
(int)ErrorCode.MembershipKillMyself,
"Updating status to Dead");
try
{
await this.UpdateStatus(SiloStatus.Dead);
}
catch (Exception exception)
{
this.log.LogError(
(int)ErrorCode.MembershipFailedToKillMyself,
"Failure updating status to " + nameof(SiloStatus.Dead) + ": {Exception}",
exception);
throw;
}
}
private async Task UpdateStatus(SiloStatus status)
{
await this.tableManager.UpdateStatus(status);
}
void ILifecycleParticipant<ISiloLifecycle>.Participate(ISiloLifecycle lifecycle)
{
{
Task OnRuntimeInitializeStart(CancellationToken ct)
{
return Task.CompletedTask;
}
async Task OnRuntimeInitializeStop(CancellationToken ct)
{
this.iAmAliveTimer.Dispose();
this.cancellation.Cancel();
await Task.WhenAny(
Task.Run(() => this.BecomeDead()),
Task.Delay(TimeSpan.FromMinutes(1)));
}
lifecycle.Subscribe(
nameof(MembershipAgent),
ServiceLifecycleStage.RuntimeInitialize,
OnRuntimeInitializeStart,
OnRuntimeInitializeStop);
}
{
async Task AfterRuntimeGrainServicesStart(CancellationToken ct)
{
await Task.Run(() => this.BecomeJoining());
}
Task AfterRuntimeGrainServicesStop(CancellationToken ct) => Task.CompletedTask;
lifecycle.Subscribe(
nameof(MembershipAgent),
ServiceLifecycleStage.AfterRuntimeGrainServices,
AfterRuntimeGrainServicesStart,
AfterRuntimeGrainServicesStop);
}
{
var tasks = new List<Task>();
async Task OnBecomeActiveStart(CancellationToken ct)
{
await Task.Run(() => this.BecomeActive());
tasks.Add(Task.Run(() => this.UpdateIAmAlive()));
}
async Task OnBecomeActiveStop(CancellationToken ct)
{
this.iAmAliveTimer.Dispose();
this.cancellation.Cancel(throwOnFirstException: false);
var cancellationTask = ct.WhenCancelled();
if (ct.IsCancellationRequested)
{
await Task.Run(() => this.BecomeStopping());
}
else
{
var task = await Task.WhenAny(cancellationTask, this.BecomeShuttingDown());
if (ReferenceEquals(task, cancellationTask))
{
this.log.LogWarning("Graceful shutdown aborted: starting ungraceful shutdown");
await Task.Run(() => this.BecomeStopping());
}
else
{
await Task.WhenAny(cancellationTask, Task.WhenAll(tasks));
}
}
}
lifecycle.Subscribe(
nameof(MembershipAgent),
ServiceLifecycleStage.BecomeActive,
OnBecomeActiveStart,
OnBecomeActiveStop);
}
}
public void Dispose()
{
this.iAmAliveTimer.Dispose();
}
}
}
| |
/*
* Copyright (C) 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.
*/
#if UNITY_ANDROID
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using GooglePlayGames.BasicApi;
using GooglePlayGames.OurUtils;
using GooglePlayGames.BasicApi.Multiplayer;
namespace GooglePlayGames.Android {
public class AndroidClient : IPlayGamesClient {
GameHelperManager mGHManager = null;
// In what state of the authentication process are we?
enum AuthState {
NoAuth, // not authenticated
AuthPending, // we want to authenticate, but GameHelper is busy
InProgress, // we are authenticating
LoadingAchs, // we are signed in and are doing the initial achievement load
Done // we are authenticated!
};
AuthState mAuthState = AuthState.NoAuth;
// are we trying silent authentication? If so, then we can't show UIs in the process:
// we have to fail instead
bool mSilentAuth = false;
// user's ID and display name (retrieved on sign in)
string mUserId = null, mUserDisplayName = null;
// the auth callback that we have to call at the end of the auth process
System.Action<bool> mAuthCallback = null;
// the achievements we've loaded
AchievementBank mAchievementBank = new AchievementBank();
// Sometimes we have to execute an action on the UI thread involving GamesClient,
// but we might hit that unlucky moment when GamesClient is still in the process
// of connecting and can't take API calls. So, if that happens, we queue the
// actions here and execute when we get onSignInSucceeded or onSignInFailed
List<Action> mActionsPendingSignIn = new List<Action>();
// Are we currently in the process of signing out?
private bool mSignOutInProgress = false;
// Result code for child activities whose result we don't care about
const int RC_UNUSED = 9999;
// RTMP client and TBMP clients
AndroidRtmpClient mRtmpClient;
AndroidTbmpClient mTbmpClient;
// invitation delegate
InvitationReceivedDelegate mInvitationDelegate = null;
// have we installed an invitation listener?
bool mRegisteredInvitationListener = false;
// the invitation we received via notification. We store it here while we don't have
// an invitation delegate to deliver it to; when we get one, we deliver it and forget it.
Invitation mInvitationFromNotification = null;
public AndroidClient() {
mRtmpClient = new AndroidRtmpClient(this);
mTbmpClient = new AndroidTbmpClient(this);
RunOnUiThread(() => {
Logger.d("Initializing Android Client.");
Logger.d("Creating GameHelperManager to manage GameHelper.");
mGHManager = new GameHelperManager(this);
// make sure that when game stops, we clean up the real time multiplayer room
mGHManager.AddOnStopDelegate(mRtmpClient.OnStop);
});
// now we wait for the result of the initial auth, which will trigger
// a call to either OnSignInSucceeded or OnSignInFailed
}
// called from game thread
public void Authenticate(System.Action<bool> callback, bool silent) {
if (mAuthState != AuthState.NoAuth) {
Logger.w("Authenticate() called while an authentication process was active. " +
mAuthState);
mAuthCallback = callback;
return;
}
// make sure the helper GameObject is ready (we use it for the auth callback)
Logger.d("Making sure PlayGamesHelperObject is ready.");
PlayGamesHelperObject.CreateObject();
Logger.d("PlayGamesHelperObject created.");
mSilentAuth = silent;
Logger.d("AUTH: starting auth process, silent=" + mSilentAuth);
RunOnUiThread(() => {
switch (mGHManager.State) {
case GameHelperManager.ConnectionState.Connected:
Logger.d("AUTH: already connected! Proceeding to achievement load phase.");
mAuthCallback = callback;
DoInitialAchievementLoad();
break;
case GameHelperManager.ConnectionState.Connecting:
Logger.d("AUTH: connection in progress; auth now pending.");
mAuthCallback = callback;
mAuthState = AuthState.AuthPending;
// we'll do the right thing in OnSignInSucceeded/Failed
break;
default:
mAuthCallback = callback;
if (mSilentAuth) {
Logger.d("AUTH: not connected and silent=true, so failing.");
mAuthState = AuthState.NoAuth;
InvokeAuthCallback(false);
} else {
Logger.d("AUTH: not connected and silent=false, so starting flow.");
mAuthState = AuthState.InProgress;
mGHManager.BeginUserInitiatedSignIn();
// we'll do the right thing in OnSignInSucceeded/Failed
}
break;
}
});
}
// call from UI thread only!
private void DoInitialAchievementLoad() {
Logger.d("AUTH: Now performing initial achievement load...");
mAuthState = AuthState.LoadingAchs;
mGHManager.CallGmsApiWithResult("games.Games", "Achievements", "load",
new OnAchievementsLoadedResultProxy(this), false);
Logger.d("AUTH: Initial achievement load call made.");
}
// UI thread
private void OnAchievementsLoaded(int statusCode, AndroidJavaObject buffer) {
if (mAuthState == AuthState.LoadingAchs) {
Logger.d("AUTH: Initial achievement load finished.");
if (statusCode == JavaConsts.STATUS_OK ||
statusCode == JavaConsts.STATUS_STALE_DATA ||
statusCode == JavaConsts.STATUS_DEFERRED) {
// successful load (either from network or local cache)
Logger.d("Processing achievement buffer.");
mAchievementBank.ProcessBuffer(buffer);
Logger.d("Closing achievement buffer.");
buffer.Call("close");
Logger.d("AUTH: Auth process complete!");
mAuthState = AuthState.Done;
InvokeAuthCallback(true);
// inform the RTMP client and TBMP clients that sign in suceeded
CheckForConnectionExtras();
mRtmpClient.OnSignInSucceeded();
mTbmpClient.OnSignInSucceeded();
} else {
Logger.w("AUTH: Failed to load achievements, status code " + statusCode);
mAuthState = AuthState.NoAuth;
InvokeAuthCallback(false);
}
} else {
Logger.w("OnAchievementsLoaded called unexpectedly in auth state " + mAuthState);
}
}
// UI thread
private void InvokeAuthCallback(bool success) {
if (mAuthCallback == null) return;
Logger.d("AUTH: Calling auth callback: success=" + success);
System.Action<bool> cb = mAuthCallback;
mAuthCallback = null;
PlayGamesHelperObject.RunOnGameThread(() => {
cb.Invoke(success);
});
}
private void RetrieveUserInfo() {
Logger.d("Attempting to retrieve player info.");
using (AndroidJavaObject playerObj = mGHManager.CallGmsApi<AndroidJavaObject>(
"games.Games", "Players", "getCurrentPlayer")) {
if (mUserId == null) {
mUserId = playerObj.Call<string>("getPlayerId");
Logger.d("Player ID: " + mUserId);
}
if (mUserDisplayName == null) {
mUserDisplayName = playerObj.Call<string>("getDisplayName");
Logger.d("Player display name: " + mUserDisplayName);
}
}
}
// called (on the UI thread) by GameHelperManager to notify us that sign in succeeded
internal void OnSignInSucceeded() {
Logger.d("AndroidClient got OnSignInSucceeded.");
RetrieveUserInfo();
if (mAuthState == AuthState.AuthPending || mAuthState == AuthState.InProgress) {
Logger.d("AUTH: Auth succeeded. Proceeding to achievement loading.");
DoInitialAchievementLoad();
} else if (mAuthState == AuthState.LoadingAchs) {
Logger.w("AUTH: Got OnSignInSucceeded() while in achievement loading phase (unexpected).");
Logger.w("AUTH: Trying to fix by issuing a new achievement load call.");
DoInitialAchievementLoad();
} else {
// we will hit this case during the normal lifecycle (for example, Activity
// was brought to the foreground and sign in has succeeded even though
// we were not in an auth flow).
Logger.d("Normal lifecycle OnSignInSucceeded received.");
RunPendingActions();
// check for invitations that may have arrived via notification
CheckForConnectionExtras();
// inform the RTMP client that sign-in has suceeded
mRtmpClient.OnSignInSucceeded();
mTbmpClient.OnSignInSucceeded();
}
}
// called (on the UI thread) by GameHelperManager to notify us that sign in failed
internal void OnSignInFailed() {
Logger.d("AndroidClient got OnSignInFailed.");
if (mAuthState == AuthState.AuthPending) {
// we have yet to start the auth flow
if (mSilentAuth) {
Logger.d("AUTH: Auth flow was pending, but silent=true, so failing.");
mAuthState = AuthState.NoAuth;
InvokeAuthCallback(false);
} else {
Logger.d("AUTH: Auth flow was pending and silent=false, so doing noisy auth.");
mAuthState = AuthState.InProgress;
mGHManager.BeginUserInitiatedSignIn();
}
} else if (mAuthState == AuthState.InProgress) {
// authentication was in progress, but failed: notify callback
Logger.d("AUTH: FAILED!");
mAuthState = AuthState.NoAuth;
InvokeAuthCallback(false);
} else if (mAuthState == AuthState.LoadingAchs) {
// we were loading achievements and got disconnected: notify callback
Logger.d("AUTH: FAILED (while loading achievements).");
mAuthState = AuthState.NoAuth;
InvokeAuthCallback(false);
} else if (mAuthState == AuthState.NoAuth) {
// we will hit this case during the normal lifecycle (for example, Activity
// was brought to the foreground and sign in has failed).
Logger.d("Normal OnSignInFailed received.");
} else if (mAuthState == AuthState.Done) {
// we lost authentication (for example, the token might have expired,
// or the user revoked it)
Logger.e("Authentication has been lost!");
mAuthState = AuthState.NoAuth;
}
}
// Runs any actions pending in the mActionsPendingSignIn queue
private void RunPendingActions() {
if (mActionsPendingSignIn.Count > 0) {
Logger.d("Running pending actions on the UI thread.");
while (mActionsPendingSignIn.Count > 0) {
Action a = mActionsPendingSignIn[0];
mActionsPendingSignIn.RemoveAt(0);
a.Invoke();
}
Logger.d("Done running pending actions on the UI thread.");
} else {
Logger.d("No pending actions to run on UI thread.");
}
}
// runs on the game thread
public bool IsAuthenticated() {
return mAuthState == AuthState.Done && !mSignOutInProgress;
}
public void SignOut() {
Logger.d("AndroidClient.SignOut");
mSignOutInProgress = true;
RunWhenConnectionStable(() => {
Logger.d("Calling GHM.SignOut");
mGHManager.SignOut();
mAuthState = AuthState.NoAuth;
mSignOutInProgress = false;
Logger.d("Now signed out.");
});
}
// Returns the game's Activity
internal AndroidJavaObject GetActivity() {
using (AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) {
return jc.GetStatic<AndroidJavaObject>("currentActivity");
}
}
internal void RunOnUiThread(System.Action action) {
using (AndroidJavaObject activity = GetActivity()) {
activity.Call("runOnUiThread", new AndroidJavaRunnable(action));
}
}
private class OnAchievementsLoadedResultProxy : AndroidJavaProxy {
AndroidClient mOwner;
internal OnAchievementsLoadedResultProxy(AndroidClient c) :
base(JavaConsts.ResultCallbackClass) {
mOwner = c;
}
public void onResult(AndroidJavaObject result) {
Logger.d("OnAchievementsLoadedResultProxy invoked");
Logger.d(" result=" + result);
int statusCode = JavaUtil.GetStatusCode(result);
AndroidJavaObject achBuffer = JavaUtil.CallNullSafeObjectMethod(result,
"getAchievements");
mOwner.OnAchievementsLoaded(statusCode, achBuffer);
if (achBuffer != null) {
achBuffer.Dispose();
}
}
}
// Runs the given action on the UI thread when the state of the GameHelper connection
// becomes stable (i.e. not in the temporary lapse between Activity startup and
// connection). So when the action runs, we will either be definitely signed in,
// or have definitely failed to sign in.
private void RunWhenConnectionStable(Action a) {
RunOnUiThread(() => {
if (mGHManager.Paused || mGHManager.Connecting) {
// we're in the middle of establishing a connection, so we'll
// have to queue this action to execute once the connection is
// established (or fails)
Logger.d("Action scheduled for later (connection currently in progress).");
mActionsPendingSignIn.Add(a);
} else {
// connection is in a definite state, so we can run it right away
a.Invoke();
}
});
}
internal void CallClientApi(string desc, Action call, Action<bool> callback) {
Logger.d("Requesting API call: " + desc);
RunWhenConnectionStable(() => {
// we got a stable connection state to the games service
// (either connected or disconnected, but not in progress).
if (mGHManager.IsConnected()) {
// we are connected, so make the API call
Logger.d("Connected! Calling API: " + desc);
call.Invoke();
if (callback != null) {
PlayGamesHelperObject.RunOnGameThread(() => {
callback.Invoke(true);
});
}
} else {
// we are not connected, so fail the API call
Logger.w("Not connected! Failed to call API :" + desc);
if (callback != null) {
PlayGamesHelperObject.RunOnGameThread(() => {
callback.Invoke(false);
});
}
}
});
}
// called from game thread
public string GetUserId() {
return mUserId;
}
// called from game thread
public string GetUserDisplayName() {
return mUserDisplayName;
}
// called from game thread
public void UnlockAchievement(string achId, Action<bool> callback) {
// if the local cache says it's unlocked, we don't have to do anything
Logger.d("AndroidClient.UnlockAchievement: " + achId);
Achievement a = GetAchievement(achId);
if (a != null && a.IsUnlocked) {
Logger.d("...was already unlocked, so no-op.");
if (callback != null) {
callback.Invoke(true);
}
return;
}
CallClientApi("unlock ach " + achId, () => {
mGHManager.CallGmsApi("games.Games", "Achievements", "unlock", achId);
}, callback);
// update local cache
a = GetAchievement(achId);
if (a != null) {
a.IsUnlocked = a.IsRevealed = true;
}
}
// called from game thread
public void RevealAchievement(string achId, Action<bool> callback) {
Logger.d("AndroidClient.RevealAchievement: " + achId);
Achievement a = GetAchievement(achId);
if (a != null && a.IsRevealed) {
Logger.d("...was already revealed, so no-op.");
if (callback != null) {
callback.Invoke(true);
}
return;
}
CallClientApi("reveal ach " + achId, () => {
mGHManager.CallGmsApi("games.Games", "Achievements", "reveal", achId);
}, callback);
// update local cache
a = GetAchievement(achId);
if (a != null) {
a.IsRevealed = true;
}
}
// called from game thread
public void IncrementAchievement(string achId, int steps, Action<bool> callback) {
Logger.d("AndroidClient.IncrementAchievement: " + achId + ", steps " + steps);
CallClientApi("increment ach " + achId, () => {
mGHManager.CallGmsApi("games.Games", "Achievements", "increment",
achId, steps);
}, callback);
// update local cache
Achievement a = GetAchievement(achId);
if (a != null) {
a.CurrentSteps += steps;
if (a.CurrentSteps >= a.TotalSteps) {
a.CurrentSteps = a.TotalSteps;
}
}
}
// called from game thread
public List<Achievement> GetAchievements() {
return mAchievementBank.GetAchievements();
}
// called from game thread
public Achievement GetAchievement(string achId) {
return mAchievementBank.GetAchievement(achId);
}
// called from game thread
public void ShowAchievementsUI() {
Logger.d("AndroidClient.ShowAchievementsUI.");
CallClientApi("show achievements ui", () => {
using (AndroidJavaObject intent = mGHManager.CallGmsApi<AndroidJavaObject>(
"games.Games", "Achievements", "getAchievementsIntent")) {
using (AndroidJavaObject activity = GetActivity()) {
Logger.d("About to show achievements UI with intent " + intent +
", activity " + activity);
if (intent != null && activity != null) {
activity.Call("startActivityForResult", intent, RC_UNUSED);
}
}
}
}, null);
}
private AndroidJavaObject GetLeaderboardIntent(string lbId) {
return (lbId == null) ?
mGHManager.CallGmsApi<AndroidJavaObject>(
"games.Games", "Leaderboards", "getAllLeaderboardsIntent") :
mGHManager.CallGmsApi<AndroidJavaObject>(
"games.Games", "Leaderboards", "getLeaderboardIntent", lbId);
}
// called from game thread
public void ShowLeaderboardUI(string lbId) {
Logger.d("AndroidClient.ShowLeaderboardUI, lb=" + (lbId == null ? "(all)" : lbId));
CallClientApi("show LB ui", () => {
using (AndroidJavaObject intent = GetLeaderboardIntent(lbId)) {
using (AndroidJavaObject activity = GetActivity()) {
Logger.d("About to show LB UI with intent " + intent +
", activity " + activity);
if (intent != null && activity != null) {
activity.Call("startActivityForResult", intent, RC_UNUSED);
}
}
}
}, null);
}
// called from game thread
public void SubmitScore(string lbId, long score, Action<bool> callback) {
Logger.d("AndroidClient.SubmitScore, lb=" + lbId + ", score=" + score);
CallClientApi("submit score " + score + ", lb " + lbId, () => {
mGHManager.CallGmsApi("games.Games", "Leaderboards",
"submitScore", lbId, score);
}, callback);
}
// called from game thread
public void LoadState(int slot, OnStateLoadedListener listener) {
Logger.d("AndroidClient.LoadState, slot=" + slot);
CallClientApi("load state slot=" + slot, () => {
OnStateResultProxy proxy = new OnStateResultProxy(this, listener);
mGHManager.CallGmsApiWithResult("appstate.AppStateManager", null, "load",
proxy, slot);
}, null);
}
// called from game thread. This is ONLY called internally (OnStateLoadedProxy
// calls this). This is not part of the IPlayGamesClient interface.
internal void ResolveState(int slot, string resolvedVersion, byte[] resolvedData,
OnStateLoadedListener listener) {
Logger.d(string.Format("AndroidClient.ResolveState, slot={0}, ver={1}, " +
"data={2}", slot, resolvedVersion, resolvedData));
CallClientApi("resolve state slot=" + slot, () => {
mGHManager.CallGmsApiWithResult("appstate.AppStateManager", null, "resolve",
new OnStateResultProxy(this, listener), slot, resolvedVersion, resolvedData);
}, null);
}
// called from game thread
public void UpdateState(int slot, byte[] data, OnStateLoadedListener listener) {
Logger.d(string.Format("AndroidClient.UpdateState, slot={0}, data={1}",
slot, Logger.describe(data)));
CallClientApi("update state, slot=" + slot, () => {
mGHManager.CallGmsApi("appstate.AppStateManager", null, "update", slot, data);
}, null);
// On Android, cloud writes always succeeds (because, in the worst case,
// data gets cached locally to send to the cloud later)
listener.OnStateSaved(true, slot);
}
// called from game thread
public void SetCloudCacheEncrypter(BufferEncrypter encrypter) {
Logger.d("Ignoring cloud cache encrypter (not used in Android)");
// Not necessary in Android (since the library takes care of storing
// data locally)
}
// called from game thread
public void RegisterInvitationDelegate(InvitationReceivedDelegate deleg) {
Logger.d("AndroidClient.RegisterInvitationDelegate");
if (deleg == null) {
Logger.w("AndroidClient.RegisterInvitationDelegate called w/ null argument.");
return;
}
mInvitationDelegate = deleg;
// install invitation listener, if we don't have one yet
if (!mRegisteredInvitationListener) {
Logger.d("Registering an invitation listener.");
RegisterInvitationListener();
}
if (mInvitationFromNotification != null) {
Logger.d("Delivering pending invitation from notification now.");
Invitation inv = mInvitationFromNotification;
mInvitationFromNotification = null;
PlayGamesHelperObject.RunOnGameThread(() => {
if (mInvitationDelegate != null) {
mInvitationDelegate.Invoke(inv, true);
}
});
}
}
// called from game thread
public Invitation GetInvitationFromNotification() {
Logger.d("AndroidClient.GetInvitationFromNotification");
Logger.d("Returning invitation: " + ((mInvitationFromNotification == null) ?
"(null)" : mInvitationFromNotification.ToString()));
return mInvitationFromNotification;
}
// called from game thread
public bool HasInvitationFromNotification() {
bool has = mInvitationFromNotification != null;
Logger.d("AndroidClient.HasInvitationFromNotification, returning " + has);
return has;
}
private void RegisterInvitationListener() {
Logger.d("AndroidClient.RegisterInvitationListener");
CallClientApi("register invitation listener", () => {
mGHManager.CallGmsApi("games.Games", "Invitations",
"registerInvitationListener", new OnInvitationReceivedProxy(this));
}, null);
mRegisteredInvitationListener = true;
}
public IRealTimeMultiplayerClient GetRtmpClient() {
return mRtmpClient;
}
public ITurnBasedMultiplayerClient GetTbmpClient() {
return mTbmpClient;
}
internal GameHelperManager GHManager {
get {
return mGHManager;
}
}
internal void ClearInvitationIfFromNotification(string invitationId) {
Logger.d("AndroidClient.ClearInvitationIfFromNotification: " + invitationId);
if (mInvitationFromNotification != null &&
mInvitationFromNotification.InvitationId.Equals(invitationId)) {
Logger.d("Clearing invitation from notification: " + invitationId);
mInvitationFromNotification = null;
}
}
private void CheckForConnectionExtras() {
// check to see if we have a pending invitation in our gamehelper
Logger.d("AndroidClient: CheckInvitationFromNotification.");
Logger.d("AndroidClient: looking for invitation in our GameHelper.");
Invitation invFromNotif = null;
AndroidJavaObject invObj = mGHManager.GetInvitation();
AndroidJavaObject matchObj = mGHManager.GetTurnBasedMatch();
mGHManager.ClearInvitationAndTurnBasedMatch();
if (invObj != null) {
Logger.d("Found invitation in GameHelper. Converting.");
invFromNotif = ConvertInvitation(invObj);
Logger.d("Found invitation in our GameHelper: " + invFromNotif);
} else {
Logger.d("No invitation in our GameHelper. Trying SignInHelperManager.");
AndroidJavaClass cls = JavaUtil.GetClass(JavaConsts.SignInHelperManagerClass);
using (AndroidJavaObject inst = cls.CallStatic<AndroidJavaObject>("getInstance")) {
if (inst.Call<bool>("hasInvitation")) {
invFromNotif = ConvertInvitation(inst.Call<AndroidJavaObject>("getInvitation"));
Logger.d("Found invitation in SignInHelperManager: " + invFromNotif);
inst.Call("forgetInvitation");
} else {
Logger.d("No invitation in SignInHelperManager either.");
}
}
}
TurnBasedMatch match = null;
if (matchObj != null) {
Logger.d("Found match in GameHelper. Converting.");
match = JavaUtil.ConvertMatch(mUserId, matchObj);
Logger.d("Match from GameHelper: " + match);
} else {
Logger.d("No match in our GameHelper. Trying SignInHelperManager.");
AndroidJavaClass cls = JavaUtil.GetClass(JavaConsts.SignInHelperManagerClass);
using (AndroidJavaObject inst = cls.CallStatic<AndroidJavaObject>("getInstance")) {
if (inst.Call<bool>("hasTurnBasedMatch")) {
match = JavaUtil.ConvertMatch(mUserId,
inst.Call<AndroidJavaObject>("getTurnBasedMatch"));
Logger.d("Found match in SignInHelperManager: " + match);
inst.Call("forgetTurnBasedMatch");
} else {
Logger.d("No match in SignInHelperManager either.");
}
}
}
// if we got an invitation from the notification, invoke the delegate
if (invFromNotif != null) {
if (mInvitationDelegate != null) {
Logger.d("Invoking invitation received delegate to deal with invitation " +
" from notification.");
PlayGamesHelperObject.RunOnGameThread(() => {
if (mInvitationDelegate != null) {
mInvitationDelegate.Invoke(invFromNotif, true);
}
});
} else {
Logger.d("No delegate to handle invitation from notification; queueing.");
mInvitationFromNotification = invFromNotif;
}
}
// if we got a turn-based match, hand it over to the TBMP client who will know
// better what to do with it
if (match != null) {
mTbmpClient.HandleMatchFromNotification(match);
}
}
private Invitation ConvertInvitation(AndroidJavaObject invObj) {
Logger.d("Converting Android invitation to our Invitation object.");
string invitationId = invObj.Call<string>("getInvitationId");
int invType = invObj.Call<int>("getInvitationType");
Participant inviter;
using (AndroidJavaObject inviterObj = invObj.Call<AndroidJavaObject>("getInviter")) {
inviter = JavaUtil.ConvertParticipant(inviterObj);
}
int variant = invObj.Call<int>("getVariant");
Invitation.InvType type;
switch (invType) {
case JavaConsts.INVITATION_TYPE_REAL_TIME:
type = Invitation.InvType.RealTime;
break;
case JavaConsts.INVITATION_TYPE_TURN_BASED:
type = Invitation.InvType.TurnBased;
break;
default:
Logger.e("Unknown invitation type " + invType);
type = Invitation.InvType.Unknown;
break;
}
Invitation result = new Invitation(type, invitationId, inviter, variant);
Logger.d("Converted invitation: " + result.ToString());
return result;
}
private void OnInvitationReceived(AndroidJavaObject invitationObj) {
Logger.d("AndroidClient.OnInvitationReceived. Converting invitation...");
Invitation inv = ConvertInvitation(invitationObj);
Logger.d("Invitation: " + inv.ToString());
if (mInvitationDelegate != null) {
Logger.d("Delivering invitation to invitation received delegate.");
PlayGamesHelperObject.RunOnGameThread(() => {
if (mInvitationDelegate != null) {
mInvitationDelegate.Invoke(inv, false);
}
});
} else {
Logger.w("AndroidClient.OnInvitationReceived discarding invitation because " +
" delegate is null.");
}
}
private void OnInvitationRemoved(string invitationId) {
Logger.d("AndroidClient.OnInvitationRemoved: " + invitationId);
ClearInvitationIfFromNotification(invitationId);
}
private class OnInvitationReceivedProxy : AndroidJavaProxy {
AndroidClient mOwner;
internal OnInvitationReceivedProxy(AndroidClient owner)
: base(JavaConsts.OnInvitationReceivedListenerClass) {
mOwner = owner;
}
public void onInvitationReceived(AndroidJavaObject invitationObj) {
Logger.d("OnInvitationReceivedProxy.onInvitationReceived");
mOwner.OnInvitationReceived(invitationObj);
}
public void onInvitationRemoved(string invitationId) {
Logger.d("OnInvitationReceivedProxy.onInvitationRemoved");
mOwner.OnInvitationRemoved(invitationId);
}
}
public string PlayerId {
get {
return mUserId;
}
}
}
}
#endif
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ecs-2014-11-13.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ECS.Model
{
/// <summary>
/// Container definitions are used in task definitions to describe the different containers
/// that are launched as part of a task.
/// </summary>
public partial class ContainerDefinition
{
private List<string> _command = new List<string>();
private int? _cpu;
private List<string> _entryPoint = new List<string>();
private List<KeyValuePair> _environment = new List<KeyValuePair>();
private bool? _essential;
private string _image;
private List<string> _links = new List<string>();
private int? _memory;
private List<MountPoint> _mountPoints = new List<MountPoint>();
private string _name;
private List<PortMapping> _portMappings = new List<PortMapping>();
private List<VolumeFrom> _volumesFrom = new List<VolumeFrom>();
/// <summary>
/// Gets and sets the property Command.
/// <para>
/// The <code>CMD</code> that is passed to the container. For more information on the
/// Docker <code>CMD</code> parameter, see <a href="https://docs.docker.com/reference/builder/#cmd">https://docs.docker.com/reference/builder/#cmd</a>.
/// </para>
/// </summary>
public List<string> Command
{
get { return this._command; }
set { this._command = value; }
}
// Check to see if Command property is set
internal bool IsSetCommand()
{
return this._command != null && this._command.Count > 0;
}
/// <summary>
/// Gets and sets the property Cpu.
/// <para>
/// The number of <code>cpu</code> units reserved for the container. A container instance
/// has 1,024 <code>cpu</code> units for every CPU core. This parameter specifies the
/// minimum amount of CPU to reserve for a container, and containers share unallocated
/// CPU units with other containers on the instance with the same ratio as their allocated
/// amount.
/// </para>
///
/// <para>
/// For example, if you run a single-container task on a single-core instance type with
/// 512 CPU units specified for that container, and that is the only task running on the
/// container instance, that container could use the full 1,024 CPU unit share at any
/// given time. However, if you launched another copy of the same task on that container
/// instance, each task would be guaranteed a minimum of 512 CPU units when needed, and
/// each container could float to higher CPU usage if the other container was not using
/// it, but if both tasks were 100% active all of the time, they would be limited to 512
/// CPU units.
/// </para>
///
/// <para>
/// The Docker daemon on the container instance uses the CPU value to calculate the relative
/// CPU share ratios for running containers. For more information, see <a href="https://docs.docker.com/reference/run/#cpu-share-constraint">CPU
/// share constraint</a> in the Docker documentation. The minimum valid CPU share value
/// that the Linux kernel will allow is 2; however, the CPU parameter is not required,
/// and you can use CPU values below 2 in your container definitions. For CPU values below
/// 2 (including null), the behavior varies based on your Amazon ECS container agent version:
/// </para>
/// <ul> <li> <b>Agent versions less than or equal to 1.1.0:</b> Null and zero CPU values
/// are passed to Docker as 0, which Docker then converts to 1,024 CPU shares. CPU values
/// of 1 are passed to Docker as 1, which the Linux kernel converts to 2 CPU shares.</li>
/// <li> <b>Agent versions greater than or equal to 1.2.0:</b> Null, zero, and CPU values
/// of 1 are passed to Docker as 2.</li> </ul>
/// </summary>
public int Cpu
{
get { return this._cpu.GetValueOrDefault(); }
set { this._cpu = value; }
}
// Check to see if Cpu property is set
internal bool IsSetCpu()
{
return this._cpu.HasValue;
}
/// <summary>
/// Gets and sets the property EntryPoint. <important>
/// <para>
/// Early versions of the Amazon ECS container agent do not properly handle <code>entryPoint</code>
/// parameters. If you have problems using <code>entryPoint</code>, update your container
/// agent or enter your commands and arguments as <code>command</code> array items instead.
/// </para>
/// </important>
/// <para>
/// The <code>ENTRYPOINT</code> that is passed to the container. For more information
/// on the Docker <code>ENTRYPOINT</code> parameter, see <a href="https://docs.docker.com/reference/builder/#entrypoint">https://docs.docker.com/reference/builder/#entrypoint</a>.
/// </para>
/// </summary>
public List<string> EntryPoint
{
get { return this._entryPoint; }
set { this._entryPoint = value; }
}
// Check to see if EntryPoint property is set
internal bool IsSetEntryPoint()
{
return this._entryPoint != null && this._entryPoint.Count > 0;
}
/// <summary>
/// Gets and sets the property Environment.
/// <para>
/// The environment variables to pass to a container.
/// </para>
/// </summary>
public List<KeyValuePair> Environment
{
get { return this._environment; }
set { this._environment = value; }
}
// Check to see if Environment property is set
internal bool IsSetEnvironment()
{
return this._environment != null && this._environment.Count > 0;
}
/// <summary>
/// Gets and sets the property Essential.
/// <para>
/// If the <code>essential</code> parameter of a container is marked as <code>true</code>,
/// the failure of that container will stop the task. If the <code>essential</code> parameter
/// of a container is marked as <code>false</code>, then its failure will not affect the
/// rest of the containers in a task. If this parameter is omitted, a container is assumed
/// to be essential.
/// </para>
/// <note>
/// <para>
/// All tasks must have at least one essential container.
/// </para>
/// </note>
/// </summary>
public bool Essential
{
get { return this._essential.GetValueOrDefault(); }
set { this._essential = value; }
}
// Check to see if Essential property is set
internal bool IsSetEssential()
{
return this._essential.HasValue;
}
/// <summary>
/// Gets and sets the property Image.
/// <para>
/// The image used to start a container. This string is passed directly to the Docker
/// daemon. Images in the Docker Hub registry are available by default. Other repositories
/// are specified with <code><i>repository-url</i>/<i>image</i>:<i>tag</i></code>.
/// </para>
/// </summary>
public string Image
{
get { return this._image; }
set { this._image = value; }
}
// Check to see if Image property is set
internal bool IsSetImage()
{
return this._image != null;
}
/// <summary>
/// Gets and sets the property Links.
/// <para>
/// The <code>link</code> parameter allows containers to communicate with each other without
/// the need for port mappings, using the <code>name</code> parameter. The <code>name:internalName</code>
/// construct is analogous to <code>name:alias</code> in Docker links. For more information
/// on linking Docker containers, see <a href="https://docs.docker.com/userguide/dockerlinks/">https://docs.docker.com/userguide/dockerlinks/</a>.
/// </para>
/// <important>
/// <para>
/// Containers that are collocated on a single container instance may be able to communicate
/// with each other without requiring links or host port mappings. Network isolation is
/// achieved on the container instance using security groups and VPC settings.
/// </para>
/// </important>
/// </summary>
public List<string> Links
{
get { return this._links; }
set { this._links = value; }
}
// Check to see if Links property is set
internal bool IsSetLinks()
{
return this._links != null && this._links.Count > 0;
}
/// <summary>
/// Gets and sets the property Memory.
/// <para>
/// The number of MiB of memory reserved for the container. If your container attempts
/// to exceed the memory allocated here, the container is killed.
/// </para>
/// </summary>
public int Memory
{
get { return this._memory.GetValueOrDefault(); }
set { this._memory = value; }
}
// Check to see if Memory property is set
internal bool IsSetMemory()
{
return this._memory.HasValue;
}
/// <summary>
/// Gets and sets the property MountPoints.
/// <para>
/// The mount points for data volumes in your container.
/// </para>
/// </summary>
public List<MountPoint> MountPoints
{
get { return this._mountPoints; }
set { this._mountPoints = value; }
}
// Check to see if MountPoints property is set
internal bool IsSetMountPoints()
{
return this._mountPoints != null && this._mountPoints.Count > 0;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// The name of a container. If you are linking multiple containers together in a task
/// definition, the <code>name</code> of one container can be entered in the <code>links</code>
/// of another container to connect the containers.
/// </para>
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
/// <summary>
/// Gets and sets the property PortMappings.
/// <para>
/// The list of port mappings for the container.
/// </para>
/// </summary>
public List<PortMapping> PortMappings
{
get { return this._portMappings; }
set { this._portMappings = value; }
}
// Check to see if PortMappings property is set
internal bool IsSetPortMappings()
{
return this._portMappings != null && this._portMappings.Count > 0;
}
/// <summary>
/// Gets and sets the property VolumesFrom.
/// <para>
/// Data volumes to mount from another container.
/// </para>
/// </summary>
public List<VolumeFrom> VolumesFrom
{
get { return this._volumesFrom; }
set { this._volumesFrom = value; }
}
// Check to see if VolumesFrom property is set
internal bool IsSetVolumesFrom()
{
return this._volumesFrom != null && this._volumesFrom.Count > 0;
}
}
}
| |
/* ****************************************************************************
*
* 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
* vspython@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.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
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.VisualStudioTools.Project {
internal class FileNode : HierarchyNode, IDiskBasedNode {
private bool _isLinkFile;
private uint _docCookie;
private static readonly string[] _defaultOpensWithDesignViewExtensions = new[] { ".aspx", ".ascx", ".asax", ".asmx", ".xsd", ".resource", ".xaml" };
private static readonly string[] _supportsDesignViewExtensions = new[] { ".aspx", ".ascx", ".asax", ".asmx" };
private static readonly string[] _supportsDesignViewSubTypes = new[] { ProjectFileAttributeValue.Code, ProjectFileAttributeValue.Form, ProjectFileAttributeValue.UserControl, ProjectFileAttributeValue.Component, ProjectFileAttributeValue.Designer };
private string _caption;
#region static fields
#if !DEV14_OR_LATER
private static Dictionary<string, int> extensionIcons;
#endif
#endregion
#region overriden Properties
public override bool DefaultOpensWithDesignView {
get {
// ASPX\ASCX files support design view but should be opened by default with
// LOGVIEWID_Primary - this is because they support design and html view which
// is a tools option setting for them. If we force designview this option
// gets bypassed. We do a similar thing for asax/asmx/xsd. By doing so, we don't force
// the designer to be invoked when double-clicking on the - it will now go through the
// shell's standard open mechanism.
string extension = Path.GetExtension(Url);
return !_defaultOpensWithDesignViewExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase) &&
!IsCodeBehindFile &&
SupportsDesignView;
}
}
public override bool SupportsDesignView {
get {
if (ItemNode != null && !ItemNode.IsExcluded) {
string extension = Path.GetExtension(Url);
if (_supportsDesignViewExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase) ||
IsCodeBehindFile) {
return true;
} else {
var subType = ItemNode.GetMetadata("SubType");
if (subType != null && _supportsDesignViewExtensions.Contains(subType, StringComparer.OrdinalIgnoreCase)) {
return true;
}
}
}
return false;
}
}
public override bool IsNonMemberItem {
get {
return ItemNode is AllFilesProjectElement;
}
}
/// <summary>
/// overwrites of the generic hierarchyitem.
/// </summary>
[System.ComponentModel.BrowsableAttribute(false)]
public override string Caption {
get {
return _caption;
}
}
private void UpdateCaption() {
// Use LinkedIntoProjectAt property if available
string caption = this.ItemNode.GetMetadata(ProjectFileConstants.LinkedIntoProjectAt);
if (caption == null || caption.Length == 0) {
// Otherwise use filename
caption = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
caption = Path.GetFileName(caption);
}
_caption = caption;
}
public override string GetEditLabel() {
if (IsLinkFile) {
// cannot rename link files
return null;
}
return base.GetEditLabel();
}
#if !DEV14_OR_LATER
public override int ImageIndex {
get {
// Check if the file is there.
if (!this.CanShowDefaultIcon()) {
return (int)ProjectNode.ImageName.MissingFile;
}
//Check for known extensions
int imageIndex;
string extension = Path.GetExtension(this.FileName);
if ((string.IsNullOrEmpty(extension)) || (!extensionIcons.TryGetValue(extension, out imageIndex))) {
// Missing or unknown extension; let the base class handle this case.
return base.ImageIndex;
}
// The file type is known and there is an image for it in the image list.
return imageIndex;
}
}
#endif
public uint DocCookie {
get {
return this._docCookie;
}
set {
this._docCookie = value;
}
}
public override bool IsLinkFile {
get {
return _isLinkFile;
}
}
internal void SetIsLinkFile(bool value) {
_isLinkFile = value;
}
protected override VSOVERLAYICON OverlayIconIndex {
get {
if (IsLinkFile) {
return VSOVERLAYICON.OVERLAYICON_SHORTCUT;
}
return VSOVERLAYICON.OVERLAYICON_NONE;
}
}
public override Guid ItemTypeGuid {
get { return VSConstants.GUID_ItemType_PhysicalFile; }
}
public override int MenuCommandId {
get { return VsMenus.IDM_VS_CTXT_ITEMNODE; }
}
public override string Url {
get {
return ItemNode.Url;
}
}
#endregion
#region ctor
#if !DEV14_OR_LATER
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")]
static FileNode() {
// Build the dictionary with the mapping between some well known extensions
// and the index of the icons inside the standard image list.
extensionIcons = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
extensionIcons.Add(".aspx", (int)ProjectNode.ImageName.WebForm);
extensionIcons.Add(".asax", (int)ProjectNode.ImageName.GlobalApplicationClass);
extensionIcons.Add(".asmx", (int)ProjectNode.ImageName.WebService);
extensionIcons.Add(".ascx", (int)ProjectNode.ImageName.WebUserControl);
extensionIcons.Add(".asp", (int)ProjectNode.ImageName.ASPPage);
extensionIcons.Add(".config", (int)ProjectNode.ImageName.WebConfig);
extensionIcons.Add(".htm", (int)ProjectNode.ImageName.HTMLPage);
extensionIcons.Add(".html", (int)ProjectNode.ImageName.HTMLPage);
extensionIcons.Add(".css", (int)ProjectNode.ImageName.StyleSheet);
extensionIcons.Add(".xsl", (int)ProjectNode.ImageName.StyleSheet);
extensionIcons.Add(".vbs", (int)ProjectNode.ImageName.ScriptFile);
extensionIcons.Add(".js", (int)ProjectNode.ImageName.ScriptFile);
extensionIcons.Add(".wsf", (int)ProjectNode.ImageName.ScriptFile);
extensionIcons.Add(".txt", (int)ProjectNode.ImageName.TextFile);
extensionIcons.Add(".resx", (int)ProjectNode.ImageName.Resources);
extensionIcons.Add(".rc", (int)ProjectNode.ImageName.Resources);
extensionIcons.Add(".bmp", (int)ProjectNode.ImageName.Bitmap);
extensionIcons.Add(".ico", (int)ProjectNode.ImageName.Icon);
extensionIcons.Add(".gif", (int)ProjectNode.ImageName.Image);
extensionIcons.Add(".jpg", (int)ProjectNode.ImageName.Image);
extensionIcons.Add(".png", (int)ProjectNode.ImageName.Image);
extensionIcons.Add(".map", (int)ProjectNode.ImageName.ImageMap);
extensionIcons.Add(".wav", (int)ProjectNode.ImageName.Audio);
extensionIcons.Add(".mid", (int)ProjectNode.ImageName.Audio);
extensionIcons.Add(".midi", (int)ProjectNode.ImageName.Audio);
extensionIcons.Add(".avi", (int)ProjectNode.ImageName.Video);
extensionIcons.Add(".mov", (int)ProjectNode.ImageName.Video);
extensionIcons.Add(".mpg", (int)ProjectNode.ImageName.Video);
extensionIcons.Add(".mpeg", (int)ProjectNode.ImageName.Video);
extensionIcons.Add(".cab", (int)ProjectNode.ImageName.CAB);
extensionIcons.Add(".jar", (int)ProjectNode.ImageName.JAR);
extensionIcons.Add(".xslt", (int)ProjectNode.ImageName.XSLTFile);
extensionIcons.Add(".xsd", (int)ProjectNode.ImageName.XMLSchema);
extensionIcons.Add(".xml", (int)ProjectNode.ImageName.XMLFile);
extensionIcons.Add(".pfx", (int)ProjectNode.ImageName.PFX);
extensionIcons.Add(".snk", (int)ProjectNode.ImageName.SNK);
}
#endif
/// <summary>
/// Constructor for the FileNode
/// </summary>
/// <param name="root">Root of the hierarchy</param>
/// <param name="e">Associated project element</param>
public FileNode(ProjectNode root, ProjectElement element)
: base(root, element) {
UpdateCaption();
}
#endregion
#region overridden methods
protected override NodeProperties CreatePropertiesObject() {
if (IsLinkFile) {
return new LinkFileNodeProperties(this);
} else if (IsNonMemberItem) {
return new ExcludedFileNodeProperties(this);
}
return new IncludedFileNodeProperties(this);
}
/// <summary>
/// Get an instance of the automation object for a FileNode
/// </summary>
/// <returns>An instance of the Automation.OAFileNode if succeeded</returns>
public override object GetAutomationObject() {
if (this.ProjectMgr == null || this.ProjectMgr.IsClosed) {
return null;
}
return new Automation.OAFileItem(this.ProjectMgr.GetAutomationObject() as Automation.OAProject, this);
}
/// <summary>
/// Renames a file node.
/// </summary>
/// <param name="label">The new name.</param>
/// <returns>An errorcode for failure or S_OK.</returns>
/// <exception cref="InvalidOperationException" if the file cannot be validated>
/// <devremark>
/// We are going to throw instead of showing messageboxes, since this method is called from various places where a dialog box does not make sense.
/// For example the FileNodeProperties are also calling this method. That should not show directly a messagebox.
/// Also the automation methods are also calling SetEditLabel
/// </devremark>
public override int SetEditLabel(string label) {
// IMPORTANT NOTE: This code will be called when a parent folder is renamed. As such, it is
// expected that we can be called with a label which is the same as the current
// label and this should not be considered a NO-OP.
if (this.ProjectMgr == null || this.ProjectMgr.IsClosed) {
return VSConstants.E_FAIL;
}
// Validate the filename.
if (String.IsNullOrEmpty(label)) {
throw new InvalidOperationException(SR.GetString(SR.ErrorInvalidFileName, label));
} else if (label.Length > NativeMethods.MAX_PATH) {
throw new InvalidOperationException(SR.GetString(SR.PathTooLong, label));
} else if (Utilities.IsFileNameInvalid(label)) {
throw new InvalidOperationException(SR.GetString(SR.ErrorInvalidFileName, label));
}
for (HierarchyNode n = this.Parent.FirstChild; n != null; n = n.NextSibling) {
// TODO: Distinguish between real Urls and fake ones (eg. "References")
if (n != this && String.Equals(n.GetEditLabel(), label, StringComparison.OrdinalIgnoreCase)) {
//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.
throw new InvalidOperationException(SR.GetString(SR.FileOrFolderAlreadyExists, label));
}
}
string fileName = Path.GetFileNameWithoutExtension(label);
// Verify that the file extension is unchanged
string strRelPath = Path.GetFileName(this.ItemNode.GetMetadata(ProjectFileConstants.Include));
if (!Utilities.IsInAutomationFunction(this.ProjectMgr.Site) &&
!String.Equals(Path.GetExtension(strRelPath), Path.GetExtension(label), StringComparison.OrdinalIgnoreCase)) {
// Prompt to confirm that they really want to change the extension of the file
string message = SR.GetString(SR.ConfirmExtensionChange, label);
IVsUIShell shell = this.ProjectMgr.Site.GetService(typeof(SVsUIShell)) as IVsUIShell;
Utilities.CheckNotNull(shell, "Could not get the UI shell from the project");
if (!VsShellUtilities.PromptYesNo(message, null, OLEMSGICON.OLEMSGICON_INFO, shell)) {
// The user cancelled the confirmation for changing the extension.
// Return S_OK in order not to show any extra dialog box
return VSConstants.S_OK;
}
}
// Build the relative path by looking at folder names above us as one scenarios
// where we get called is when a folder above us gets renamed (in which case our path is invalid)
HierarchyNode parent = this.Parent;
while (parent != null && (parent is FolderNode)) {
strRelPath = Path.Combine(parent.GetEditLabel(), strRelPath);
parent = parent.Parent;
}
return SetEditLabel(label, strRelPath);
}
public override string GetMkDocument() {
Debug.Assert(!string.IsNullOrEmpty(this.Url), "No url specified for this node");
Debug.Assert(Path.IsPathRooted(this.Url), "Url should not be a relative path");
return this.Url;
}
/// <summary>
/// Delete the item corresponding to the specified path from storage.
/// </summary>
/// <param name="path"></param>
protected internal override void DeleteFromStorage(string path) {
if (File.Exists(path)) {
File.SetAttributes(path, FileAttributes.Normal); // make sure it's not readonly.
File.Delete(path);
}
}
/// <summary>
/// Rename the underlying document based on the change the user just made to the edit label.
/// </summary>
protected internal override int SetEditLabel(string label, string relativePath) {
int returnValue = VSConstants.S_OK;
uint oldId = this.ID;
string strSavePath = Path.GetDirectoryName(relativePath);
strSavePath = CommonUtils.GetAbsoluteDirectoryPath(this.ProjectMgr.ProjectHome, strSavePath);
string newName = Path.Combine(strSavePath, label);
if (String.Equals(newName, this.Url, StringComparison.Ordinal)) {
// This is really a no-op (including changing case), so there is nothing to do
return VSConstants.S_FALSE;
} else if (String.Equals(newName, this.Url, StringComparison.OrdinalIgnoreCase)) {
// This is a change of file casing only.
} else {
// If the renamed file already exists then quit (unless it is the result of the parent having done the move).
if (IsFileOnDisk(newName)
&& (IsFileOnDisk(this.Url)
|| !String.Equals(Path.GetFileName(newName), Path.GetFileName(this.Url), StringComparison.OrdinalIgnoreCase))) {
throw new InvalidOperationException(SR.GetString(SR.FileCannotBeRenamedToAnExistingFile, label));
} else if (newName.Length > NativeMethods.MAX_PATH) {
throw new InvalidOperationException(SR.GetString(SR.PathTooLong, label));
}
}
string oldName = this.Url;
// must update the caption prior to calling RenameDocument, since it may
// cause queries of that property (such as from open editors).
string oldrelPath = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
try {
if (!RenameDocument(oldName, newName)) {
this.ItemNode.Rename(oldrelPath);
}
if (this is DependentFileNode) {
ProjectMgr.OnInvalidateItems(this.Parent);
}
} catch (Exception e) {
// Just re-throw the exception so we don't get duplicate message boxes.
Trace.WriteLine("Exception : " + e.Message);
this.RecoverFromRenameFailure(newName, oldrelPath);
returnValue = Marshal.GetHRForException(e);
throw;
}
// Return S_FALSE if the hierarchy item id has changed. This forces VS to flush the stale
// hierarchy item id.
if (returnValue == (int)VSConstants.S_OK || returnValue == (int)VSConstants.S_FALSE || returnValue == VSConstants.OLE_E_PROMPTSAVECANCELLED) {
return (oldId == this.ID) ? VSConstants.S_OK : (int)VSConstants.S_FALSE;
}
return returnValue;
}
/// <summary>
/// Returns a specific Document manager to handle files
/// </summary>
/// <returns>Document manager object</returns>
protected internal override DocumentManager GetDocumentManager() {
return new FileDocumentManager(this);
}
public override int QueryService(ref Guid guidService, out object result) {
if (guidService == typeof(EnvDTE.Project).GUID) {
result = ProjectMgr.GetAutomationObject();
return VSConstants.S_OK;
} else if (guidService == typeof(EnvDTE.ProjectItem).GUID) {
result = GetAutomationObject();
return VSConstants.S_OK;
}
return base.QueryService(ref guidService, out result);
}
/// <summary>
/// Called by the drag&drop implementation to ask the node
/// which is being dragged/droped over which nodes should
/// process the operation.
/// This allows for dragging to a node that cannot contain
/// items to let its parent accept the drop, while a reference
/// node delegate to the project and a folder/project node to itself.
/// </summary>
/// <returns></returns>
protected internal override HierarchyNode GetDragTargetHandlerNode() {
Debug.Assert(this.ProjectMgr != null, " The project manager is null for the filenode");
HierarchyNode handlerNode = this;
while (handlerNode != null && !(handlerNode is ProjectNode || handlerNode is FolderNode))
handlerNode = handlerNode.Parent;
if (handlerNode == null)
handlerNode = this.ProjectMgr;
return handlerNode;
}
internal override int ExecCommandOnNode(Guid cmdGroup, uint cmd, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) {
if (this.ProjectMgr == null || this.ProjectMgr.IsClosed) {
return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED;
}
// Exec on special filenode commands
if (cmdGroup == VsMenus.guidStandardCommandSet97) {
IVsWindowFrame windowFrame = null;
switch ((VsCommands)cmd) {
case VsCommands.ViewCode:
return ((FileDocumentManager)this.GetDocumentManager()).Open(false, false, VSConstants.LOGVIEWID_Code, out windowFrame, WindowFrameShowAction.Show);
case VsCommands.ViewForm:
return ((FileDocumentManager)this.GetDocumentManager()).Open(false, false, VSConstants.LOGVIEWID_Designer, out windowFrame, WindowFrameShowAction.Show);
case VsCommands.Open:
return ((FileDocumentManager)this.GetDocumentManager()).Open(false, false, WindowFrameShowAction.Show);
case VsCommands.OpenWith:
return ((FileDocumentManager)this.GetDocumentManager()).Open(false, true, VSConstants.LOGVIEWID_UserChooseView, out windowFrame, WindowFrameShowAction.Show);
}
}
return base.ExecCommandOnNode(cmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut);
}
internal 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.ViewCode:
//case VsCommands.Delete: goto case VsCommands.OpenWith;
case VsCommands.Open:
case VsCommands.OpenWith:
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;
}
}
return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result);
}
protected override void DoDefaultAction() {
FileDocumentManager manager = this.GetDocumentManager() as FileDocumentManager;
Utilities.CheckNotNull(manager, "Could not get the FileDocumentManager");
manager.Open(false, false, WindowFrameShowAction.Show);
}
/// <summary>
/// Performs a SaveAs operation of an open document. Called from SaveItem after the running document table has been updated with the new doc data.
/// </summary>
/// <param name="docData">A pointer to the document in the rdt</param>
/// <param name="newFilePath">The new file path to the document</param>
/// <returns></returns>
internal override int AfterSaveItemAs(IntPtr docData, string newFilePath) {
Utilities.ArgumentNotNullOrEmpty("newFilePath", newFilePath);
int returnCode = VSConstants.S_OK;
newFilePath = newFilePath.Trim();
//Identify if Path or FileName are the same for old and new file
string newDirectoryName = CommonUtils.NormalizeDirectoryPath(Path.GetDirectoryName(newFilePath));
string oldDirectoryName = CommonUtils.NormalizeDirectoryPath(Path.GetDirectoryName(this.GetMkDocument()));
bool isSamePath = CommonUtils.IsSameDirectory(newDirectoryName, oldDirectoryName);
bool isSameFile = CommonUtils.IsSamePath(newFilePath, this.Url);
//Get target container
HierarchyNode targetContainer = null;
bool isLink = false;
if (isSamePath) {
targetContainer = this.Parent;
} else if (!CommonUtils.IsSubpathOf(this.ProjectMgr.ProjectHome, newDirectoryName)) {
targetContainer = this.Parent;
isLink = true;
} else if (CommonUtils.IsSameDirectory(this.ProjectMgr.ProjectHome, newDirectoryName)) {
//the projectnode is the target container
targetContainer = this.ProjectMgr;
} else {
//search for the target container among existing child nodes
targetContainer = this.ProjectMgr.FindNodeByFullPath(newDirectoryName);
if (targetContainer != null && (targetContainer is FileNode)) {
// We already have a file node with this name in the hierarchy.
throw new InvalidOperationException(SR.GetString(SR.FileAlreadyExistsAndCannotBeRenamed, Path.GetFileName(newFilePath)));
}
}
if (targetContainer == null) {
// Add a chain of subdirectories to the project.
string relativeUri = CommonUtils.GetRelativeDirectoryPath(this.ProjectMgr.ProjectHome, newDirectoryName);
targetContainer = this.ProjectMgr.CreateFolderNodes(relativeUri);
}
Utilities.CheckNotNull(targetContainer, "Could not find a target container");
//Suspend file changes while we rename the document
string oldrelPath = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
string oldName = CommonUtils.GetAbsoluteFilePath(this.ProjectMgr.ProjectHome, oldrelPath);
SuspendFileChanges sfc = new SuspendFileChanges(this.ProjectMgr.Site, oldName);
sfc.Suspend();
try {
// Rename the node.
DocumentManager.UpdateCaption(this.ProjectMgr.Site, Path.GetFileName(newFilePath), docData);
// Check if the file name was actually changed.
// In same cases (e.g. if the item is a file and the user has changed its encoding) this function
// is called even if there is no real rename.
if (!isSameFile || (this.Parent.ID != targetContainer.ID)) {
// The path of the file is changed or its parent is changed; in both cases we have
// to rename the item.
if (isLink != IsLinkFile) {
if (isLink) {
var newPath = CommonUtils.GetRelativeFilePath(
this.ProjectMgr.ProjectHome,
Path.Combine(Path.GetDirectoryName(Url), Path.GetFileName(newFilePath))
);
ItemNode.SetMetadata(ProjectFileConstants.Link, newPath);
} else {
ItemNode.SetMetadata(ProjectFileConstants.Link, null);
}
SetIsLinkFile(isLink);
}
RenameFileNode(oldName, newFilePath, targetContainer);
ProjectMgr.OnInvalidateItems(this.Parent);
}
} catch (Exception e) {
Trace.WriteLine("Exception : " + e.Message);
this.RecoverFromRenameFailure(newFilePath, oldrelPath);
throw;
} finally {
sfc.Resume();
}
return returnCode;
}
/// <summary>
/// Determines if this is node a valid node for painting the default file icon.
/// </summary>
/// <returns></returns>
protected override bool CanShowDefaultIcon() {
string moniker = this.GetMkDocument();
return File.Exists(moniker);
}
#endregion
#region virtual methods
public override object GetProperty(int propId) {
switch ((__VSHPROPID)propId) {
case __VSHPROPID.VSHPROPID_ItemDocCookie:
if (this.DocCookie != 0)
return (IntPtr)this.DocCookie; //cast to IntPtr as some callers expect VT_INT
break;
}
return base.GetProperty(propId);
}
public virtual string FileName {
get {
return this.GetEditLabel();
}
set {
this.SetEditLabel(value);
}
}
/// <summary>
/// Determine if this item is represented physical on disk and shows a messagebox in case that the file is not present and a UI is to be presented.
/// </summary>
/// <param name="showMessage">true if user should be presented for UI in case the file is not present</param>
/// <returns>true if file is on disk</returns>
internal protected virtual bool IsFileOnDisk(bool showMessage) {
bool fileExist = IsFileOnDisk(this.Url);
if (!fileExist && showMessage && !Utilities.IsInAutomationFunction(this.ProjectMgr.Site)) {
string message = SR.GetString(SR.ItemDoesNotExistInProjectDirectory, GetEditLabel());
string title = string.Empty;
OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL;
OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK;
OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
Utilities.ShowMessageBox(this.ProjectMgr.Site, title, message, icon, buttons, defaultButton);
}
return fileExist;
}
/// <summary>
/// Determine if the file represented by "path" exist in storage.
/// Override this method if your files are not persisted on disk.
/// </summary>
/// <param name="path">Url representing the file</param>
/// <returns>True if the file exist</returns>
internal protected virtual bool IsFileOnDisk(string path) {
return File.Exists(path);
}
/// <summary>
/// Renames the file in the hierarchy by removing old node and adding a new node in the hierarchy.
/// </summary>
/// <param name="oldFileName">The old file name.</param>
/// <param name="newFileName">The new file name</param>
/// <param name="newParentId">The new parent id of the item.</param>
/// <returns>The newly added FileNode.</returns>
/// <remarks>While a new node will be used to represent the item, the underlying MSBuild item will be the same and as a result file properties saved in the project file will not be lost.</remarks>
internal FileNode RenameFileNode(string oldFileName, string newFileName, HierarchyNode newParent) {
if (CommonUtils.IsSamePath(oldFileName, newFileName)) {
// We do not want to rename the same file
return null;
}
//If we are included in the project and our parent isn't then
//we need to bring our parent into the project
if (!this.IsNonMemberItem && newParent.IsNonMemberItem) {
ErrorHandler.ThrowOnFailure(newParent.IncludeInProject(false));
}
// Retrieve child nodes to add later.
List<HierarchyNode> childNodes = this.GetChildNodes();
FileNode renamedNode;
using (this.ProjectMgr.ExtensibilityEventsDispatcher.Suspend()) {
// Remove this from its parent.
ProjectMgr.OnItemDeleted(this);
this.Parent.RemoveChild(this);
// Update name in MSBuild
this.ItemNode.Rename(CommonUtils.GetRelativeFilePath(ProjectMgr.ProjectHome, newFileName));
// Request a new file node be made. This is used to replace the old file node. This way custom
// derived FileNode types will be used and correctly associated on rename. This is useful for things
// like .txt -> .js where the file would now be able to be a startup project/file.
renamedNode = this.ProjectMgr.CreateFileNode(this.ItemNode);
renamedNode.ItemNode.RefreshProperties();
renamedNode.UpdateCaption();
newParent.AddChild(renamedNode);
renamedNode.Parent = newParent;
}
UpdateCaption();
ProjectMgr.ReDrawNode(renamedNode, UIHierarchyElement.Caption);
renamedNode.ProjectMgr.ExtensibilityEventsDispatcher.FireItemRenamed(this, oldFileName);
//Update the new document in the RDT.
DocumentManager.RenameDocument(renamedNode.ProjectMgr.Site, oldFileName, newFileName, renamedNode.ID);
//Select the new node in the hierarchy
renamedNode.ExpandItem(EXPANDFLAGS.EXPF_SelectItem);
// Add children to new node and rename them appropriately.
childNodes.ForEach(x => renamedNode.AddChild(x));
RenameChildNodes(renamedNode);
return renamedNode;
}
/// <summary>
/// Rename all childnodes
/// </summary>
/// <param name="newFileNode">The newly added Parent node.</param>
protected virtual void RenameChildNodes(FileNode parentNode) {
foreach (var childNode in GetChildNodes().OfType<FileNode>()) {
string newfilename;
if (childNode.HasParentNodeNameRelation) {
string relationalName = childNode.Parent.GetRelationalName();
string extension = childNode.GetRelationNameExtension();
newfilename = relationalName + extension;
newfilename = CommonUtils.GetAbsoluteFilePath(Path.GetDirectoryName(childNode.Parent.GetMkDocument()), newfilename);
} else {
newfilename = CommonUtils.GetAbsoluteFilePath(Path.GetDirectoryName(childNode.Parent.GetMkDocument()), childNode.GetEditLabel());
}
childNode.RenameDocument(childNode.GetMkDocument(), newfilename);
//We must update the DependsUpon property since the rename operation will not do it if the childNode is not renamed
//which happens if the is no name relation between the parent and the child
string dependentOf = childNode.ItemNode.GetMetadata(ProjectFileConstants.DependentUpon);
if (!string.IsNullOrEmpty(dependentOf)) {
childNode.ItemNode.SetMetadata(ProjectFileConstants.DependentUpon, childNode.Parent.ItemNode.GetMetadata(ProjectFileConstants.Include));
}
}
}
/// <summary>
/// Tries recovering from a rename failure.
/// </summary>
/// <param name="fileThatFailed"> The file that failed to be renamed.</param>
/// <param name="originalFileName">The original filenamee</param>
protected virtual void RecoverFromRenameFailure(string fileThatFailed, string originalFileName) {
if (this.ItemNode != null && !String.IsNullOrEmpty(originalFileName)) {
this.ItemNode.Rename(originalFileName);
}
}
internal override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation) {
if (deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_DeleteFromStorage) {
return this.ProjectMgr.CanProjectDeleteItems;
}
return false;
}
/// <summary>
/// This should be overriden for node that are not saved on disk
/// </summary>
/// <param name="oldName">Previous name in storage</param>
/// <param name="newName">New name in storage</param>
internal virtual void RenameInStorage(string oldName, string newName) {
// Make a few attempts over a short time period
for (int retries = 4; retries > 0; --retries) {
try {
File.Move(oldName, newName);
return;
} catch (IOException) {
System.Threading.Thread.Sleep(50);
}
}
// Final attempt has no handling so exception propagates
File.Move(oldName, newName);
}
/// <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>
protected internal override void GetSccSpecialFiles(string sccFile, IList<string> files, IList<tagVsSccFilesFlags> flags) {
if (this.ExcludeNodeFromScc) {
return;
}
Utilities.ArgumentNotNull("files", files);
Utilities.ArgumentNotNull("flags", flags);
foreach (HierarchyNode node in this.GetChildNodes()) {
files.Add(node.GetMkDocument());
}
}
#endregion
#region Helper methods
/// <summary>
/// Gets called to rename the eventually running document this hierarchyitem points to
/// </summary>
/// returns FALSE if the doc can not be renamed
internal bool RenameDocument(string oldName, string newName) {
IVsRunningDocumentTable pRDT = this.GetService(typeof(IVsRunningDocumentTable)) as IVsRunningDocumentTable;
if (pRDT == null)
return false;
IntPtr docData = IntPtr.Zero;
IVsHierarchy pIVsHierarchy;
uint itemId;
uint uiVsDocCookie;
SuspendFileChanges sfc = null;
if (File.Exists(oldName)) {
sfc = new SuspendFileChanges(this.ProjectMgr.Site, oldName);
sfc.Suspend();
}
try {
// Suspend ms build since during a rename operation no msbuild re-evaluation should be performed until we have finished.
// Scenario that could fail if we do not suspend.
// We have a project system relying on MPF that triggers a Compile target build (re-evaluates itself) whenever the project changes. (example: a file is added, property changed.)
// 1. User renames a file in the above project sytem relying on MPF
// 2. Our rename funstionality implemented in this method removes and readds the file and as a post step copies all msbuild entries from the removed file to the added file.
// 3. The project system mentioned will trigger an msbuild re-evaluate with the new item, because it was listening to OnItemAdded.
// The problem is that the item at the "add" time is only partly added to the project, since the msbuild part has not yet been copied over as mentioned in part 2 of the last step of the rename process.
// The result is that the project re-evaluates itself wrongly.
VSRENAMEFILEFLAGS renameflag = VSRENAMEFILEFLAGS.VSRENAMEFILEFLAGS_NoFlags;
ErrorHandler.ThrowOnFailure(pRDT.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, oldName, out pIVsHierarchy, out itemId, out docData, out uiVsDocCookie));
if (pIVsHierarchy != null && !Utilities.IsSameComObject(pIVsHierarchy, this.ProjectMgr)) {
// Don't rename it if it wasn't opened by us.
return false;
}
// ask other potentially running packages
if (!this.ProjectMgr.Tracker.CanRenameItem(oldName, newName, renameflag)) {
return false;
}
if (IsFileOnDisk(oldName)) {
RenameInStorage(oldName, newName);
}
// For some reason when ignoreFileChanges is called in Resume, we get an ArgumentException because
// Somewhere a required fileWatcher is null. This issue only occurs when you copy and rename a typescript file,
// Calling Resume here prevents said fileWatcher from being null. Don't know why it works, but it does.
// Also fun! This is the only location it can go (between RenameInStorage and RenameFileNode)
// So presumably there is some condition that is no longer met once both of these methods are called with a ts file.
// https://nodejstools.codeplex.com/workitem/1510
if (sfc != null) {
sfc.Resume();
sfc.Suspend();
}
if (!CommonUtils.IsSamePath(oldName, newName)) {
// Check out the project file if necessary.
if (!this.ProjectMgr.QueryEditProjectFile(false)) {
throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
}
this.RenameFileNode(oldName, newName);
} else {
this.RenameCaseOnlyChange(oldName, newName);
}
DocumentManager.UpdateCaption(this.ProjectMgr.Site, Caption, docData);
// changed from MPFProj:
// http://mpfproj10.codeplex.com/WorkItem/View.aspx?WorkItemId=8231
this.ProjectMgr.Tracker.OnItemRenamed(oldName, newName, renameflag);
} finally {
if (sfc != null) {
sfc.Resume();
}
if (docData != IntPtr.Zero) {
Marshal.Release(docData);
}
}
return true;
}
internal virtual FileNode RenameFileNode(string oldFileName, string newFileName) {
string newFolder = Path.GetDirectoryName(newFileName) + Path.DirectorySeparatorChar;
var parentFolder = ProjectMgr.FindNodeByFullPath(newFolder);
if (parentFolder == null) {
Debug.Assert(newFolder == ProjectMgr.ProjectHome);
parentFolder = ProjectMgr;
}
return this.RenameFileNode(oldFileName, newFileName, parentFolder);
}
/// <summary>
/// Renames the file node for a case only change.
/// </summary>
/// <param name="newFileName">The new file name.</param>
private void RenameCaseOnlyChange(string oldName, string newName) {
//Update the include for this item.
string relName = CommonUtils.GetRelativeFilePath(this.ProjectMgr.ProjectHome, newName);
Debug.Assert(String.Equals(this.ItemNode.GetMetadata(ProjectFileConstants.Include), relName, StringComparison.OrdinalIgnoreCase),
"Not just changing the filename case");
this.ItemNode.Rename(relName);
this.ItemNode.RefreshProperties();
UpdateCaption();
ProjectMgr.ReDrawNode(this, UIHierarchyElement.Caption);
this.RenameChildNodes(this);
// Refresh the property browser.
IVsUIShell shell = this.ProjectMgr.Site.GetService(typeof(SVsUIShell)) as IVsUIShell;
Utilities.CheckNotNull(shell, "Could not get the UI shell from the project");
ErrorHandler.ThrowOnFailure(shell.RefreshPropertyBrowser(0));
//Select the new node in the hierarchy
ExpandItem(EXPANDFLAGS.EXPF_SelectItem);
}
#endregion
#region helpers
/// <summary>
/// Update the ChildNodes after the parent node has been renamed
/// </summary>
/// <param name="newFileNode">The new FileNode created as part of the rename of this node</param>
private void SetNewParentOnChildNodes(FileNode newFileNode) {
foreach (HierarchyNode childNode in GetChildNodes()) {
childNode.Parent = newFileNode;
}
}
private List<HierarchyNode> GetChildNodes() {
List<HierarchyNode> childNodes = new List<HierarchyNode>();
HierarchyNode childNode = this.FirstChild;
while (childNode != null) {
childNodes.Add(childNode);
childNode = childNode.NextSibling;
}
return childNodes;
}
#endregion
void IDiskBasedNode.RenameForDeferredSave(string basePath, string baseNewPath) {
string oldLoc = CommonUtils.GetAbsoluteFilePath(basePath, ItemNode.GetMetadata(ProjectFileConstants.Include));
string newLoc = CommonUtils.GetAbsoluteFilePath(baseNewPath, ItemNode.GetMetadata(ProjectFileConstants.Include));
ProjectMgr.UpdatePathForDeferredSave(oldLoc, newLoc);
// make sure the directory is there
Directory.CreateDirectory(Path.GetDirectoryName(newLoc));
if (File.Exists(oldLoc)) {
File.Move(oldLoc, newLoc);
}
}
}
}
| |
// Copyright (c) 2007-2008, Gaudenz Alder
using System;
using System.Collections.Generic;
using System.Text;
namespace com.mxgraph
{
/// <summary>
/// Fast organic layout algorithm.
/// </summary>
public class mxFastOrganicLayout: mxIGraphLayout
{
/// <summary>
/// Holds the enclosing graph.
/// </summary>
protected mxGraph graph;
/// <summary>
/// The force constant by which the attractive forces are divided and the
/// replusive forces are multiple by the square of. The value equates to the
/// average radius there is of free space around each node. Default is 50.
/// </summary>
protected double forceConstant = 50;
/// <summary>
/// Cache of forceConstant^2 for performance.
/// </summary>
protected double forceConstantSquared = 0;
/// <summary>
/// Minimal distance limit. Default is 2. Prevents of
/// dividing by zero.
/// </summary>
protected double minDistanceLimit = 2;
/// <summary>
/// Cached version of minDistanceLimit squared.
/// </summary>
protected double minDistanceLimitSquared = 0;
/// <summary>
/// Start value of temperature. Default is 200.
/// </summary>
protected double initialTemp = 200;
/// <summary>
/// Temperature to limit displacement at later stages of layout.
/// </summary>
protected double temperature = 0;
/// <summary>
/// Total number of iterations to run the layout though.
/// </summary>
protected int maxIterations = 0;
/// <summary>
/// Current iteration count.
/// </summary>
protected int iteration = 0;
/// <summary>
/// An array of all vertices to be laid out.
/// </summary>
protected Object[] vertexArray;
/// <summary>
/// An array of locally stored X co-ordinate displacements for the vertices.
/// </summary>
protected double[] dispX;
/// <summary>
/// An array of locally stored Y co-ordinate displacements for the vertices.
/// </summary>
protected double[] dispY;
/// <summary>
/// An array of locally stored co-ordinate positions for the vertices.
/// </summary>
protected double[][] cellLocation;
/// <summary>
/// The approximate radius of each cell, nodes only.
/// </summary>
protected double[] radius;
/// <summary>
/// The approximate radius squared of each cell, nodes only.
/// </summary>
protected double[] radiusSquared;
/// <summary>
/// Array of booleans representing the movable states of the vertices.
/// </summary>
protected bool[] isMoveable;
/// <summary>
/// Local copy of cell neighbours.
/// </summary>
protected int[][] neighbours;
/// <summary>
/// Boolean flag that specifies if the layout is allowed to run. If this is
/// set to false, then the layout exits in the following iteration.
/// </summary>
protected bool allowedToRun = true;
/// <summary>
/// Maps from vertices to indices.
/// </summary>
protected Dictionary<object, int> indices = new Dictionary<object, int>();
/// <summary>
/// Random number generator.
/// </summary>
protected Random random = new Random();
/// <summary>
/// Constructs a new fast organic layout for the specified graph.
/// </summary>
/// <param name="graph"></param>
public mxFastOrganicLayout(mxGraph graph)
{
this.graph = graph;
}
/// <summary>
/// Flag to stop a running layout run.
/// </summary>
public bool IsAllowedToRun
{
get { return allowedToRun; }
set { allowedToRun = value; }
}
/// <summary>
/// Returns true if the given cell should be ignored by the layout algorithm.
/// This implementation returns false if the cell is a vertex and has at least
/// one connected edge.
/// </summary>
/// <param name="cell">Object that represents the cell.</param>
/// <returns>Returns true if the given cell should be ignored.</returns>
public bool IsCellIgnored(Object cell)
{
return !graph.Model.IsVertex(cell) ||
graph.Model.GetEdgeCount(cell) == 0;
}
/// <summary>
/// Maximum number of iterations.
/// </summary>
public int MaxIterations
{
get { return maxIterations; }
set { maxIterations = value; }
}
/// <summary>
/// Force constant to be used for the springs.
/// </summary>
public double ForceConstant
{
get { return forceConstant; }
set { forceConstant = value; }
}
/// <summary>
/// Minimum distance between nodes.
/// </summary>
public double MinDistanceLimit
{
get { return minDistanceLimit; }
set { minDistanceLimit = value; }
}
/// <summary>
/// Initial temperature.
/// </summary>
public double InitialTemp
{
get { return initialTemp; }
set { initialTemp = value; }
}
/// <summary>
/// Reduces the temperature of the layout from an initial setting in a linear
/// fashion to zero.
/// </summary>
protected void reduceTemperature()
{
temperature = initialTemp * (1.0 - iteration / maxIterations);
}
/// <summary>
/// Notified when a cell is being moved in a parent
/// that has automatic layout to update the cell
/// state (eg. index) so that the outcome of the
/// layou will position the vertex as close to the
/// point (x, y) as possible.
///
/// Not yet implemented.
/// </summary>
/// <param name="cell"></param>
/// <param name="x"></param>
/// <param name="y"></param>
public void move(Object cell, double x, double y)
{
// TODO: Map the position to a child index for
// the cell to be placed closest to the position
}
/// <summary>
/// Executes the fast organic layout.
/// </summary>
/// <param name="parent"></param>
public void execute(Object parent)
{
mxIGraphModel model = graph.Model;
// Finds the relevant vertices for the layout
int childCount = model.GetChildCount(parent);
List<Object> tmp = new List<Object>(childCount);
for (int i = 0; i < childCount; i++)
{
Object child = model.GetChildAt(parent, i);
if (!IsCellIgnored(child))
{
tmp.Add(child);
}
}
vertexArray = tmp.ToArray();
int n = vertexArray.Length;
dispX = new double[n];
dispY = new double[n];
cellLocation = new double[n][];
isMoveable = new bool[n];
neighbours = new int[n][];
radius = new double[n];
radiusSquared = new double[n];
minDistanceLimitSquared = minDistanceLimit * minDistanceLimit;
if (forceConstant < 0.001)
{
forceConstant = 0.001;
}
forceConstantSquared = forceConstant * forceConstant;
// Create a map of vertices first. This is required for the array of
// arrays called neighbours which holds, for each vertex, a list of
// ints which represents the neighbours cells to that vertex as
// the indices into vertexArray
for (int i = 0; i < vertexArray.Length; i++)
{
Object vertex = vertexArray[i];
cellLocation[i] = new double[2];
// Set up the mapping from array indices to cells
indices[vertex] = i;
mxGeometry bounds = model.GetGeometry(vertex);
// Set the X,Y value of the internal version of the cell to
// the center point of the vertex for better positioning
double width = bounds.Width;
double height = bounds.Height;
// Randomize (0, 0) locations
double x = bounds.X;
double y = bounds.Y;
cellLocation[i][0] = x + width / 2.0;
cellLocation[i][1] = y + height / 2.0;
radius[i] = Math.Min(width, height);
radiusSquared[i] = radius[i] * radius[i];
}
for (int i = 0; i < n; i++)
{
dispX[i] = 0;
dispY[i] = 0;
isMoveable[i] = graph.IsCellMovable(vertexArray[i]);
// Get lists of neighbours to all vertices, translate the cells
// obtained in indices into vertexArray and store as an array
// against the orginial cell index
Object[] edges = mxGraphModel.GetEdges(model, vertexArray[i]);
Object[] cells = mxGraphModel.GetOpposites(model, edges,
vertexArray[i], true, true);
neighbours[i] = new int[cells.Length];
for (int j = 0; j < cells.Length; j++)
{
int? index = indices[cells[j]];
// Check the connected cell in part of the vertex list to be
// acted on by this layout
if (index != null)
{
neighbours[i][j] = (int) index;
}
// Else if index of the other cell doesn't correspond to
// any cell listed to be acted upon in this layout. Set
// the index to the value of this vertex (a dummy self-loop)
// so the attraction force of the edge is not calculated
else
{
neighbours[i][j] = i;
}
}
}
temperature = initialTemp;
// If max number of iterations has not been set, guess it
if (maxIterations == 0)
{
maxIterations = (int)(20 * Math.Sqrt(n));
}
// Main iteration loop
for (iteration = 0; iteration < maxIterations; iteration++)
{
if (!allowedToRun)
{
return;
}
// Calculate repulsive forces on all vertices
calcRepulsion();
// Calculate attractive forces through edges
calcAttraction();
calcPositions();
reduceTemperature();
}
// Moved cell location back to top-left from center locations used in
// algorithm
model.BeginUpdate();
try
{
double? minx = null;
double? miny = null;
for (int i = 0; i < vertexArray.Length; i++)
{
Object vertex = vertexArray[i];
mxGeometry geo = model.GetGeometry(vertex);
if (geo != null)
{
cellLocation[i][0] -= geo.Width / 2.0;
cellLocation[i][1] -= geo.Height / 2.0;
geo = geo.Clone();
geo.X = graph.Snap(cellLocation[i][0]);
geo.Y = graph.Snap(cellLocation[i][1]);
model.SetGeometry(vertex, geo);
if (minx == null)
{
minx = geo.X;
}
else
{
minx = Math.Min((double) minx, geo.X);
}
if (miny == null)
{
miny = geo.Y;
}
else
{
miny = Math.Min((double) miny, geo.Y);
}
}
}
// Modifies the cloned geometries in-place. Not needed
// to clone the geometries again as we're in the same
// undoable change.
if (minx != null || miny != null)
{
for (int i = 0; i < vertexArray.Length; i++)
{
Object vertex = vertexArray[i];
mxGeometry geo = model.GetGeometry(vertex);
if (geo != null)
{
if (minx != null)
{
geo.X -= ((double) minx) - 1;
}
if (miny != null)
{
geo.Y -= ((double) miny) - 1;
}
}
}
}
}
finally
{
model.EndUpdate();
}
}
/// <summary>
/// Takes the displacements calculated for each cell and applies them to the
/// local cache of cell positions. Limits the displacement to the current
/// temperature.
/// </summary>
protected void calcPositions()
{
for (int index = 0; index < vertexArray.Length; index++)
{
if (isMoveable[index])
{
// Get the distance of displacement for this node for this
// iteration
double deltaLength = Math.Sqrt(dispX[index] * dispX[index]
+ dispY[index] * dispY[index]);
if (deltaLength < 0.001)
{
deltaLength = 0.001;
}
// Scale down by the current temperature if less than the
// displacement distance
double newXDisp = dispX[index] / deltaLength
* Math.Min(deltaLength, temperature);
double newYDisp = dispY[index] / deltaLength
* Math.Min(deltaLength, temperature);
// reset displacements
dispX[index] = 0;
dispY[index] = 0;
// Update the cached cell locations
cellLocation[index][0] += newXDisp;
cellLocation[index][1] += newYDisp;
}
}
}
/// <summary>
/// Calculates the attractive forces between all laid out nodes linked by
/// edges
/// </summary>
protected void calcAttraction()
{
// Check the neighbours of each vertex and calculate the attractive
// force of the edge connecting them
for (int i = 0; i < vertexArray.Length; i++)
{
for (int k = 0; k < neighbours[i].Length; k++)
{
// Get the index of the othe cell in the vertex array
int j = neighbours[i][k];
// Do not proceed self-loops
if (i != j)
{
double xDelta = cellLocation[i][0] - cellLocation[j][0];
double yDelta = cellLocation[i][1] - cellLocation[j][1];
// The distance between the nodes
double deltaLengthSquared = xDelta * xDelta + yDelta
* yDelta - radiusSquared[i] - radiusSquared[j];
if (deltaLengthSquared < minDistanceLimitSquared)
{
deltaLengthSquared = minDistanceLimitSquared;
}
double deltaLength = Math.Sqrt(deltaLengthSquared);
double force = (deltaLengthSquared) / forceConstant;
double displacementX = (xDelta / deltaLength) * force;
double displacementY = (yDelta / deltaLength) * force;
if (isMoveable[i])
{
this.dispX[i] -= displacementX;
this.dispY[i] -= displacementY;
}
if (isMoveable[j])
{
dispX[j] += displacementX;
dispY[j] += displacementY;
}
}
}
}
}
/// <summary>
/// Calculates the repulsive forces between all laid out nodes
/// </summary>
protected void calcRepulsion()
{
int vertexCount = vertexArray.Length;
for (int i = 0; i < vertexCount; i++)
{
for (int j = i; j < vertexCount; j++)
{
// Exits if the layout is no longer allowed to run
if (!allowedToRun)
{
return;
}
if (j != i)
{
double xDelta = cellLocation[i][0] - cellLocation[j][0];
double yDelta = cellLocation[i][1] - cellLocation[j][1];
if (xDelta == 0)
{
xDelta = 0.01 + random.NextDouble();
}
if (yDelta == 0)
{
yDelta = 0.01 + random.NextDouble();
}
// Distance between nodes
double deltaLength = Math.Sqrt((xDelta * xDelta)
+ (yDelta * yDelta));
double deltaLengthWithRadius = deltaLength - radius[i]
- radius[j];
if (deltaLengthWithRadius < minDistanceLimit)
{
deltaLengthWithRadius = minDistanceLimit;
}
double force = forceConstantSquared / deltaLengthWithRadius;
double displacementX = (xDelta / deltaLength) * force;
double displacementY = (yDelta / deltaLength) * force;
if (isMoveable[i])
{
dispX[i] += displacementX;
dispY[i] += displacementY;
}
if (isMoveable[j])
{
dispX[j] -= displacementX;
dispY[j] -= displacementY;
}
}
}
}
}
}
}
| |
// 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.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
namespace Microsoft.Tools.ServiceModel.Svcutil
{
internal class TargetFrameworkHelper
{
public static ReadOnlyDictionary<Version, Version> NetStandardToNetCoreVersionMap { get; } = new ReadOnlyDictionary<Version, Version>(new SortedDictionary<Version, Version>
{
// Service Model requires netstandard1.3 so it is the minimum version that will work.
{new Version("1.3"), new Version("1.0") },
{new Version("1.4"), new Version("1.0") },
{new Version("1.5"), new Version("1.0") },
{new Version("1.6"), new Version("1.0") },
{new Version("1.6.1"), new Version("1.1") },
{new Version("2.0"), new Version("2.0") }
});
internal static SortedDictionary<Version, List<ProjectDependency>> NetCoreVersionReferenceTable = new SortedDictionary<Version, List<ProjectDependency>>
{
{new Version("1.0"), new List<ProjectDependency> {
ProjectDependency.FromPackage("System.ServiceModel.Duplex", "4.0.*" ),
ProjectDependency.FromPackage("System.ServiceModel.Http", "4.1.*" ),
ProjectDependency.FromPackage("System.ServiceModel.NetTcp", "4.1.*" ),
ProjectDependency.FromPackage("System.ServiceModel.Security", "4.0.*"),
ProjectDependency.FromPackage("System.Xml.XmlSerializer", "4.0.*" ),
} },
{new Version("1.1"), new List<ProjectDependency> {
ProjectDependency.FromPackage("System.ServiceModel.Duplex", "4.3.*" ),
ProjectDependency.FromPackage("System.ServiceModel.Http", "4.3.*" ),
ProjectDependency.FromPackage("System.ServiceModel.NetTcp", "4.3.*" ),
ProjectDependency.FromPackage("System.ServiceModel.Security", "4.3.*"),
ProjectDependency.FromPackage("System.Xml.XmlSerializer", "4.3.*" ),
} },
{new Version("2.0"), new List<ProjectDependency> {
ProjectDependency.FromPackage("System.ServiceModel.Duplex", "4.4.*" ),
ProjectDependency.FromPackage("System.ServiceModel.Http", "4.4.*" ),
ProjectDependency.FromPackage("System.ServiceModel.NetTcp", "4.4.*" ),
ProjectDependency.FromPackage("System.ServiceModel.Security", "4.4.*"),
} },
{new Version("5.0"), new List<ProjectDependency> {
ProjectDependency.FromPackage("System.ServiceModel.Duplex", "4.7.*" ),
ProjectDependency.FromPackage("System.ServiceModel.Http", "4.7.*" ),
ProjectDependency.FromPackage("System.ServiceModel.NetTcp", "4.7.*" ),
ProjectDependency.FromPackage("System.ServiceModel.Security", "4.7.*"),
} }
};
internal static List<ProjectDependency> FullFrameworkReferences = new List<ProjectDependency>()
{
ProjectDependency.FromAssembly("System.ServiceModel"),
};
internal static List<ProjectDependency> ServiceModelPackages = new List<ProjectDependency>()
{
ProjectDependency.FromPackage("System.ServiceModel.Duplex", "*"),
ProjectDependency.FromPackage("System.ServiceModel.Http", "*" ),
ProjectDependency.FromPackage("System.ServiceModel.NetTcp", "*"),
ProjectDependency.FromPackage("System.ServiceModel.Primitives", "*"),
ProjectDependency.FromPackage("System.ServiceModel", "System.ServiceModel.Primitives", "*"),
ProjectDependency.FromPackage("System.Private.ServiceModel", "*"),
ProjectDependency.FromPackage("System.ServiceModel.Security", "*"),
ProjectDependency.FromPackage("System.Xml.XmlSerializer", "*"),
};
public static Version MinSupportedNetFxVersion { get; } = new Version("4.5");
public static Version MinSupportedNetStandardVersion { get; } = NetStandardToNetCoreVersionMap.Keys.First();
public static Version MinSupportedNetCoreAppVersion { get; } = NetStandardToNetCoreVersionMap.Values.First();
public static IEnumerable<ProjectDependency> GetWcfProjectReferences(string targetFramework)
{
IEnumerable<ProjectDependency> dependencies = null;
if (IsSupportedFramework(targetFramework, out var frameworkInfo))
{
if (frameworkInfo.IsDnx)
{
if (NetCoreVersionReferenceTable.ContainsKey(frameworkInfo.Version))
{
dependencies = NetCoreVersionReferenceTable[frameworkInfo.Version];
}
else
{
dependencies = NetCoreVersionReferenceTable.Last().Value;
}
}
else
{
dependencies = FullFrameworkReferences;
}
}
return dependencies;
}
/// <summary>
/// From the specified framework collection, find the the framework that would work best for Svcutil (if any).
/// </summary>
public static string GetBestFitTargetFramework(IEnumerable<string> targetFrameworks)
{
string targetFramework = string.Empty;
FrameworkInfo fxInfo;
if (targetFrameworks != null)
{
targetFramework = targetFrameworks.FirstOrDefault((framework) => IsSupportedFramework(framework, out fxInfo) && fxInfo.IsKnownDnx);
if (targetFramework == null)
{
targetFramework = targetFrameworks.FirstOrDefault((framework) => IsSupportedFramework(framework, out fxInfo) && fxInfo.IsDnx);
if (targetFramework == null)
{
targetFramework = targetFrameworks.FirstOrDefault((framework) => IsSupportedFramework(framework, out fxInfo));
if (targetFramework == null)
{
targetFramework = targetFrameworks.FirstOrDefault() ?? string.Empty;
}
}
}
}
return targetFramework;
}
public static Version GetLowestNetCoreVersion(IEnumerable<string> targetFrameworks)
{
Version targetVersion = null;
foreach (string targetFramework in targetFrameworks)
{
if (TargetFrameworkHelper.IsSupportedFramework(targetFramework, out var frameworkInfo) && frameworkInfo.IsDnx)
{
Version netCoreVersion;
if (frameworkInfo.IsKnownDnx)
{
netCoreVersion = frameworkInfo.Name == FrameworkInfo.Netstandard ?
TargetFrameworkHelper.NetStandardToNetCoreVersionMap[frameworkInfo.Version] :
frameworkInfo.Version;
}
else
{
// this is a target framework not yet known to the tool, use the latest known netcore version.
netCoreVersion = TargetFrameworkHelper.NetStandardToNetCoreVersionMap.Values.LastOrDefault();
}
if (targetVersion == null || targetVersion > netCoreVersion)
{
targetVersion = netCoreVersion;
}
}
}
return targetVersion;
}
public static FrameworkInfo GetValidFrameworkInfo(string targetFramework)
{
if (!IsSupportedFramework(targetFramework, out FrameworkInfo frameworkInfo))
{
throw new Exception(string.Format(CultureInfo.CurrentCulture, Shared.Resources.ErrorNotSupportedTargetFrameworkFormat,
targetFramework, MinSupportedNetCoreAppVersion, MinSupportedNetStandardVersion, MinSupportedNetFxVersion));
}
return frameworkInfo;
}
public static bool IsSupportedFramework(string fullFrameworkName, out FrameworkInfo frameworkInfo)
{
bool isSupported = false;
if (FrameworkInfo.TryParse(fullFrameworkName, out frameworkInfo))
{
isSupported = (frameworkInfo.Name == FrameworkInfo.Netstandard && frameworkInfo.Version >= MinSupportedNetStandardVersion) ||
(frameworkInfo.Name == FrameworkInfo.Netcoreapp && frameworkInfo.Version >= MinSupportedNetCoreAppVersion) ||
(frameworkInfo.Name == FrameworkInfo.Netfx && frameworkInfo.Version >= MinSupportedNetFxVersion);
}
return isSupported;
}
public static bool ContainsFullFrameworkTarget(IEnumerable<string> targetFrameworks)
{
foreach (string targetFramework in targetFrameworks)
{
if (TargetFrameworkHelper.IsSupportedFramework(targetFramework, out var frameworkInfo) && !frameworkInfo.IsDnx)
{
return true;
}
}
return false;
}
}
}
| |
// Copyright (c) 2012, Event Store LLP
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the Event Store LLP nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Threading;
using EventStore.Projections.Core.Services.Management;
using EventStore.Projections.Core.Services.Processing;
using EventStore.Projections.Core.v8;
using NUnit.Framework;
using EventStore.Projections.Core.Services;
namespace EventStore.Projections.Core.Tests.Services.projections_manager.v8
{
[TestFixture]
public class when_creating_v8_projection
{
private ProjectionStateHandlerFactory _stateHandlerFactory;
[SetUp]
public void Setup()
{
_stateHandlerFactory = new ProjectionStateHandlerFactory();
}
[Test, Category("v8")]
public void api_can_be_used()
{
var ver = Js1.ApiVersion();
Console.WriteLine(ver);
}
[Test, Category("v8")]
public void api_can_be_used2()
{
var ver = Js1.ApiVersion();
Console.WriteLine(ver);
}
[Test, Category("v8")]
public void it_can_be_created()
{
using (_stateHandlerFactory.Create("JS", @""))
{
}
}
[Test, Category("v8")]
public void it_can_log_messages()
{
string m = null;
using (_stateHandlerFactory.Create("JS", @"log(""Message1"");", logger: s => m = s))
{
}
Assert.AreEqual("Message1", m);
}
[Test, Category("v8"), ExpectedException(typeof(Js1Exception), ExpectedMessage = "SyntaxError:", MatchType = MessageMatch.StartsWith)]
public void js_syntax_errors_are_reported()
{
string m = null;
using (_stateHandlerFactory.Create("JS", @"log(1;", logger: s => m = s))
{
}
}
[Test, Category("v8"), ExpectedException(typeof(Js1Exception), ExpectedMessage = "123")]
public void js_exceptions_errors_are_reported()
{
string m = null;
using (_stateHandlerFactory.Create("JS", @"throw 123;", logger: s => m = s))
{
}
}
[Test, Category("v8"), ExpectedException(typeof(Js1Exception), ExpectedMessage = "Terminated", MatchType = MessageMatch.Contains)]
public void long_compilation_times_out()
{
string m = null;
using (_stateHandlerFactory.Create("JS",
@"
var i = 0;
while (true) i++;
",
logger: s => m = s,
cancelCallbackFactory: (timeout, action) => ThreadPool.QueueUserWorkItem(state =>
{
Console.WriteLine("Calling a callback in " + timeout + "ms");
Thread.Sleep(timeout);
action();
})))
{
}
}
[Test, Category("v8"), ExpectedException(typeof(Js1Exception), ExpectedMessage = "Terminated", MatchType = MessageMatch.Contains)]
public void long_execution_times_out()
{
//string m = null;
using (var h = _stateHandlerFactory.Create("JS",
@"
fromAll().when({
$any: function (s, e) {
log('1');
var i = 0;
while (true) i++;
}
});
",
logger: Console.WriteLine,
cancelCallbackFactory: (timeout, action) => ThreadPool.QueueUserWorkItem(state =>
{
Console.WriteLine("Calling a callback in " + timeout + "ms");
Thread.Sleep(timeout);
action();
})))
{
h.Initialize();
string newState;
EmittedEventEnvelope[] emittedevents;
h.ProcessEvent(
"partition", CheckpointTag.FromPosition(0, 100, 50), "stream", "event", "", Guid.NewGuid(), 1, "", "{}",
out newState, out emittedevents);
}
}
[Test, Category("v8"), ExpectedException(typeof(Js1Exception), ExpectedMessage = "Terminated", MatchType = MessageMatch.Contains)]
public void long_post_processing_times_out()
{
//string m = null;
using (var h = _stateHandlerFactory.Create("JS",
@"
fromAll().when({
$any: function (s, e) {
return {};
}
})
.transformBy(function(s){
log('1');
var i = 0;
while (true) i++;
});
",
logger: Console.WriteLine,
cancelCallbackFactory: (timeout, action) => ThreadPool.QueueUserWorkItem(state =>
{
Console.WriteLine("Calling a callback in " + timeout + "ms");
Thread.Sleep(timeout);
action();
})))
{
h.Initialize();
string newState;
EmittedEventEnvelope[] emittedevents;
h.ProcessEvent(
"partition", CheckpointTag.FromPosition(0, 100, 50), "stream", "event", "", Guid.NewGuid(), 1, "", "{}",
out newState, out emittedevents);
h.TransformStateToResult();
}
}
[Test, Explicit, Category("v8"), Category("Manual")]
public void long_execution_times_out_many()
{
//string m = null;
for (var i = 0; i < 10; i++)
{
Console.WriteLine(i);
try
{
using (var h = _stateHandlerFactory.Create(
"JS", @"
fromAll().when({
$any: function (s, e) {
log('1');
var i = 0;
while (true) i++;
}
});
", logger: Console.WriteLine,
cancelCallbackFactory: (timeout, action) => ThreadPool.QueueUserWorkItem(
state =>
{
Console.WriteLine("Calling a callback in " + timeout + "ms");
Thread.Sleep(timeout);
action();
})))
{
h.Initialize();
string newState;
EmittedEventEnvelope[] emittedevents;
h.ProcessEvent(
"partition", CheckpointTag.FromPosition(0, 100, 50), "stream", "event", "", Guid.NewGuid(), 1,
"", "{}", out newState, out emittedevents);
}
}
catch (Js1Exception)
{
}
}
Assert.Pass();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
#if LEGACYTELEMETRY
using Microsoft.PowerShell.Telemetry.Internal;
#endif
using Dbg = System.Management.Automation.Diagnostics;
#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings
namespace System.Management.Automation.Runspaces
{
/// <summary>
/// Runspaces is base class for different kind of Runspaces.
/// </summary>
/// <remarks>There should be a class derived from it for each type of
/// Runspace. Types of Runspace which we support are Local, X-AppDomain,
/// X-Process and X-Machine.</remarks>
internal abstract class RunspaceBase : Runspace
{
#region constructors
/// <summary>
/// Construct an instance of an Runspace using a custom
/// implementation of PSHost.
/// </summary>
/// <param name="host">The explicit PSHost implementation.</param>
/// <exception cref="System.ArgumentNullException">
/// Host is null.
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// host is null.
/// </exception>
protected RunspaceBase(PSHost host)
{
if (host == null)
{
throw PSTraceSource.NewArgumentNullException("host");
}
InitialSessionState = InitialSessionState.CreateDefault();
Host = host;
}
/// <summary>
/// Construct an instance of an Runspace using a custom
/// implementation of PSHost.
/// </summary>
/// <param name="host">The explicit PSHost implementation.</param>
/// <exception cref="System.ArgumentNullException">
/// Host is null.
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// host is null.
/// </exception>
/// <param name="initialSessionState">
/// configuration information for this runspace instance.
/// </param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "OK to call ThreadOptions")]
protected RunspaceBase(PSHost host, InitialSessionState initialSessionState)
{
if (host == null)
{
throw PSTraceSource.NewArgumentNullException("host");
}
if (initialSessionState == null)
{
throw PSTraceSource.NewArgumentNullException("initialSessionState");
}
Host = host;
InitialSessionState = initialSessionState.Clone();
this.ThreadOptions = initialSessionState.ThreadOptions;
#if !CORECLR // No ApartmentState In CoreCLR
this.ApartmentState = initialSessionState.ApartmentState;
#endif
}
/// <summary>
/// Construct an instance of an Runspace using a custom
/// implementation of PSHost.
/// </summary>
/// <param name="host">
/// The explicit PSHost implementation
/// </param>
/// <param name="initialSessionState">
/// configuration information for this runspace instance.
/// </param>
/// <param name="suppressClone">
/// If true, don't make a copy of the initial session state object.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Host is null.
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// host is null.
/// </exception>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "OK to call ThreadOptions")]
protected RunspaceBase(PSHost host, InitialSessionState initialSessionState, bool suppressClone)
{
if (host == null)
{
throw PSTraceSource.NewArgumentNullException("host");
}
if (initialSessionState == null)
{
throw PSTraceSource.NewArgumentNullException("initialSessionState");
}
Host = host;
if (suppressClone)
{
InitialSessionState = initialSessionState;
}
else
{
InitialSessionState = initialSessionState.Clone();
}
this.ThreadOptions = initialSessionState.ThreadOptions;
#if !CORECLR // No ApartmentState In CoreCLR
this.ApartmentState = initialSessionState.ApartmentState;
#endif
}
/// <summary>
/// The host implemented PSHost interface.
/// </summary>
protected PSHost Host { get; }
/// <summary>
/// InitialSessionState information for this runspace.
/// </summary>
public override InitialSessionState InitialSessionState { get; }
#endregion constructors
#region properties
/// <summary>
/// Return version of this runspace.
/// </summary>
public override Version Version { get; } = PSVersionInfo.PSVersion;
private RunspaceStateInfo _runspaceStateInfo = new RunspaceStateInfo(RunspaceState.BeforeOpen);
/// <summary>
/// Retrieve information about current state of the runspace.
/// </summary>
public override RunspaceStateInfo RunspaceStateInfo
{
get
{
lock (SyncRoot)
{
// Do not return internal state.
return _runspaceStateInfo.Clone();
}
}
}
/// <summary>
/// Gets the current availability of the Runspace.
/// </summary>
public override RunspaceAvailability RunspaceAvailability
{
get { return _runspaceAvailability; }
protected set { _runspaceAvailability = value; }
}
private RunspaceAvailability _runspaceAvailability = RunspaceAvailability.None;
/// <summary>
/// Object used for synchronization.
/// </summary>
protected internal object SyncRoot { get; } = new object();
/// <summary>
/// Information about the computer where this runspace is created.
/// </summary>
public override RunspaceConnectionInfo ConnectionInfo
{
get
{
// null refers to local case for path
return null;
}
}
/// <summary>
/// Original Connection Info that the user passed.
/// </summary>
public override RunspaceConnectionInfo OriginalConnectionInfo
{
get { return null; }
}
#endregion properties
#region Open
/// <summary>
/// Open the runspace synchronously.
/// </summary>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is not BeforeOpen
/// </exception>
public override void Open()
{
CoreOpen(true);
}
/// <summary>
/// Open the runspace Asynchronously.
/// </summary>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is not BeforeOpen
/// </exception>
public override void OpenAsync()
{
CoreOpen(false);
}
/// <summary>
/// Opens the runspace.
/// </summary>
/// <param name="syncCall">If true runspace is opened synchronously
/// else runspaces is opened asynchronously
/// </param>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is not BeforeOpen
/// </exception>
private void CoreOpen(bool syncCall)
{
bool etwEnabled = RunspaceEventSource.Log.IsEnabled();
if (etwEnabled) RunspaceEventSource.Log.OpenRunspaceStart();
lock (SyncRoot)
{
// Call fails if RunspaceState is not BeforeOpen.
if (RunspaceState != RunspaceState.BeforeOpen)
{
InvalidRunspaceStateException e =
new InvalidRunspaceStateException
(
StringUtil.Format(RunspaceStrings.CannotOpenAgain, new object[] { RunspaceState.ToString() }),
RunspaceState,
RunspaceState.BeforeOpen
);
throw e;
}
SetRunspaceState(RunspaceState.Opening);
}
// Raise event outside the lock
RaiseRunspaceStateEvents();
OpenHelper(syncCall);
if (etwEnabled) RunspaceEventSource.Log.OpenRunspaceStop();
#if LEGACYTELEMETRY
// We report startup telementry when opening the runspace - because this is the first time
// we are really using PowerShell. This isn't the cleanest place though, because
// sometimes there are many runspaces created - the callee ensures telemetry is only
// reported once. Note that if the host implements IHostProvidesTelemetryData, we rely
// on the host calling ReportStartupTelemetry.
if (!(this.Host is IHostProvidesTelemetryData))
{
TelemetryAPI.ReportStartupTelemetry(null);
}
#endif
}
/// <summary>
/// Derived class's open implementation.
/// </summary>
protected abstract void OpenHelper(bool syncCall);
#endregion open
#region close
/// <summary>
/// Close the runspace synchronously.
/// </summary>
/// <remarks>
/// Attempts to execute pipelines after a call to close will fail.
/// </remarks>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is BeforeOpen or Opening
/// </exception>
public override void Close()
{
CoreClose(true);
}
/// <summary>
/// Close the runspace Asynchronously.
/// </summary>
/// <remarks>
/// Attempts to execute pipelines after a call to
/// close will fail.
/// </remarks>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is BeforeOpen or Opening
/// </exception>
public override void CloseAsync()
{
CoreClose(false);
}
/// <summary>
/// Close the runspace.
/// </summary>
/// <param name="syncCall">If true runspace is closed synchronously
/// else runspaces is closed asynchronously
/// </param>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is BeforeOpen or Opening
/// </exception>
/// <exception cref="InvalidOperationException">
/// If SessionStateProxy has some method call in progress
/// </exception>
private void CoreClose(bool syncCall)
{
bool alreadyClosing = false;
lock (SyncRoot)
{
if (RunspaceState == RunspaceState.Closed ||
RunspaceState == RunspaceState.Broken)
{
return;
}
else if (RunspaceState == RunspaceState.BeforeOpen)
{
SetRunspaceState(RunspaceState.Closing, null);
SetRunspaceState(RunspaceState.Closed, null);
RaiseRunspaceStateEvents();
return;
}
else if (RunspaceState == RunspaceState.Opening)
{
// Wait till the runspace is opened - This is set in DoOpenHelper()
// Release the lock before we wait
Monitor.Exit(SyncRoot);
try
{
RunspaceOpening.Wait();
}
finally
{
// Acquire the lock before we carry on with the rest operations
Monitor.Enter(SyncRoot);
}
}
if (_bSessionStateProxyCallInProgress)
{
throw PSTraceSource.NewInvalidOperationException(RunspaceStrings.RunspaceCloseInvalidWhileSessionStateProxy);
}
if (RunspaceState == RunspaceState.Closing)
{
alreadyClosing = true;
}
else
{
if (RunspaceState != RunspaceState.Opened)
{
InvalidRunspaceStateException e =
new InvalidRunspaceStateException
(
StringUtil.Format(RunspaceStrings.RunspaceNotInOpenedState, RunspaceState.ToString()),
RunspaceState,
RunspaceState.Opened
);
throw e;
}
SetRunspaceState(RunspaceState.Closing);
}
}
if (alreadyClosing)
{
// Already closing is set to true if Runspace is already
// in closing. In this case wait for runspace to close.
// This can happen in two scenarios:
// 1) User calls Runspace.Close from two threads.
// 2) In remoting, some error from data structure handler layer can start
// runspace closure. At the same time, user can call
// remove runspace.
//
if (syncCall)
{
WaitForFinishofPipelines();
}
return;
}
// Raise Event outside the lock
RaiseRunspaceStateEvents();
// Call the derived class implementation to do the actual work
CloseHelper(syncCall);
}
/// <summary>
/// Derived class's close implementation.
/// </summary>
/// <param name="syncCall">If true runspace is closed synchronously
/// else runspaces is closed asynchronously
/// </param>
protected abstract void CloseHelper(bool syncCall);
#endregion close
#region Disconnect-Connect
/// <summary>
/// Disconnects the runspace synchronously.
/// </summary>
public override void Disconnect()
{
//
// Disconnect operation is not supported on local runspaces.
//
throw new InvalidRunspaceStateException(
RunspaceStrings.DisconnectNotSupported);
}
/// <summary>
/// Disconnects the runspace asynchronously.
/// </summary>
public override void DisconnectAsync()
{
//
// Disconnect operation is not supported on local runspaces.
//
throw new InvalidRunspaceStateException(
RunspaceStrings.DisconnectNotSupported);
}
/// <summary>
/// Connects a runspace to its remote counterpart synchronously.
/// </summary>
public override void Connect()
{
//
// Connect operation is not supported on local runspaces.
//
throw new InvalidRunspaceStateException(
RunspaceStrings.ConnectNotSupported);
}
/// <summary>
/// Connects a runspace to its remote counterpart asynchronously.
/// </summary>
public override void ConnectAsync()
{
//
// Connect operation is not supported on local runspaces.
//
throw new InvalidRunspaceStateException(
RunspaceStrings.ConnectNotSupported);
}
/// <summary>
/// Creates a pipeline object in the Disconnected state.
/// </summary>
/// <returns>Pipeline.</returns>
public override Pipeline CreateDisconnectedPipeline()
{
//
// Disconnect-Connect is not supported on local runspaces.
//
throw new InvalidRunspaceStateException(
RunspaceStrings.DisconnectConnectNotSupported);
}
/// <summary>
/// Creates a powershell object in the Disconnected state.
/// </summary>
/// <returns>PowerShell.</returns>
public override PowerShell CreateDisconnectedPowerShell()
{
//
// Disconnect-Connect is not supported on local runspaces.
//
throw new InvalidRunspaceStateException(
RunspaceStrings.DisconnectConnectNotSupported);
}
/// <summary>
/// Returns Runspace capabilities.
/// </summary>
/// <returns>RunspaceCapability.</returns>
public override RunspaceCapability GetCapabilities()
{
return RunspaceCapability.Default;
}
#endregion
#region CreatePipeline
/// <summary>
/// Create an empty pipeline.
/// </summary>
/// <returns>An empty pipeline.</returns>
public override Pipeline CreatePipeline()
{
return CoreCreatePipeline(null, false, false);
}
/// <summary>
/// Create a pipeline from a command string.
/// </summary>
/// <param name="command">A valid command string.</param>
/// <returns>
/// A pipeline pre-filled with Commands specified in commandString.
/// </returns>
/// <exception cref="ArgumentNullException">
/// command is null
/// </exception>
public override Pipeline CreatePipeline(string command)
{
if (command == null)
{
throw PSTraceSource.NewArgumentNullException("command");
}
return CoreCreatePipeline(command, false, false);
}
/// <summary>
/// Create a pipeline from a command string.
/// </summary>
/// <param name="command">A valid command string.</param>
/// <param name="addToHistory">If true command is added to history.</param>
/// <returns>
/// A pipeline pre-filled with Commands specified in commandString.
/// </returns>
/// <exception cref="ArgumentNullException">
/// command is null
/// </exception>
public override Pipeline CreatePipeline(string command, bool addToHistory)
{
if (command == null)
{
throw PSTraceSource.NewArgumentNullException("command");
}
return CoreCreatePipeline(command, addToHistory, false);
}
/// <summary>
/// Creates a nested pipeline.
/// </summary>
/// <remarks>
/// Nested pipelines are needed for nested prompt scenario. Nested
/// prompt requires that we execute new pipelines( child pipelines)
/// while current pipeline (lets call it parent pipeline) is blocked.
/// </remarks>
public override Pipeline CreateNestedPipeline()
{
return CoreCreatePipeline(null, false, true);
}
/// <summary>
/// Creates a nested pipeline.
/// </summary>
/// <param name="command">A valid command string.</param>
/// <param name="addToHistory">If true command is added to history.</param>
/// <returns>
/// A pipeline pre-filled with Commands specified in commandString.
/// </returns>
/// <exception cref="ArgumentNullException">
/// command is null
/// </exception>
public override Pipeline CreateNestedPipeline(string command, bool addToHistory)
{
if (command == null)
{
throw PSTraceSource.NewArgumentNullException("command");
}
return CoreCreatePipeline(command, addToHistory, true);
}
/// <summary>
/// Create a pipeline from a command string.
/// </summary>
/// <param name="command">A valid command string or string.Empty.</param>
/// <param name="addToHistory">If true command is added to history.</param>
/// <param name="isNested">True for nested pipeline.</param>
/// <returns>
/// A pipeline pre-filled with Commands specified in commandString.
/// </returns>
protected abstract Pipeline CoreCreatePipeline(string command, bool addToHistory, bool isNested);
#endregion CreatePipeline
#region state change event
/// <summary>
/// Event raised when RunspaceState changes.
/// </summary>
public override event EventHandler<RunspaceStateEventArgs> StateChanged;
/// <summary>
/// Event raised when the availability of the Runspace changes.
/// </summary>
public override event EventHandler<RunspaceAvailabilityEventArgs> AvailabilityChanged;
/// <summary>
/// Returns true if there are any subscribers to the AvailabilityChanged event.
/// </summary>
internal override bool HasAvailabilityChangedSubscribers
{
get { return this.AvailabilityChanged != null; }
}
/// <summary>
/// Raises the AvailabilityChanged event.
/// </summary>
protected override void OnAvailabilityChanged(RunspaceAvailabilityEventArgs e)
{
EventHandler<RunspaceAvailabilityEventArgs> eh = this.AvailabilityChanged;
if (eh != null)
{
try
{
eh(this, e);
}
catch (Exception)
{
}
}
}
/// <summary>
/// Retrieve the current state of the runspace.
/// <see cref="RunspaceState"/>
/// </summary>
protected RunspaceState RunspaceState
{
get
{
return _runspaceStateInfo.State;
}
}
/// <summary>
/// This is queue of all the state change event which have occured for
/// this runspace. RaiseRunspaceStateEvents raises event for each
/// item in this queue. We don't raise events from with SetRunspaceState
/// because SetRunspaceState is often called from with in the a lock.
/// Raising event with in a lock introduces chances of deadlock in GUI
/// applications.
/// </summary>
private Queue<RunspaceEventQueueItem> _runspaceEventQueue = new Queue<RunspaceEventQueueItem>();
private class RunspaceEventQueueItem
{
public RunspaceEventQueueItem(RunspaceStateInfo runspaceStateInfo, RunspaceAvailability currentAvailability, RunspaceAvailability newAvailability)
{
this.RunspaceStateInfo = runspaceStateInfo;
this.CurrentRunspaceAvailability = currentAvailability;
this.NewRunspaceAvailability = newAvailability;
}
public RunspaceStateInfo RunspaceStateInfo;
public RunspaceAvailability CurrentRunspaceAvailability;
public RunspaceAvailability NewRunspaceAvailability;
}
// This is to notify once runspace has been opened (RunspaceState.Opened)
internal ManualResetEventSlim RunspaceOpening = new ManualResetEventSlim(false);
/// <summary>
/// Set the new runspace state.
/// </summary>
/// <param name="state">The new state.</param>
/// <param name="reason">An exception indicating the state change is the
/// result of an error, otherwise; null.
/// </param>
/// <remarks>
/// Sets the internal runspace state information member variable. It also
/// adds RunspaceStateInfo to a queue.
/// RaiseRunspaceStateEvents raises event for each item in this queue.
/// </remarks>
protected void SetRunspaceState(RunspaceState state, Exception reason)
{
lock (SyncRoot)
{
if (state != RunspaceState)
{
_runspaceStateInfo = new RunspaceStateInfo(state, reason);
// Add _runspaceStateInfo to _runspaceEventQueue.
// RaiseRunspaceStateEvents will raise event for each item
// in this queue.
// Note:We are doing clone here instead of passing the member
// _runspaceStateInfo because we donot want outside
// to change our runspace state.
RunspaceAvailability previousAvailability = _runspaceAvailability;
this.UpdateRunspaceAvailability(_runspaceStateInfo.State, false);
_runspaceEventQueue.Enqueue(
new RunspaceEventQueueItem(
_runspaceStateInfo.Clone(),
previousAvailability,
_runspaceAvailability));
}
}
}
/// <summary>
/// Set the current runspace state - no error.
/// </summary>
/// <param name="state">The new state.</param>
protected void SetRunspaceState(RunspaceState state)
{
this.SetRunspaceState(state, null);
}
/// <summary>
/// Raises events for changes in runspace state.
/// </summary>
protected void RaiseRunspaceStateEvents()
{
Queue<RunspaceEventQueueItem> tempEventQueue = null;
EventHandler<RunspaceStateEventArgs> stateChanged = null;
bool hasAvailabilityChangedSubscribers = false;
lock (SyncRoot)
{
stateChanged = this.StateChanged;
hasAvailabilityChangedSubscribers = this.HasAvailabilityChangedSubscribers;
if (stateChanged != null || hasAvailabilityChangedSubscribers)
{
tempEventQueue = _runspaceEventQueue;
_runspaceEventQueue = new Queue<RunspaceEventQueueItem>();
}
else
{
// Clear the events if there are no EventHandlers. This
// ensures that events do not get called for state
// changes prior to their registration.
_runspaceEventQueue.Clear();
}
}
if (tempEventQueue != null)
{
while (tempEventQueue.Count > 0)
{
RunspaceEventQueueItem queueItem = tempEventQueue.Dequeue();
if (hasAvailabilityChangedSubscribers && queueItem.NewRunspaceAvailability != queueItem.CurrentRunspaceAvailability)
{
this.OnAvailabilityChanged(new RunspaceAvailabilityEventArgs(queueItem.NewRunspaceAvailability));
}
#pragma warning disable 56500
// Exception raised by events are not error condition for runspace
// object.
if (stateChanged != null)
{
try
{
stateChanged(this, new RunspaceStateEventArgs(queueItem.RunspaceStateInfo));
}
catch (Exception)
{
}
}
#pragma warning restore 56500
}
}
}
#endregion state change event
#region running pipeline management
/// <summary>
/// In RemoteRunspace, it is required to invoke pipeline
/// as part of open call (i.e. while state is Opening).
/// If this property is true, runspace state check is
/// not performed in AddToRunningPipelineList call.
/// </summary>
protected bool ByPassRunspaceStateCheck { get; set; }
private readonly object _pipelineListLock = new object();
/// <summary>
/// List of pipeline which are currently executing in this runspace.
/// </summary>
protected List<Pipeline> RunningPipelines { get; } = new List<Pipeline>();
/// <summary>
/// Add the pipeline to list of pipelines in execution.
/// </summary>
/// <param name="pipeline">Pipeline to add to the
/// list of pipelines in execution</param>
/// <exception cref="InvalidRunspaceStateException">
/// Thrown if the runspace is not in the Opened state.
/// <see cref="RunspaceState"/>.
/// </exception>
/// <exception cref="ArgumentNullException">Thrown if
/// <paramref name="pipeline"/> is null.
/// </exception>
internal void AddToRunningPipelineList(PipelineBase pipeline)
{
Dbg.Assert(pipeline != null, "caller should validate the parameter");
lock (_pipelineListLock)
{
if (ByPassRunspaceStateCheck == false && RunspaceState != RunspaceState.Opened)
{
InvalidRunspaceStateException e =
new InvalidRunspaceStateException
(
StringUtil.Format(RunspaceStrings.RunspaceNotOpenForPipeline, RunspaceState.ToString()),
RunspaceState,
RunspaceState.Opened
);
throw e;
}
// Add the pipeline to list of Executing pipeline.
// Note:_runningPipelines is always accessed with the lock so
// there is no need to create a synchronized version of list
RunningPipelines.Add(pipeline);
_currentlyRunningPipeline = pipeline;
}
}
/// <summary>
/// Remove the pipeline from list of pipelines in execution.
/// </summary>
/// <param name="pipeline">Pipeline to remove from the
/// list of pipelines in execution</param>
/// <exception cref="ArgumentNullException">
/// Thrown if <paramref name="pipeline"/> is null.
/// </exception>
internal void RemoveFromRunningPipelineList(PipelineBase pipeline)
{
Dbg.Assert(pipeline != null, "caller should validate the parameter");
lock (_pipelineListLock)
{
Dbg.Assert(RunspaceState != RunspaceState.BeforeOpen,
"Runspace should not be before open when pipeline is running");
// Remove the pipeline to list of Executing pipeline.
// Note:_runningPipelines is always accessed with the lock so
// there is no need to create a synchronized version of list
RunningPipelines.Remove(pipeline);
// Update the running pipeline
if (RunningPipelines.Count == 0)
{
_currentlyRunningPipeline = null;
}
else
{
_currentlyRunningPipeline = RunningPipelines[RunningPipelines.Count - 1];
}
pipeline.PipelineFinishedEvent.Set();
}
}
/// <summary>
/// Waits till all the pipelines running in the runspace have
/// finished execution.
/// </summary>
internal bool WaitForFinishofPipelines()
{
// Take a snapshot of list of active pipelines.
// Note:Before we enter to this CloseHelper routine
// CoreClose has already set the state of Runspace
// to closing. So no new pipelines can be executed on this
// runspace and so no new pipelines will be added to
// _runningPipelines. However we still need to lock because
// running pipelines can be removed from this.
PipelineBase[] runningPipelines;
lock (_pipelineListLock)
{
runningPipelines = RunningPipelines.Cast<PipelineBase>().ToArray();
}
if (runningPipelines.Length > 0)
{
WaitHandle[] waitHandles = new WaitHandle[runningPipelines.Length];
for (int i = 0; i < runningPipelines.Length; i++)
{
waitHandles[i] = runningPipelines[i].PipelineFinishedEvent;
}
#if !CORECLR // No ApartmentState.STA In CoreCLR
// WaitAll for multiple handles on a STA (single-thread apartment) thread is not supported as WaitAll will prevent the message pump to run
if (runningPipelines.Length > 1 && Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
{
// We use a worker thread to wait for all handles, and the STA thread can just wait on the worker thread -- the worker
// threads from the ThreadPool are MTA.
using (ManualResetEvent waitAllIsDone = new ManualResetEvent(false))
{
Tuple<WaitHandle[], ManualResetEvent> stateInfo = new Tuple<WaitHandle[], ManualResetEvent>(waitHandles, waitAllIsDone);
ThreadPool.QueueUserWorkItem(new WaitCallback(
delegate (object state)
{
var tuple = (Tuple<WaitHandle[], ManualResetEvent>)state;
WaitHandle.WaitAll(tuple.Item1);
tuple.Item2.Set();
}), stateInfo);
return waitAllIsDone.WaitOne();
}
}
#endif
return WaitHandle.WaitAll(waitHandles);
}
else
{
return true;
}
}
/// <summary>
/// Stops all the running pipelines.
/// </summary>
protected void StopPipelines()
{
PipelineBase[] runningPipelines;
lock (_pipelineListLock)
{
runningPipelines = RunningPipelines.Cast<PipelineBase>().ToArray();
}
if (runningPipelines.Length > 0)
{
// Start from the most recent pipeline.
for (int i = runningPipelines.Length - 1; i >= 0; i--)
{
runningPipelines[i].Stop();
}
}
}
internal bool RunActionIfNoRunningPipelinesWithThreadCheck(Action action)
{
bool ranit = false;
bool shouldRunAction = false;
lock (_pipelineListLock)
{
// If we have no running pipeline, or if the currently running pipeline is
// the same as the current thread, then execute the action.
var pipelineRunning = _currentlyRunningPipeline as PipelineBase;
if (pipelineRunning == null ||
Thread.CurrentThread.Equals(pipelineRunning.NestedPipelineExecutionThread))
{
shouldRunAction = true;
}
}
if (shouldRunAction)
{
action();
ranit = true;
}
return ranit;
}
/// <summary>
/// Gets the currently executing pipeline.
/// </summary>
/// <remarks>Internal because it is needed by invoke-history</remarks>
internal override Pipeline GetCurrentlyRunningPipeline()
{
return _currentlyRunningPipeline;
}
private Pipeline _currentlyRunningPipeline = null;
/// <summary>
/// This method stops all the pipelines which are nested
/// under specified pipeline.
/// </summary>
/// <param name="pipeline"></param>
/// <returns></returns>
internal void StopNestedPipelines(Pipeline pipeline)
{
List<Pipeline> nestedPipelines = null;
lock (_pipelineListLock)
{
// first check if this pipeline is in the list of running
// pipelines. It is possible that pipeline has already
// completed.
if (RunningPipelines.Contains(pipeline) == false)
{
return;
}
// If this pipeline is currently running pipeline,
// then it does not have nested pipelines
if (GetCurrentlyRunningPipeline() == pipeline)
{
return;
}
// Build list of nested pipelines
nestedPipelines = new List<Pipeline>();
for (int i = RunningPipelines.Count - 1; i >= 0; i--)
{
if (RunningPipelines[i] == pipeline)
break;
nestedPipelines.Add(RunningPipelines[i]);
}
}
foreach (Pipeline np in nestedPipelines)
{
try
{
np.Stop();
}
catch (InvalidPipelineStateException)
{
}
}
}
internal
void
DoConcurrentCheckAndAddToRunningPipelines(PipelineBase pipeline, bool syncCall)
{
// Concurrency check should be done under runspace lock
lock (SyncRoot)
{
if (_bSessionStateProxyCallInProgress == true)
{
throw PSTraceSource.NewInvalidOperationException(RunspaceStrings.NoPipelineWhenSessionStateProxyInProgress);
}
// Delegate to pipeline to do check if it is fine to invoke if another
// pipeline is running.
pipeline.DoConcurrentCheck(syncCall, SyncRoot, true);
// Finally add to the list of running pipelines.
AddToRunningPipelineList(pipeline);
}
}
// PowerShell support for async notifications happen through the
// CheckForInterrupts() method on ParseTreeNode. These are only called when
// the engine is active (and processing,) so the Pulse() method
// executes the equivalent of a NOP so that async events
// can be processed when the engine is idle.
internal void Pulse()
{
// If we don't already have a pipeline running, pulse the engine.
bool pipelineCreated = false;
if (GetCurrentlyRunningPipeline() == null)
{
lock (SyncRoot)
{
if (GetCurrentlyRunningPipeline() == null)
{
// This is a pipeline that does the least amount possible.
// It evaluates a constant, and results in the execution of only two parse tree nodes.
// We don't need to void it, as we aren't using the results. In addition, voiding
// (as opposed to ignoring) is 1.6x slower.
try
{
PulsePipeline = (PipelineBase)CreatePipeline("0");
PulsePipeline.IsPulsePipeline = true;
pipelineCreated = true;
}
catch (ObjectDisposedException)
{
// Ignore. The runspace is closing. The event was not processed,
// but this should not crash PowerShell.
}
}
}
}
// Invoke pipeline outside the runspace lock.
// A concurrency check will be made on the runspace before this
// pipeline is invoked.
if (pipelineCreated)
{
try
{
PulsePipeline.Invoke();
}
catch (PSInvalidOperationException)
{
// Ignore. A pipeline was created between the time
// we checked for it, and when we invoked the pipeline.
// This is unlikely, but taking a lock on the runspace
// means that OUR invoke will not be able to run.
}
catch (InvalidRunspaceStateException)
{
// Ignore. The runspace is closing. The event was not processed,
// but this should not crash PowerShell.
}
catch (ObjectDisposedException)
{
// Ignore. The runspace is closing. The event was not processed,
// but this should not crash PowerShell.
}
}
}
internal PipelineBase PulsePipeline { get; private set; }
#endregion running pipeline management
#region session state proxy
// Note: When SessionStateProxy calls are in progress,
// pipeline cannot be invoked. Also when pipeline is in
// progress, SessionStateProxy calls cannot be made.
private bool _bSessionStateProxyCallInProgress;
/// <summary>
/// This method ensures that SessionStateProxy call is allowed and if
/// allowed it sets a variable to disallow further SessionStateProxy or
/// pipeline calls.
/// </summary>
private void DoConcurrentCheckAndMarkSessionStateProxyCallInProgress()
{
lock (SyncRoot)
{
if (RunspaceState != RunspaceState.Opened)
{
InvalidRunspaceStateException e =
new InvalidRunspaceStateException
(
StringUtil.Format(RunspaceStrings.RunspaceNotInOpenedState, RunspaceState.ToString()),
RunspaceState,
RunspaceState.Opened
);
throw e;
}
if (_bSessionStateProxyCallInProgress == true)
{
throw PSTraceSource.NewInvalidOperationException(RunspaceStrings.AnotherSessionStateProxyInProgress);
}
Pipeline runningPipeline = GetCurrentlyRunningPipeline();
if (runningPipeline != null)
{
// Detect if we're running an engine pulse, or we're running a nested pipeline
// from an engine pulse
if (runningPipeline == PulsePipeline ||
(runningPipeline.IsNested && PulsePipeline != null))
{
// If so, wait and try again
// Release the lock before we wait for the pulse pipelines
Monitor.Exit(SyncRoot);
try
{
WaitForFinishofPipelines();
}
finally
{
// Acquire the lock before we carry on with the rest operations
Monitor.Enter(SyncRoot);
}
DoConcurrentCheckAndMarkSessionStateProxyCallInProgress();
return;
}
else
{
throw PSTraceSource.NewInvalidOperationException(RunspaceStrings.NoSessionStateProxyWhenPipelineInProgress);
}
}
// Now we can invoke session state proxy
_bSessionStateProxyCallInProgress = true;
}
}
/// <summary>
/// SetVariable implementation. This class does the necessary checks to ensure
/// that no pipeline or other SessionStateProxy calls are in progress.
/// It delegates to derived class worker method for actual operation.
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
internal void SetVariable(string name, object value)
{
DoConcurrentCheckAndMarkSessionStateProxyCallInProgress();
try
{
DoSetVariable(name, value);
}
finally
{
lock (SyncRoot)
{
_bSessionStateProxyCallInProgress = false;
}
}
}
/// <summary>
/// GetVariable implementation. This class does the necessary checks to ensure
/// that no pipeline or other SessionStateProxy calls are in progress.
/// It delegates to derived class worker method for actual operation.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
internal object GetVariable(string name)
{
DoConcurrentCheckAndMarkSessionStateProxyCallInProgress();
try
{
return DoGetVariable(name);
}
finally
{
lock (SyncRoot)
{
_bSessionStateProxyCallInProgress = false;
}
}
}
/// <summary>
/// Applications implementation. This class does the necessary checks to ensure
/// that no pipeline or other SessionStateProxy calls are in progress.
/// It delegates to derived class worker method for actual operation.
/// </summary>
/// <returns></returns>
internal List<string> Applications
{
get
{
DoConcurrentCheckAndMarkSessionStateProxyCallInProgress();
try
{
return DoApplications;
}
finally
{
lock (SyncRoot)
{
_bSessionStateProxyCallInProgress = false;
}
}
}
}
/// <summary>
/// Scripts implementation. This class does the necessary checks to ensure
/// that no pipeline or other SessionStateProxy calls are in progress.
/// It delegates to derived class worker method for actual operation.
/// </summary>
/// <returns></returns>
internal List<string> Scripts
{
get
{
DoConcurrentCheckAndMarkSessionStateProxyCallInProgress();
try
{
return DoScripts;
}
finally
{
lock (SyncRoot)
{
_bSessionStateProxyCallInProgress = false;
}
}
}
}
/// <summary>
/// Protected methods to be implemented by derived class.
/// This does the actual work of getting scripts.
/// </summary>
internal DriveManagementIntrinsics Drive
{
get
{
DoConcurrentCheckAndMarkSessionStateProxyCallInProgress();
try
{
return DoDrive;
}
finally
{
lock (SyncRoot)
{
_bSessionStateProxyCallInProgress = false;
}
}
}
}
/// <summary>
/// Protected methods to be implemented by derived class.
/// This does the actual work of getting scripts.
/// </summary>
public PSLanguageMode LanguageMode
{
get
{
if (RunspaceState != RunspaceState.Opened)
{
InvalidRunspaceStateException e =
new InvalidRunspaceStateException
(
StringUtil.Format(RunspaceStrings.RunspaceNotInOpenedState, RunspaceState.ToString()),
RunspaceState,
RunspaceState.Opened
);
throw e;
}
return DoLanguageMode;
}
set
{
if (RunspaceState != RunspaceState.Opened)
{
InvalidRunspaceStateException e =
new InvalidRunspaceStateException
(
StringUtil.Format(RunspaceStrings.RunspaceNotInOpenedState, RunspaceState.ToString()),
RunspaceState,
RunspaceState.Opened
);
throw e;
}
DoLanguageMode = value;
}
}
/// <summary>
/// Protected methods to be implemented by derived class.
/// This does the actual work of getting scripts.
/// </summary>
internal PSModuleInfo Module
{
get
{
DoConcurrentCheckAndMarkSessionStateProxyCallInProgress();
try
{
return DoModule;
}
finally
{
lock (SyncRoot)
{
_bSessionStateProxyCallInProgress = false;
}
}
}
}
/// <summary>
/// Protected methods to be implemented by derived class.
/// This does the actual work of getting scripts.
/// </summary>
internal PathIntrinsics PathIntrinsics
{
get
{
DoConcurrentCheckAndMarkSessionStateProxyCallInProgress();
try
{
return DoPath;
}
finally
{
lock (SyncRoot)
{
_bSessionStateProxyCallInProgress = false;
}
}
}
}
/// <summary>
/// Protected methods to be implemented by derived class.
/// This does the actual work of getting scripts.
/// </summary>
internal CmdletProviderManagementIntrinsics Provider
{
get
{
DoConcurrentCheckAndMarkSessionStateProxyCallInProgress();
try
{
return DoProvider;
}
finally
{
lock (SyncRoot)
{
_bSessionStateProxyCallInProgress = false;
}
}
}
}
/// <summary>
/// Protected methods to be implemented by derived class.
/// This does the actual work of getting scripts.
/// </summary>
internal PSVariableIntrinsics PSVariable
{
get
{
DoConcurrentCheckAndMarkSessionStateProxyCallInProgress();
try
{
return DoPSVariable;
}
finally
{
lock (SyncRoot)
{
_bSessionStateProxyCallInProgress = false;
}
}
}
}
/// <summary>
/// Protected methods to be implemented by derived class.
/// This does the actual work of getting scripts.
/// </summary>
internal CommandInvocationIntrinsics InvokeCommand
{
get
{
DoConcurrentCheckAndMarkSessionStateProxyCallInProgress();
try
{
return DoInvokeCommand;
}
finally
{
lock (SyncRoot)
{
_bSessionStateProxyCallInProgress = false;
}
}
}
}
/// <summary>
/// Protected methods to be implemented by derived class.
/// This does the actual work of getting scripts.
/// </summary>
internal ProviderIntrinsics InvokeProvider
{
get
{
DoConcurrentCheckAndMarkSessionStateProxyCallInProgress();
try
{
return DoInvokeProvider;
}
finally
{
lock (SyncRoot)
{
_bSessionStateProxyCallInProgress = false;
}
}
}
}
/// <summary>
/// Protected methods to be implemented by derived class.
/// This does the actual work of setting variable.
/// </summary>
/// <param name="name">Name of the variable to set.</param>
/// <param name="value">The value to set it to.</param>
protected abstract void DoSetVariable(string name, object value);
/// <summary>
/// Protected methods to be implemented by derived class.
/// This does the actual work of getting variable.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
protected abstract object DoGetVariable(string name);
/// <summary>
/// Protected methods to be implemented by derived class.
/// This does the actual work of getting applications.
/// </summary>
protected abstract List<string> DoApplications { get; }
/// <summary>
/// Protected methods to be implemented by derived class.
/// This does the actual work of getting scripts.
/// </summary>
protected abstract List<string> DoScripts { get; }
/// <summary>
/// Protected methods to be implemented by derived class.
/// This does the actual work of getting scripts.
/// </summary>
protected abstract DriveManagementIntrinsics DoDrive { get; }
/// <summary>
/// Protected methods to be implemented by derived class.
/// This does the actual work of getting scripts.
/// </summary>
protected abstract PSLanguageMode DoLanguageMode { get; set; }
/// <summary>
/// Protected methods to be implemented by derived class.
/// This does the actual work of getting scripts.
/// </summary>
protected abstract PSModuleInfo DoModule { get; }
/// <summary>
/// Protected methods to be implemented by derived class.
/// This does the actual work of getting scripts.
/// </summary>
protected abstract PathIntrinsics DoPath { get; }
/// <summary>
/// Protected methods to be implemented by derived class.
/// This does the actual work of getting scripts.
/// </summary>
protected abstract CmdletProviderManagementIntrinsics DoProvider { get; }
/// <summary>
/// Protected methods to be implemented by derived class.
/// This does the actual work of getting scripts.
/// </summary>
protected abstract PSVariableIntrinsics DoPSVariable { get; }
/// <summary>
/// Protected methods to be implemented by derived class.
/// This does the actual work of getting scripts.
/// </summary>
protected abstract CommandInvocationIntrinsics DoInvokeCommand { get; }
/// <summary>
/// Protected methods to be implemented by derived class.
/// This does the actual work of getting scripts.
/// </summary>
protected abstract ProviderIntrinsics DoInvokeProvider { get; }
private SessionStateProxy _sessionStateProxy;
/// <summary>
/// Returns SessionState proxy object.
/// </summary>
/// <returns></returns>
internal override SessionStateProxy GetSessionStateProxy()
{
return _sessionStateProxy ?? (_sessionStateProxy = new SessionStateProxy(this));
}
#endregion session state proxy
}
}
| |
// 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.ServiceModel.Description;
using System.Runtime.Serialization;
using Microsoft.Xml;
using System.ServiceModel.Diagnostics;
using System.Runtime;
namespace System.ServiceModel.Dispatcher
{
internal class PrimitiveOperationFormatter : IClientMessageFormatter, IDispatchMessageFormatter
{
private OperationDescription _operation;
private MessageDescription _responseMessage;
private MessageDescription _requestMessage;
private XmlDictionaryString _action;
private XmlDictionaryString _replyAction;
private ActionHeader _actionHeaderNone;
private ActionHeader _actionHeader10;
private ActionHeader _replyActionHeaderNone;
private ActionHeader _replyActionHeader10;
private XmlDictionaryString _requestWrapperName;
private XmlDictionaryString _requestWrapperNamespace;
private XmlDictionaryString _responseWrapperName;
private XmlDictionaryString _responseWrapperNamespace;
private PartInfo[] _requestParts;
private PartInfo[] _responseParts;
private PartInfo _returnPart;
private XmlDictionaryString _xsiNilLocalName;
private XmlDictionaryString _xsiNilNamespace;
public PrimitiveOperationFormatter(OperationDescription description, bool isRpc)
{
if (description == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("description");
OperationFormatter.Validate(description, isRpc, false/*isEncoded*/);
_operation = description;
_requestMessage = description.Messages[0];
if (description.Messages.Count == 2)
_responseMessage = description.Messages[1];
int stringCount = 3 + _requestMessage.Body.Parts.Count;
if (_responseMessage != null)
stringCount += 2 + _responseMessage.Body.Parts.Count;
XmlDictionary dictionary = new XmlDictionary(stringCount * 2);
_xsiNilLocalName = dictionary.Add("nil");
_xsiNilNamespace = dictionary.Add(EndpointAddressProcessor.XsiNs);
OperationFormatter.GetActions(description, dictionary, out _action, out _replyAction);
if (_requestMessage.Body.WrapperName != null)
{
_requestWrapperName = AddToDictionary(dictionary, _requestMessage.Body.WrapperName);
_requestWrapperNamespace = AddToDictionary(dictionary, _requestMessage.Body.WrapperNamespace);
}
_requestParts = AddToDictionary(dictionary, _requestMessage.Body.Parts, isRpc);
if (_responseMessage != null)
{
if (_responseMessage.Body.WrapperName != null)
{
_responseWrapperName = AddToDictionary(dictionary, _responseMessage.Body.WrapperName);
_responseWrapperNamespace = AddToDictionary(dictionary, _responseMessage.Body.WrapperNamespace);
}
_responseParts = AddToDictionary(dictionary, _responseMessage.Body.Parts, isRpc);
if (_responseMessage.Body.ReturnValue != null && _responseMessage.Body.ReturnValue.Type != typeof(void))
{
_returnPart = AddToDictionary(dictionary, _responseMessage.Body.ReturnValue, isRpc);
}
}
}
private ActionHeader ActionHeaderNone
{
get
{
if (_actionHeaderNone == null)
{
_actionHeaderNone =
ActionHeader.Create(_action, AddressingVersion.None);
}
return _actionHeaderNone;
}
}
private ActionHeader ActionHeader10
{
get
{
if (_actionHeader10 == null)
{
_actionHeader10 =
ActionHeader.Create(_action, AddressingVersion.WSAddressing10);
}
return _actionHeader10;
}
}
private ActionHeader ReplyActionHeaderNone
{
get
{
if (_replyActionHeaderNone == null)
{
_replyActionHeaderNone =
ActionHeader.Create(_replyAction, AddressingVersion.None);
}
return _replyActionHeaderNone;
}
}
private ActionHeader ReplyActionHeader10
{
get
{
if (_replyActionHeader10 == null)
{
_replyActionHeader10 =
ActionHeader.Create(_replyAction, AddressingVersion.WSAddressing10);
}
return _replyActionHeader10;
}
}
private static XmlDictionaryString AddToDictionary(XmlDictionary dictionary, string s)
{
XmlDictionaryString dictionaryString;
if (!dictionary.TryLookup(s, out dictionaryString))
{
dictionaryString = dictionary.Add(s);
}
return dictionaryString;
}
private static PartInfo[] AddToDictionary(XmlDictionary dictionary, MessagePartDescriptionCollection parts, bool isRpc)
{
PartInfo[] partInfos = new PartInfo[parts.Count];
for (int i = 0; i < parts.Count; i++)
{
partInfos[i] = AddToDictionary(dictionary, parts[i], isRpc);
}
return partInfos;
}
private ActionHeader GetActionHeader(AddressingVersion addressing)
{
if (_action == null)
{
return null;
}
if (addressing == AddressingVersion.WSAddressing10)
{
return ActionHeader10;
}
else if (addressing == AddressingVersion.None)
{
return ActionHeaderNone;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(string.Format(SRServiceModel.AddressingVersionNotSupported, addressing)));
}
}
private ActionHeader GetReplyActionHeader(AddressingVersion addressing)
{
if (_replyAction == null)
{
return null;
}
if (addressing == AddressingVersion.WSAddressing10)
{
return ReplyActionHeader10;
}
else if (addressing == AddressingVersion.None)
{
return ReplyActionHeaderNone;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(string.Format(SRServiceModel.AddressingVersionNotSupported, addressing)));
}
}
private static string GetArrayItemName(Type type)
{
switch (type.GetTypeCode())
{
case TypeCode.Boolean:
return "boolean";
case TypeCode.DateTime:
return "dateTime";
case TypeCode.Decimal:
return "decimal";
case TypeCode.Int32:
return "int";
case TypeCode.Int64:
return "long";
case TypeCode.Single:
return "float";
case TypeCode.Double:
return "double";
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.SFxInvalidUseOfPrimitiveOperationFormatter));
}
}
private static PartInfo AddToDictionary(XmlDictionary dictionary, MessagePartDescription part, bool isRpc)
{
Type type = part.Type;
XmlDictionaryString itemName = null;
XmlDictionaryString itemNamespace = null;
if (type.IsArray && type != typeof(byte[]))
{
const string ns = "http://schemas.microsoft.com/2003/10/Serialization/Arrays";
string name = GetArrayItemName(type.GetElementType());
itemName = AddToDictionary(dictionary, name);
itemNamespace = AddToDictionary(dictionary, ns);
}
return new PartInfo(part,
AddToDictionary(dictionary, part.Name),
AddToDictionary(dictionary, isRpc ? string.Empty : part.Namespace),
itemName, itemNamespace);
}
public static bool IsContractSupported(OperationDescription description)
{
if (description == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("description");
OperationDescription operation = description;
MessageDescription requestMessage = description.Messages[0];
MessageDescription responseMessage = null;
if (description.Messages.Count == 2)
responseMessage = description.Messages[1];
if (requestMessage.Headers.Count > 0)
return false;
if (requestMessage.Properties.Count > 0)
return false;
if (requestMessage.IsTypedMessage)
return false;
if (responseMessage != null)
{
if (responseMessage.Headers.Count > 0)
return false;
if (responseMessage.Properties.Count > 0)
return false;
if (responseMessage.IsTypedMessage)
return false;
}
if (!AreTypesSupported(requestMessage.Body.Parts))
return false;
if (responseMessage != null)
{
if (!AreTypesSupported(responseMessage.Body.Parts))
return false;
if (responseMessage.Body.ReturnValue != null && !IsTypeSupported(responseMessage.Body.ReturnValue))
return false;
}
return true;
}
private static bool AreTypesSupported(MessagePartDescriptionCollection bodyDescriptions)
{
for (int i = 0; i < bodyDescriptions.Count; i++)
if (!IsTypeSupported(bodyDescriptions[i]))
return false;
return true;
}
private static bool IsTypeSupported(MessagePartDescription bodyDescription)
{
Fx.Assert(bodyDescription != null, "");
Type type = bodyDescription.Type;
if (type == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.SFxMessagePartDescriptionMissingType, bodyDescription.Name, bodyDescription.Namespace)));
if (bodyDescription.Multiple)
return false;
if (type == typeof(void))
return true;
if (type.IsEnum())
return false;
switch (type.GetTypeCode())
{
case TypeCode.Boolean:
case TypeCode.DateTime:
case TypeCode.Decimal:
case TypeCode.Double:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.String:
return true;
case TypeCode.Object:
if (type.IsArray && type.GetArrayRank() == 1 && IsArrayTypeSupported(type.GetElementType()))
return true;
break;
default:
break;
}
return false;
}
private static bool IsArrayTypeSupported(Type type)
{
if (type.IsEnum())
return false;
switch (type.GetTypeCode())
{
case TypeCode.Byte:
case TypeCode.Boolean:
case TypeCode.DateTime:
case TypeCode.Decimal:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
return true;
default:
return false;
}
}
public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
{
if (messageVersion == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageVersion");
if (parameters == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parameters");
return Message.CreateMessage(messageVersion, GetActionHeader(messageVersion.Addressing), new PrimitiveRequestBodyWriter(parameters, this));
}
public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
{
if (messageVersion == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageVersion");
if (parameters == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parameters");
return Message.CreateMessage(messageVersion, GetReplyActionHeader(messageVersion.Addressing), new PrimitiveResponseBodyWriter(parameters, result, this));
}
public object DeserializeReply(Message message, object[] parameters)
{
if (message == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message"));
if (parameters == null)
throw TraceUtility.ThrowHelperError(new ArgumentNullException("parameters"), message);
try
{
if (message.IsEmpty)
{
if (_responseWrapperName == null)
return null;
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SRServiceModel.SFxInvalidMessageBodyEmptyMessage));
}
XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents();
using (bodyReader)
{
object returnValue = DeserializeResponse(bodyReader, parameters);
message.ReadFromBodyContentsToEnd(bodyReader);
return returnValue;
}
}
catch (XmlException xe)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(
string.Format(SRServiceModel.SFxErrorDeserializingReplyBodyMore, _operation.Name, xe.Message), xe));
}
catch (FormatException fe)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(
string.Format(SRServiceModel.SFxErrorDeserializingReplyBodyMore, _operation.Name, fe.Message), fe));
}
catch (SerializationException se)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(
string.Format(SRServiceModel.SFxErrorDeserializingReplyBodyMore, _operation.Name, se.Message), se));
}
}
public void DeserializeRequest(Message message, object[] parameters)
{
if (message == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message"));
if (parameters == null)
throw TraceUtility.ThrowHelperError(new ArgumentNullException("parameters"), message);
try
{
if (message.IsEmpty)
{
if (_requestWrapperName == null)
return;
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SRServiceModel.SFxInvalidMessageBodyEmptyMessage));
}
XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents();
using (bodyReader)
{
DeserializeRequest(bodyReader, parameters);
message.ReadFromBodyContentsToEnd(bodyReader);
}
}
catch (XmlException xe)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
OperationFormatter.CreateDeserializationFailedFault(
string.Format(SRServiceModel.SFxErrorDeserializingRequestBodyMore, _operation.Name, xe.Message),
xe));
}
catch (FormatException fe)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
OperationFormatter.CreateDeserializationFailedFault(
string.Format(SRServiceModel.SFxErrorDeserializingRequestBodyMore, _operation.Name, fe.Message),
fe));
}
catch (SerializationException se)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(
string.Format(SRServiceModel.SFxErrorDeserializingRequestBodyMore, _operation.Name, se.Message),
se));
}
}
private void DeserializeRequest(XmlDictionaryReader reader, object[] parameters)
{
if (_requestWrapperName != null)
{
if (!reader.IsStartElement(_requestWrapperName, _requestWrapperNamespace))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(string.Format(SRServiceModel.SFxInvalidMessageBody, _requestWrapperName, _requestWrapperNamespace, reader.NodeType, reader.Name, reader.NamespaceURI)));
bool isEmptyElement = reader.IsEmptyElement;
reader.Read();
if (isEmptyElement)
{
return;
}
}
DeserializeParameters(reader, _requestParts, parameters);
if (_requestWrapperName != null)
{
reader.ReadEndElement();
}
}
private object DeserializeResponse(XmlDictionaryReader reader, object[] parameters)
{
if (_responseWrapperName != null)
{
if (!reader.IsStartElement(_responseWrapperName, _responseWrapperNamespace))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(string.Format(SRServiceModel.SFxInvalidMessageBody, _responseWrapperName, _responseWrapperNamespace, reader.NodeType, reader.Name, reader.NamespaceURI)));
bool isEmptyElement = reader.IsEmptyElement;
reader.Read();
if (isEmptyElement)
{
return null;
}
}
object returnValue = null;
if (_returnPart != null)
{
while (true)
{
if (IsPartElement(reader, _returnPart))
{
returnValue = DeserializeParameter(reader, _returnPart);
break;
}
if (!reader.IsStartElement())
break;
if (IsPartElements(reader, _responseParts))
break;
OperationFormatter.TraceAndSkipElement(reader);
}
}
DeserializeParameters(reader, _responseParts, parameters);
if (_responseWrapperName != null)
{
reader.ReadEndElement();
}
return returnValue;
}
private void DeserializeParameters(XmlDictionaryReader reader, PartInfo[] parts, object[] parameters)
{
if (parts.Length != parameters.Length)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentException(string.Format(SRServiceModel.SFxParameterCountMismatch, "parts", parts.Length, "parameters", parameters.Length), "parameters"));
int nextPartIndex = 0;
while (reader.IsStartElement())
{
for (int i = nextPartIndex; i < parts.Length; i++)
{
PartInfo part = parts[i];
if (IsPartElement(reader, part))
{
parameters[part.Description.Index] = DeserializeParameter(reader, parts[i]);
nextPartIndex = i + 1;
}
else
parameters[part.Description.Index] = null;
}
if (reader.IsStartElement())
OperationFormatter.TraceAndSkipElement(reader);
}
}
private bool IsPartElements(XmlDictionaryReader reader, PartInfo[] parts)
{
foreach (PartInfo part in parts)
if (IsPartElement(reader, part))
return true;
return false;
}
private bool IsPartElement(XmlDictionaryReader reader, PartInfo part)
{
return reader.IsStartElement(part.DictionaryName, part.DictionaryNamespace);
}
private object DeserializeParameter(XmlDictionaryReader reader, PartInfo part)
{
if (reader.AttributeCount > 0 &&
reader.MoveToAttribute(_xsiNilLocalName.Value, _xsiNilNamespace.Value) &&
reader.ReadContentAsBoolean())
{
reader.Skip();
return null;
}
return part.ReadValue(reader);
}
private void SerializeParameter(XmlDictionaryWriter writer, PartInfo part, object graph)
{
writer.WriteStartElement(part.DictionaryName, part.DictionaryNamespace);
if (graph == null)
{
writer.WriteStartAttribute(_xsiNilLocalName, _xsiNilNamespace);
writer.WriteValue(true);
writer.WriteEndAttribute();
}
else
part.WriteValue(writer, graph);
writer.WriteEndElement();
}
private void SerializeParameters(XmlDictionaryWriter writer, PartInfo[] parts, object[] parameters)
{
if (parts.Length != parameters.Length)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentException(string.Format(SRServiceModel.SFxParameterCountMismatch, "parts", parts.Length, "parameters", parameters.Length), "parameters"));
for (int i = 0; i < parts.Length; i++)
{
PartInfo part = parts[i];
SerializeParameter(writer, part, parameters[part.Description.Index]);
}
}
private void SerializeRequest(XmlDictionaryWriter writer, object[] parameters)
{
if (_requestWrapperName != null)
writer.WriteStartElement(_requestWrapperName, _requestWrapperNamespace);
SerializeParameters(writer, _requestParts, parameters);
if (_requestWrapperName != null)
writer.WriteEndElement();
}
private void SerializeResponse(XmlDictionaryWriter writer, object returnValue, object[] parameters)
{
if (_responseWrapperName != null)
writer.WriteStartElement(_responseWrapperName, _responseWrapperNamespace);
if (_returnPart != null)
SerializeParameter(writer, _returnPart, returnValue);
SerializeParameters(writer, _responseParts, parameters);
if (_responseWrapperName != null)
writer.WriteEndElement();
}
internal class PartInfo
{
private XmlDictionaryString _dictionaryName;
private XmlDictionaryString _dictionaryNamespace;
private XmlDictionaryString _itemName;
private XmlDictionaryString _itemNamespace;
private MessagePartDescription _description;
private TypeCode _typeCode;
private bool _isArray;
public PartInfo(MessagePartDescription description, XmlDictionaryString dictionaryName, XmlDictionaryString dictionaryNamespace, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
{
_dictionaryName = dictionaryName;
_dictionaryNamespace = dictionaryNamespace;
_itemName = itemName;
_itemNamespace = itemNamespace;
_description = description;
if (description.Type.IsArray)
{
_isArray = true;
_typeCode = description.Type.GetElementType().GetTypeCode();
}
else
{
_isArray = false;
_typeCode = description.Type.GetTypeCode();
}
}
public MessagePartDescription Description
{
get { return _description; }
}
public XmlDictionaryString DictionaryName
{
get { return _dictionaryName; }
}
public XmlDictionaryString DictionaryNamespace
{
get { return _dictionaryNamespace; }
}
public object ReadValue(XmlDictionaryReader reader)
{
object value;
if (_isArray)
{
switch (_typeCode)
{
case TypeCode.Byte:
value = reader.ReadElementContentAsBase64();
break;
case TypeCode.Boolean:
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
value = reader.ReadBooleanArray(_itemName, _itemNamespace);
reader.ReadEndElement();
}
else
{
reader.Read();
value = Array.Empty<bool>();
}
break;
case TypeCode.DateTime:
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
value = reader.ReadDateTimeArray(_itemName, _itemNamespace);
reader.ReadEndElement();
}
else
{
reader.Read();
value = Array.Empty<DateTime>();
}
break;
case TypeCode.Decimal:
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
value = reader.ReadDecimalArray(_itemName, _itemNamespace);
reader.ReadEndElement();
}
else
{
reader.Read();
value = Array.Empty<Decimal>();
}
break;
case TypeCode.Int32:
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
value = reader.ReadInt32Array(_itemName, _itemNamespace);
reader.ReadEndElement();
}
else
{
reader.Read();
value = Array.Empty<Int32>();
}
break;
case TypeCode.Int64:
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
value = reader.ReadInt64Array(_itemName, _itemNamespace);
reader.ReadEndElement();
}
else
{
reader.Read();
value = Array.Empty<Int64>();
}
break;
case TypeCode.Single:
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
value = reader.ReadSingleArray(_itemName, _itemNamespace);
reader.ReadEndElement();
}
else
{
reader.Read();
value = Array.Empty<Single>();
}
break;
case TypeCode.Double:
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
value = reader.ReadDoubleArray(_itemName, _itemNamespace);
reader.ReadEndElement();
}
else
{
reader.Read();
value = Array.Empty<Double>();
}
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.SFxInvalidUseOfPrimitiveOperationFormatter));
}
}
else
{
switch (_typeCode)
{
case TypeCode.Boolean:
value = reader.ReadElementContentAsBoolean();
break;
case TypeCode.DateTime:
value = reader.ReadElementContentAsDateTime();
break;
case TypeCode.Decimal:
value = reader.ReadElementContentAsDecimal();
break;
case TypeCode.Double:
value = reader.ReadElementContentAsDouble();
break;
case TypeCode.Int32:
value = reader.ReadElementContentAsInt();
break;
case TypeCode.Int64:
value = reader.ReadElementContentAsLong();
break;
case TypeCode.Single:
value = reader.ReadElementContentAsFloat();
break;
case TypeCode.String:
return reader.ReadElementContentAsString();
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.SFxInvalidUseOfPrimitiveOperationFormatter));
}
}
return value;
}
public void WriteValue(XmlDictionaryWriter writer, object value)
{
if (_isArray)
{
switch (_typeCode)
{
case TypeCode.Byte:
{
byte[] arrayValue = (byte[])value;
writer.WriteBase64(arrayValue, 0, arrayValue.Length);
}
break;
case TypeCode.Boolean:
{
bool[] arrayValue = (bool[])value;
writer.WriteArray(null, _itemName, _itemNamespace, arrayValue, 0, arrayValue.Length);
}
break;
case TypeCode.DateTime:
{
DateTime[] arrayValue = (DateTime[])value;
writer.WriteArray(null, _itemName, _itemNamespace, arrayValue, 0, arrayValue.Length);
}
break;
case TypeCode.Decimal:
{
decimal[] arrayValue = (decimal[])value;
writer.WriteArray(null, _itemName, _itemNamespace, arrayValue, 0, arrayValue.Length);
}
break;
case TypeCode.Int32:
{
Int32[] arrayValue = (Int32[])value;
writer.WriteArray(null, _itemName, _itemNamespace, arrayValue, 0, arrayValue.Length);
}
break;
case TypeCode.Int64:
{
Int64[] arrayValue = (Int64[])value;
writer.WriteArray(null, _itemName, _itemNamespace, arrayValue, 0, arrayValue.Length);
}
break;
case TypeCode.Single:
{
float[] arrayValue = (float[])value;
writer.WriteArray(null, _itemName, _itemNamespace, arrayValue, 0, arrayValue.Length);
}
break;
case TypeCode.Double:
{
double[] arrayValue = (double[])value;
writer.WriteArray(null, _itemName, _itemNamespace, arrayValue, 0, arrayValue.Length);
}
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.SFxInvalidUseOfPrimitiveOperationFormatter));
}
}
else
{
switch (_typeCode)
{
case TypeCode.Boolean:
writer.WriteValue((bool)value);
break;
case TypeCode.DateTime:
writer.WriteValue((DateTime)value);
break;
case TypeCode.Decimal:
writer.WriteValue((Decimal)value);
break;
case TypeCode.Double:
writer.WriteValue((double)value);
break;
case TypeCode.Int32:
writer.WriteValue((int)value);
break;
case TypeCode.Int64:
writer.WriteValue((long)value);
break;
case TypeCode.Single:
writer.WriteValue((float)value);
break;
case TypeCode.String:
writer.WriteString((string)value);
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.SFxInvalidUseOfPrimitiveOperationFormatter));
}
}
}
}
internal class PrimitiveRequestBodyWriter : BodyWriter
{
private object[] _parameters;
private PrimitiveOperationFormatter _primitiveOperationFormatter;
public PrimitiveRequestBodyWriter(object[] parameters, PrimitiveOperationFormatter primitiveOperationFormatter)
: base(true)
{
_parameters = parameters;
_primitiveOperationFormatter = primitiveOperationFormatter;
}
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
_primitiveOperationFormatter.SerializeRequest(writer, _parameters);
}
}
internal class PrimitiveResponseBodyWriter : BodyWriter
{
private object[] _parameters;
private object _returnValue;
private PrimitiveOperationFormatter _primitiveOperationFormatter;
public PrimitiveResponseBodyWriter(object[] parameters, object returnValue,
PrimitiveOperationFormatter primitiveOperationFormatter)
: base(true)
{
_parameters = parameters;
_returnValue = returnValue;
_primitiveOperationFormatter = primitiveOperationFormatter;
}
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
_primitiveOperationFormatter.SerializeResponse(writer, _returnValue, _parameters);
}
}
}
}
| |
/*
* 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.
*/
#pragma warning disable 618
namespace Apache.Ignite.Core.Tests
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Events;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Impl.Events;
using Apache.Ignite.Core.Tests.Compute;
using NUnit.Framework;
/// <summary>
/// <see cref="IEvents"/> tests.
/// </summary>
public class EventsTest
{
/** */
private IIgnite _grid1;
/** */
private IIgnite _grid2;
/** */
private IIgnite _grid3;
/** */
private IIgnite[] _grids;
/// <summary>
/// Executes before each test.
/// </summary>
[SetUp]
public void SetUp()
{
StartGrids();
EventsTestHelper.ListenResult = true;
}
/// <summary>
/// Executes after each test.
/// </summary>
[TearDown]
public void TearDown()
{
try
{
TestUtils.AssertHandleRegistryIsEmpty(1000, _grid1, _grid2, _grid3);
}
catch (Exception)
{
// Restart grids to cleanup
StopGrids();
throw;
}
finally
{
EventsTestHelper.AssertFailures();
if (TestContext.CurrentContext.Test.Name.StartsWith("TestEventTypes"))
StopGrids(); // clean events for other tests
}
}
/// <summary>
/// Fixture tear down.
/// </summary>
[TestFixtureTearDown]
public void FixtureTearDown()
{
StopGrids();
}
/// <summary>
/// Tests enable/disable of event types.
/// </summary>
[Test]
public void TestEnableDisable()
{
var events = _grid1.GetEvents();
Assert.AreEqual(0, events.GetEnabledEvents().Count);
Assert.IsFalse(EventType.CacheAll.Any(events.IsEnabled));
events.EnableLocal(EventType.CacheAll);
Assert.AreEqual(EventType.CacheAll, events.GetEnabledEvents());
Assert.IsTrue(EventType.CacheAll.All(events.IsEnabled));
events.EnableLocal(EventType.TaskExecutionAll);
events.DisableLocal(EventType.CacheAll);
Assert.AreEqual(EventType.TaskExecutionAll, events.GetEnabledEvents());
}
/// <summary>
/// Tests LocalListen.
/// </summary>
[Test]
public void TestLocalListen()
{
var events = _grid1.GetEvents();
var listener = EventsTestHelper.GetListener();
var eventType = EventType.TaskExecutionAll;
events.EnableLocal(eventType);
events.LocalListen(listener, eventType);
CheckSend(3); // 3 events per task * 3 grids
// Check unsubscription for specific event
events.StopLocalListen(listener, EventType.TaskReduced);
CheckSend(2);
// Unsubscribe from all events
events.StopLocalListen(listener, Enumerable.Empty<int>());
CheckNoEvent();
// Check unsubscription by filter
events.LocalListen(listener, EventType.TaskReduced);
CheckSend();
EventsTestHelper.ListenResult = false;
CheckSend(); // one last event will be received for each listener
CheckNoEvent();
}
/// <summary>
/// Tests LocalListen.
/// </summary>
[Test]
[Ignore("IGNITE-879")]
public void TestLocalListenRepeatedSubscription()
{
var events = _grid1.GetEvents();
var listener = EventsTestHelper.GetListener();
var eventType = EventType.TaskExecutionAll;
events.EnableLocal(eventType);
events.LocalListen(listener, eventType);
CheckSend(3); // 3 events per task * 3 grids
events.LocalListen(listener, eventType);
events.LocalListen(listener, eventType);
CheckSend(9);
events.StopLocalListen(listener, eventType);
CheckSend(6);
events.StopLocalListen(listener, eventType);
CheckSend(3);
events.StopLocalListen(listener, eventType);
CheckNoEvent();
}
/// <summary>
/// Tests all available event types/classes.
/// </summary>
[Test, TestCaseSource("TestCases")]
public void TestEventTypes(EventTestCase testCase)
{
var events = _grid1.GetEvents();
events.EnableLocal(testCase.EventType);
var listener = EventsTestHelper.GetListener();
events.LocalListen(listener, testCase.EventType);
EventsTestHelper.ClearReceived(testCase.EventCount);
testCase.GenerateEvent(_grid1);
EventsTestHelper.VerifyReceive(testCase.EventCount, testCase.EventObjectType, testCase.EventType);
if (testCase.VerifyEvents != null)
testCase.VerifyEvents(EventsTestHelper.ReceivedEvents.Reverse(), _grid1);
// Check stop
events.StopLocalListen(listener);
EventsTestHelper.ClearReceived(0);
testCase.GenerateEvent(_grid1);
Thread.Sleep(EventsTestHelper.Timeout);
}
/// <summary>
/// Test cases for TestEventTypes: type id + type + event generator.
/// </summary>
public IEnumerable<EventTestCase> TestCases
{
get
{
yield return new EventTestCase
{
EventType = EventType.CacheAll,
EventObjectType = typeof (CacheEvent),
GenerateEvent = g => g.GetCache<int, int>(null).Put(1, 1),
VerifyEvents = (e, g) => VerifyCacheEvents(e, g),
EventCount = 2
};
yield return new EventTestCase
{
EventType = EventType.TaskExecutionAll,
EventObjectType = typeof (TaskEvent),
GenerateEvent = g => GenerateTaskEvent(g),
VerifyEvents = (e, g) => VerifyTaskEvents(e),
EventCount = 3
};
yield return new EventTestCase
{
EventType = EventType.JobExecutionAll,
EventObjectType = typeof (JobEvent),
GenerateEvent = g => GenerateTaskEvent(g),
EventCount = 7
};
yield return new EventTestCase
{
EventType = new[] {EventType.CacheQueryExecuted},
EventObjectType = typeof (CacheQueryExecutedEvent),
GenerateEvent = g => GenerateCacheQueryEvent(g),
EventCount = 1
};
yield return new EventTestCase
{
EventType = new[] { EventType.CacheQueryObjectRead },
EventObjectType = typeof (CacheQueryReadEvent),
GenerateEvent = g => GenerateCacheQueryEvent(g),
EventCount = 1
};
}
}
/// <summary>
/// Tests the LocalQuery.
/// </summary>
[Test]
public void TestLocalQuery()
{
var events = _grid1.GetEvents();
var eventType = EventType.TaskExecutionAll;
events.EnableLocal(eventType);
var oldEvents = events.LocalQuery();
GenerateTaskEvent();
// "Except" works because of overridden equality
var qryResult = events.LocalQuery(eventType).Except(oldEvents).ToList();
Assert.AreEqual(3, qryResult.Count);
}
/// <summary>
/// Tests the record local.
/// </summary>
[Test]
public void TestRecordLocal()
{
Assert.Throws<NotImplementedException>(() => _grid1.GetEvents().RecordLocal(new MyEvent()));
}
/// <summary>
/// Tests the WaitForLocal.
/// </summary>
[Test]
public void TestWaitForLocal()
{
var events = _grid1.GetEvents();
var timeout = TimeSpan.FromSeconds(3);
var eventType = EventType.TaskExecutionAll;
events.EnableLocal(eventType);
var taskFuncs = GetWaitTasks(events).Select(
func => (Func<IEventFilter<IEvent>, int[], Task<IEvent>>) (
(filter, types) =>
{
var task = func(filter, types);
Thread.Sleep(100); // allow task to start and begin waiting for events
GenerateTaskEvent();
return task;
})).ToArray();
for (int i = 0; i < taskFuncs.Length; i++)
{
var getWaitTask = taskFuncs[i];
// No params
var waitTask = getWaitTask(null, new int[0]);
waitTask.Wait(timeout);
// Event types
waitTask = getWaitTask(null, new[] {EventType.TaskReduced});
Assert.IsTrue(waitTask.Wait(timeout));
Assert.IsInstanceOf(typeof(TaskEvent), waitTask.Result);
Assert.AreEqual(EventType.TaskReduced, waitTask.Result.Type);
if (i > 3)
{
// Filter
waitTask = getWaitTask(new EventFilter<IEvent>(e => e.Type == EventType.TaskReduced), new int[0]);
Assert.IsTrue(waitTask.Wait(timeout));
Assert.IsInstanceOf(typeof(TaskEvent), waitTask.Result);
Assert.AreEqual(EventType.TaskReduced, waitTask.Result.Type);
// Filter & types
waitTask = getWaitTask(new EventFilter<IEvent>(e => e.Type == EventType.TaskReduced),
new[] {EventType.TaskReduced});
Assert.IsTrue(waitTask.Wait(timeout));
Assert.IsInstanceOf(typeof(TaskEvent), waitTask.Result);
Assert.AreEqual(EventType.TaskReduced, waitTask.Result.Type);
}
}
}
/// <summary>
/// Gets the wait tasks for different overloads of WaitForLocal.
/// </summary>
private static IEnumerable<Func<IEventFilter<IEvent>, int[], Task<IEvent>>> GetWaitTasks(IEvents events)
{
yield return (filter, types) => Task.Factory.StartNew(() => events.WaitForLocal(types));
yield return (filter, types) => Task.Factory.StartNew(() => events.WaitForLocal(types.ToList()));
yield return (filter, types) => events.WaitForLocalAsync(types);
yield return (filter, types) => events.WaitForLocalAsync(types.ToList());
yield return (filter, types) => Task.Factory.StartNew(() => events.WaitForLocal(filter, types));
yield return (filter, types) => Task.Factory.StartNew(() => events.WaitForLocal(filter, types.ToList()));
yield return (filter, types) => events.WaitForLocalAsync(filter, types);
yield return (filter, types) => events.WaitForLocalAsync(filter, types.ToList());
}
/// <summary>
/// Tests the wait for local overloads.
/// </summary>
[Test]
public void TestWaitForLocalOverloads()
{
}
/*
/// <summary>
/// Tests RemoteListen.
/// </summary>
[Test]
public void TestRemoteListen(
[Values(true, false)] bool async,
[Values(true, false)] bool binarizable,
[Values(true, false)] bool autoUnsubscribe)
{
foreach (var g in _grids)
{
g.GetEvents().EnableLocal(EventType.JobExecutionAll);
g.GetEvents().EnableLocal(EventType.TaskExecutionAll);
}
var events = _grid1.GetEvents();
var expectedType = EventType.JobStarted;
var remoteFilter = binary
? (IEventFilter<IEvent>) new RemoteEventBinarizableFilter(expectedType)
: new RemoteEventFilter(expectedType);
var localListener = EventsTestHelper.GetListener();
if (async)
events = events.WithAsync();
var listenId = events.RemoteListen(localListener: localListener, remoteFilter: remoteFilter,
autoUnsubscribe: autoUnsubscribe);
if (async)
listenId = events.GetFuture<Guid>().Get();
Assert.IsNotNull(listenId);
CheckSend(3, typeof(JobEvent), expectedType);
_grid3.GetEvents().DisableLocal(EventType.JobExecutionAll);
CheckSend(2, typeof(JobEvent), expectedType);
events.StopRemoteListen(listenId.Value);
if (async)
events.GetFuture().Get();
CheckNoEvent();
// Check unsubscription with listener
events.RemoteListen(localListener: localListener, remoteFilter: remoteFilter,
autoUnsubscribe: autoUnsubscribe);
if (async)
events.GetFuture<Guid>().Get();
CheckSend(2, typeof(JobEvent), expectedType);
EventsTestHelper.ListenResult = false;
CheckSend(1, typeof(JobEvent), expectedType); // one last event
CheckNoEvent();
}*/
/// <summary>
/// Tests RemoteQuery.
/// </summary>
[Test]
public void TestRemoteQuery([Values(true, false)] bool async)
{
foreach (var g in _grids)
g.GetEvents().EnableLocal(EventType.JobExecutionAll);
var events = _grid1.GetEvents();
var eventFilter = new RemoteEventFilter(EventType.JobStarted);
var oldEvents = events.RemoteQuery(eventFilter);
GenerateTaskEvent();
var remoteQuery = !async
? events.RemoteQuery(eventFilter, EventsTestHelper.Timeout, EventType.JobExecutionAll)
: events.RemoteQueryAsync(eventFilter, EventsTestHelper.Timeout, EventType.JobExecutionAll).Result;
var qryResult = remoteQuery.Except(oldEvents).Cast<JobEvent>().ToList();
Assert.AreEqual(_grids.Length - 1, qryResult.Count);
Assert.IsTrue(qryResult.All(x => x.Type == EventType.JobStarted));
}
/// <summary>
/// Tests serialization.
/// </summary>
[Test]
public void TestSerialization()
{
var grid = (Ignite) _grid1;
var comp = (Impl.Compute.Compute) grid.GetCluster().ForLocal().GetCompute();
var locNode = grid.GetCluster().GetLocalNode();
var expectedGuid = Guid.Parse("00000000-0000-0001-0000-000000000002");
var expectedGridGuid = new IgniteGuid(expectedGuid, 3);
using (var inStream = IgniteManager.Memory.Allocate().GetStream())
{
var result = comp.ExecuteJavaTask<bool>("org.apache.ignite.platform.PlatformEventsWriteEventTask",
inStream.MemoryPointer);
Assert.IsTrue(result);
inStream.SynchronizeInput();
var reader = grid.Marshaller.StartUnmarshal(inStream);
var cacheEvent = EventReader.Read<CacheEvent>(reader);
CheckEventBase(cacheEvent);
Assert.AreEqual("cacheName", cacheEvent.CacheName);
Assert.AreEqual(locNode, cacheEvent.EventNode);
Assert.AreEqual(1, cacheEvent.Partition);
Assert.AreEqual(true, cacheEvent.IsNear);
Assert.AreEqual(2, cacheEvent.Key);
Assert.AreEqual(expectedGridGuid, cacheEvent.Xid);
Assert.AreEqual(4, cacheEvent.NewValue);
Assert.AreEqual(true, cacheEvent.HasNewValue);
Assert.AreEqual(5, cacheEvent.OldValue);
Assert.AreEqual(true, cacheEvent.HasOldValue);
Assert.AreEqual(expectedGuid, cacheEvent.SubjectId);
Assert.AreEqual("cloClsName", cacheEvent.ClosureClassName);
Assert.AreEqual("taskName", cacheEvent.TaskName);
Assert.IsTrue(cacheEvent.ToShortString().StartsWith("SWAP_SPACE_CLEARED: IsNear="));
var qryExecEvent = EventReader.Read<CacheQueryExecutedEvent>(reader);
CheckEventBase(qryExecEvent);
Assert.AreEqual("qryType", qryExecEvent.QueryType);
Assert.AreEqual("cacheName", qryExecEvent.CacheName);
Assert.AreEqual("clsName", qryExecEvent.ClassName);
Assert.AreEqual("clause", qryExecEvent.Clause);
Assert.AreEqual(expectedGuid, qryExecEvent.SubjectId);
Assert.AreEqual("taskName", qryExecEvent.TaskName);
Assert.AreEqual(
"SWAP_SPACE_CLEARED: QueryType=qryType, CacheName=cacheName, ClassName=clsName, Clause=clause, " +
"SubjectId=00000000-0000-0001-0000-000000000002, TaskName=taskName", qryExecEvent.ToShortString());
var qryReadEvent = EventReader.Read<CacheQueryReadEvent>(reader);
CheckEventBase(qryReadEvent);
Assert.AreEqual("qryType", qryReadEvent.QueryType);
Assert.AreEqual("cacheName", qryReadEvent.CacheName);
Assert.AreEqual("clsName", qryReadEvent.ClassName);
Assert.AreEqual("clause", qryReadEvent.Clause);
Assert.AreEqual(expectedGuid, qryReadEvent.SubjectId);
Assert.AreEqual("taskName", qryReadEvent.TaskName);
Assert.AreEqual(1, qryReadEvent.Key);
Assert.AreEqual(2, qryReadEvent.Value);
Assert.AreEqual(3, qryReadEvent.OldValue);
Assert.AreEqual(4, qryReadEvent.Row);
Assert.AreEqual(
"SWAP_SPACE_CLEARED: QueryType=qryType, CacheName=cacheName, ClassName=clsName, Clause=clause, " +
"SubjectId=00000000-0000-0001-0000-000000000002, TaskName=taskName, Key=1, Value=2, " +
"OldValue=3, Row=4", qryReadEvent.ToShortString());
var cacheRebalancingEvent = EventReader.Read<CacheRebalancingEvent>(reader);
CheckEventBase(cacheRebalancingEvent);
Assert.AreEqual("cacheName", cacheRebalancingEvent.CacheName);
Assert.AreEqual(1, cacheRebalancingEvent.Partition);
Assert.AreEqual(locNode, cacheRebalancingEvent.DiscoveryNode);
Assert.AreEqual(2, cacheRebalancingEvent.DiscoveryEventType);
Assert.AreEqual(3, cacheRebalancingEvent.DiscoveryTimestamp);
Assert.IsTrue(cacheRebalancingEvent.ToShortString().StartsWith(
"SWAP_SPACE_CLEARED: CacheName=cacheName, Partition=1, DiscoveryNode=GridNode"));
var checkpointEvent = EventReader.Read<CheckpointEvent>(reader);
CheckEventBase(checkpointEvent);
Assert.AreEqual("cpKey", checkpointEvent.Key);
Assert.AreEqual("SWAP_SPACE_CLEARED: Key=cpKey", checkpointEvent.ToShortString());
var discoEvent = EventReader.Read<DiscoveryEvent>(reader);
CheckEventBase(discoEvent);
Assert.AreEqual(grid.TopologyVersion, discoEvent.TopologyVersion);
Assert.AreEqual(grid.GetNodes(), discoEvent.TopologyNodes);
Assert.IsTrue(discoEvent.ToShortString().StartsWith("SWAP_SPACE_CLEARED: EventNode=GridNode"));
var jobEvent = EventReader.Read<JobEvent>(reader);
CheckEventBase(jobEvent);
Assert.AreEqual(expectedGridGuid, jobEvent.JobId);
Assert.AreEqual("taskClsName", jobEvent.TaskClassName);
Assert.AreEqual("taskName", jobEvent.TaskName);
Assert.AreEqual(locNode, jobEvent.TaskNode);
Assert.AreEqual(expectedGridGuid, jobEvent.TaskSessionId);
Assert.AreEqual(expectedGuid, jobEvent.TaskSubjectId);
Assert.IsTrue(jobEvent.ToShortString().StartsWith("SWAP_SPACE_CLEARED: TaskName=taskName"));
var spaceEvent = EventReader.Read<SwapSpaceEvent>(reader);
CheckEventBase(spaceEvent);
Assert.AreEqual("space", spaceEvent.Space);
Assert.IsTrue(spaceEvent.ToShortString().StartsWith("SWAP_SPACE_CLEARED: Space=space"));
var taskEvent = EventReader.Read<TaskEvent>(reader);
CheckEventBase(taskEvent);
Assert.AreEqual(true,taskEvent.Internal);
Assert.AreEqual(expectedGuid, taskEvent.SubjectId);
Assert.AreEqual("taskClsName", taskEvent.TaskClassName);
Assert.AreEqual("taskName", taskEvent.TaskName);
Assert.AreEqual(expectedGridGuid, taskEvent.TaskSessionId);
Assert.IsTrue(taskEvent.ToShortString().StartsWith("SWAP_SPACE_CLEARED: TaskName=taskName"));
}
}
/// <summary>
/// Tests the event store configuration.
/// </summary>
[Test]
public void TestConfiguration()
{
var cfg = _grid1.GetConfiguration().EventStorageSpi as MemoryEventStorageSpi;
Assert.IsNotNull(cfg);
Assert.AreEqual(MemoryEventStorageSpi.DefaultExpirationTimeout, cfg.ExpirationTimeout);
Assert.AreEqual(MemoryEventStorageSpi.DefaultMaxEventCount, cfg.MaxEventCount);
// Test user-defined event storage.
var igniteCfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
IgniteInstanceName = "grid4",
EventStorageSpi = new MyEventStorage()
};
var ex = Assert.Throws<IgniteException>(() => Ignition.Start(igniteCfg));
Assert.AreEqual("Failed to start Ignite.NET, check inner exception for details", ex.Message);
Assert.IsNotNull(ex.InnerException);
Assert.AreEqual("Unsupported IgniteConfiguration.EventStorageSpi: " +
"'Apache.Ignite.Core.Tests.MyEventStorage'. Supported implementations: " +
"'Apache.Ignite.Core.Events.NoopEventStorageSpi', " +
"'Apache.Ignite.Core.Events.MemoryEventStorageSpi'.", ex.InnerException.Message);
}
/// <summary>
/// Checks base event fields serialization.
/// </summary>
/// <param name="evt">The evt.</param>
private void CheckEventBase(IEvent evt)
{
var locNode = _grid1.GetCluster().GetLocalNode();
Assert.AreEqual(locNode, evt.Node);
Assert.AreEqual("msg", evt.Message);
Assert.AreEqual(EventType.SwapSpaceCleared, evt.Type);
Assert.IsNotNullOrEmpty(evt.Name);
Assert.AreNotEqual(Guid.Empty, evt.Id.GlobalId);
Assert.IsTrue(Math.Abs((evt.Timestamp - DateTime.UtcNow).TotalSeconds) < 20,
"Invalid event timestamp: '{0}', current time: '{1}'", evt.Timestamp, DateTime.Now);
Assert.Greater(evt.LocalOrder, 0);
Assert.IsTrue(evt.ToString().Contains("[Name=SWAP_SPACE_CLEARED"));
Assert.IsTrue(evt.ToShortString().StartsWith("SWAP_SPACE_CLEARED"));
}
/// <summary>
/// Sends events in various ways and verifies correct receive.
/// </summary>
/// <param name="repeat">Expected event count multiplier.</param>
/// <param name="eventObjectType">Expected event object type.</param>
/// <param name="eventType">Type of the event.</param>
private void CheckSend(int repeat = 1, Type eventObjectType = null, params int[] eventType)
{
EventsTestHelper.ClearReceived(repeat);
GenerateTaskEvent();
EventsTestHelper.VerifyReceive(repeat, eventObjectType ?? typeof (TaskEvent),
eventType.Any() ? eventType : EventType.TaskExecutionAll);
}
/// <summary>
/// Checks that no event has arrived.
/// </summary>
private void CheckNoEvent()
{
// this will result in an exception in case of a event
EventsTestHelper.ClearReceived(0);
GenerateTaskEvent();
Thread.Sleep(EventsTestHelper.Timeout);
EventsTestHelper.AssertFailures();
}
/// <summary>
/// Gets the Ignite configuration.
/// </summary>
private static IgniteConfiguration GetConfiguration(string springConfigUrl)
{
return new IgniteConfiguration
{
SpringConfigUrl = springConfigUrl,
JvmClasspath = TestUtils.CreateTestClasspath(),
JvmOptions = TestUtils.TestJavaOptions(),
BinaryConfiguration = new BinaryConfiguration
{
TypeConfigurations = new List<BinaryTypeConfiguration>
{
new BinaryTypeConfiguration(typeof (RemoteEventBinarizableFilter))
}
},
EventStorageSpi = new MemoryEventStorageSpi()
};
}
/// <summary>
/// Generates the task event.
/// </summary>
private void GenerateTaskEvent(IIgnite grid = null)
{
(grid ?? _grid1).GetCompute().Broadcast(new ComputeAction());
}
/// <summary>
/// Verifies the task events.
/// </summary>
private static void VerifyTaskEvents(IEnumerable<IEvent> events)
{
var e = events.Cast<TaskEvent>().ToArray();
// started, reduced, finished
Assert.AreEqual(
new[] {EventType.TaskStarted, EventType.TaskReduced, EventType.TaskFinished},
e.Select(x => x.Type).ToArray());
}
/// <summary>
/// Generates the cache query event.
/// </summary>
private static void GenerateCacheQueryEvent(IIgnite g)
{
var cache = g.GetCache<int, int>(null);
cache.Clear();
cache.Put(1, 1);
cache.Query(new ScanQuery<int, int>()).GetAll();
}
/// <summary>
/// Verifies the cache events.
/// </summary>
private static void VerifyCacheEvents(IEnumerable<IEvent> events, IIgnite grid)
{
var e = events.Cast<CacheEvent>().ToArray();
foreach (var cacheEvent in e)
{
Assert.AreEqual(null, cacheEvent.CacheName);
Assert.AreEqual(null, cacheEvent.ClosureClassName);
Assert.AreEqual(null, cacheEvent.TaskName);
Assert.AreEqual(grid.GetCluster().GetLocalNode(), cacheEvent.EventNode);
Assert.AreEqual(grid.GetCluster().GetLocalNode(), cacheEvent.Node);
Assert.AreEqual(false, cacheEvent.HasOldValue);
Assert.AreEqual(null, cacheEvent.OldValue);
if (cacheEvent.Type == EventType.CacheObjectPut)
{
Assert.AreEqual(true, cacheEvent.HasNewValue);
Assert.AreEqual(1, cacheEvent.NewValue);
}
else if (cacheEvent.Type == EventType.CacheEntryCreated)
{
Assert.AreEqual(false, cacheEvent.HasNewValue);
Assert.AreEqual(null, cacheEvent.NewValue);
}
else
{
Assert.Fail("Unexpected event type");
}
}
}
/// <summary>
/// Starts the grids.
/// </summary>
private void StartGrids()
{
if (_grid1 != null)
return;
_grid1 = Ignition.Start(GetConfiguration("config\\compute\\compute-grid1.xml"));
_grid2 = Ignition.Start(GetConfiguration("config\\compute\\compute-grid2.xml"));
_grid3 = Ignition.Start(GetConfiguration("config\\compute\\compute-grid3.xml"));
_grids = new[] {_grid1, _grid2, _grid3};
}
/// <summary>
/// Stops the grids.
/// </summary>
private void StopGrids()
{
_grid1 = _grid2 = _grid3 = null;
_grids = null;
Ignition.StopAll(true);
}
}
/// <summary>
/// Event test helper class.
/// </summary>
[Serializable]
public static class EventsTestHelper
{
/** */
public static readonly ConcurrentStack<IEvent> ReceivedEvents = new ConcurrentStack<IEvent>();
/** */
public static readonly ConcurrentStack<string> Failures = new ConcurrentStack<string>();
/** */
public static readonly CountdownEvent ReceivedEvent = new CountdownEvent(0);
/** */
public static readonly ConcurrentStack<Guid?> LastNodeIds = new ConcurrentStack<Guid?>();
/** */
public static volatile bool ListenResult = true;
/** */
public static readonly TimeSpan Timeout = TimeSpan.FromMilliseconds(800);
/// <summary>
/// Clears received event information.
/// </summary>
/// <param name="expectedCount">The expected count of events to be received.</param>
public static void ClearReceived(int expectedCount)
{
ReceivedEvents.Clear();
ReceivedEvent.Reset(expectedCount);
LastNodeIds.Clear();
}
/// <summary>
/// Verifies received events against events events.
/// </summary>
public static void VerifyReceive(int count, Type eventObjectType, ICollection<int> eventTypes)
{
// check if expected event count has been received; Wait returns false if there were none.
Assert.IsTrue(ReceivedEvent.Wait(Timeout),
"Failed to receive expected number of events. Remaining count: " + ReceivedEvent.CurrentCount);
Assert.AreEqual(count, ReceivedEvents.Count);
Assert.IsTrue(ReceivedEvents.All(x => x.GetType() == eventObjectType));
Assert.IsTrue(ReceivedEvents.All(x => eventTypes.Contains(x.Type)));
AssertFailures();
}
/// <summary>
/// Gets the event listener.
/// </summary>
/// <returns>New instance of event listener.</returns>
public static IEventListener<IEvent> GetListener()
{
return new EventFilter<IEvent>(Listen);
}
/// <summary>
/// Combines accumulated failures and throws an assertion, if there are any.
/// Clears accumulated failures.
/// </summary>
public static void AssertFailures()
{
try
{
if (Failures.Any())
Assert.Fail(Failures.Reverse().Aggregate((x, y) => string.Format("{0}\n{1}", x, y)));
}
finally
{
Failures.Clear();
}
}
/// <summary>
/// Listen method.
/// </summary>
/// <param name="evt">Event.</param>
private static bool Listen(IEvent evt)
{
try
{
LastNodeIds.Push(evt.Node.Id);
ReceivedEvents.Push(evt);
ReceivedEvent.Signal();
return ListenResult;
}
catch (Exception ex)
{
// When executed on remote nodes, these exceptions will not go to sender,
// so we have to accumulate them.
Failures.Push(string.Format("Exception in Listen (msg: {0}, id: {1}): {2}", evt, evt.Node.Id, ex));
throw;
}
}
}
/// <summary>
/// Test event filter.
/// </summary>
[Serializable]
public class EventFilter<T> : IEventFilter<T>, IEventListener<T> where T : IEvent
{
/** */
private readonly Func<T, bool> _invoke;
/// <summary>
/// Initializes a new instance of the <see cref="RemoteListenEventFilter"/> class.
/// </summary>
/// <param name="invoke">The invoke delegate.</param>
public EventFilter(Func<T, bool> invoke)
{
_invoke = invoke;
}
/** <inheritdoc /> */
bool IEventFilter<T>.Invoke(T evt)
{
return _invoke(evt);
}
/** <inheritdoc /> */
bool IEventListener<T>.Invoke(T evt)
{
return _invoke(evt);
}
/** <inheritdoc /> */
// ReSharper disable once UnusedMember.Global
public bool Invoke(T evt)
{
throw new Exception("Invalid method");
}
}
/// <summary>
/// Remote event filter.
/// </summary>
[Serializable]
public class RemoteEventFilter : IEventFilter<IEvent>
{
/** */
private readonly int _type;
public RemoteEventFilter(int type)
{
_type = type;
}
/** <inheritdoc /> */
public bool Invoke(IEvent evt)
{
return evt.Type == _type;
}
}
/// <summary>
/// Binary remote event filter.
/// </summary>
public class RemoteEventBinarizableFilter : IEventFilter<IEvent>, IBinarizable
{
/** */
private int _type;
/// <summary>
/// Initializes a new instance of the <see cref="RemoteEventBinarizableFilter"/> class.
/// </summary>
/// <param name="type">The event type.</param>
public RemoteEventBinarizableFilter(int type)
{
_type = type;
}
/** <inheritdoc /> */
public bool Invoke(IEvent evt)
{
return evt.Type == _type;
}
/** <inheritdoc /> */
public void WriteBinary(IBinaryWriter writer)
{
writer.GetRawWriter().WriteInt(_type);
}
/** <inheritdoc /> */
public void ReadBinary(IBinaryReader reader)
{
_type = reader.GetRawReader().ReadInt();
}
}
/// <summary>
/// Event test case.
/// </summary>
public class EventTestCase
{
/// <summary>
/// Gets or sets the type of the event.
/// </summary>
public ICollection<int> EventType { get; set; }
/// <summary>
/// Gets or sets the type of the event object.
/// </summary>
public Type EventObjectType { get; set; }
/// <summary>
/// Gets or sets the generate event action.
/// </summary>
public Action<IIgnite> GenerateEvent { get; set; }
/// <summary>
/// Gets or sets the verify events action.
/// </summary>
public Action<IEnumerable<IEvent>, IIgnite> VerifyEvents { get; set; }
/// <summary>
/// Gets or sets the event count.
/// </summary>
public int EventCount { get; set; }
/** <inheritdoc /> */
public override string ToString()
{
return EventObjectType.ToString();
}
}
/// <summary>
/// Custom event.
/// </summary>
public class MyEvent : IEvent
{
/** <inheritdoc /> */
public IgniteGuid Id
{
get { throw new NotImplementedException(); }
}
/** <inheritdoc /> */
public long LocalOrder
{
get { throw new NotImplementedException(); }
}
/** <inheritdoc /> */
public IClusterNode Node
{
get { throw new NotImplementedException(); }
}
/** <inheritdoc /> */
public string Message
{
get { throw new NotImplementedException(); }
}
/** <inheritdoc /> */
public int Type
{
get { throw new NotImplementedException(); }
}
/** <inheritdoc /> */
public string Name
{
get { throw new NotImplementedException(); }
}
/** <inheritdoc /> */
public DateTime Timestamp
{
get { throw new NotImplementedException(); }
}
/** <inheritdoc /> */
public string ToShortString()
{
throw new NotImplementedException();
}
}
public class MyEventStorage : IEventStorageSpi
{
// No-op.
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using Appleseed.Framework;
using System.Globalization;
using Appleseed.Framework.Providers.Geographic;
namespace Appleseed.Tests
{
[TestFixture]
public class GeographicProviderTest
{
[TestFixtureSetUp]
public void FixtureSetUp()
{
// Set up initial database environment for testing purposes
TestHelper.TearDownDB();
TestHelper.RecreateDBSchema();
}
[SetUp]
public void Init()
{
GeographicProvider.Current.CountriesFilter = "AR,BR,CL,UY";
}
[Test]
public void CountryCtorTest1()
{
try
{
Country c = new Country();
Assert.AreEqual(string.Empty, c.CountryID);
Assert.AreEqual(string.Empty, c.NeutralName);
Assert.AreEqual(string.Empty, c.AdministrativeDivisionNeutralName);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void CountryCtorTest2()
{
try
{
Country c = new Country("BR", "Brazil", "State");
Assert.AreEqual("BR", c.CountryID);
Assert.AreEqual("Brazil", c.NeutralName);
Assert.AreEqual("State", c.AdministrativeDivisionNeutralName);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void StateCtorTest1()
{
try
{
State s = new State();
Assert.AreEqual(string.Empty, s.CountryID);
Assert.AreEqual(string.Empty, s.NeutralName);
Assert.AreEqual(0, s.StateID);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void StateCtorTest2()
{
try
{
State s = new State(1000, "UY", "aName");
Assert.AreEqual("UY", s.CountryID);
Assert.AreEqual("aName", s.NeutralName);
Assert.AreEqual(1000, s.StateID);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void ProviderInstanciationTest()
{
try
{
GeographicProvider provider = GeographicProvider.Current;
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void ProviderInitializeTest()
{
try
{
string filteredCountries = GeographicProvider.Current.CountriesFilter;
Assert.AreEqual("AR,BR,CL,UY", filteredCountries);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetCountriesTest1()
{
try
{
IList<Country> countries = GeographicProvider.Current.GetCountries();
Assert.AreEqual(countries.Count, 4); // AR, BR, UY and CL
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetCountriesLocalizationTest1()
{
try
{
IList<Country> countries = GeographicProvider.Current.GetCountries();
CultureInfo currentCulture = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");
Assert.AreEqual("Argentinien", countries[0].Name);
Assert.AreEqual("Brasilien", countries[1].Name);
Assert.AreEqual("Chile", countries[2].Name);
Assert.AreEqual("Uruguay", countries[3].Name);
// again so we can test cached names
Assert.AreEqual("Argentinien", countries[0].Name);
Assert.AreEqual("Brasilien", countries[1].Name);
Assert.AreEqual("Chile", countries[2].Name);
Assert.AreEqual("Uruguay", countries[3].Name);
System.Threading.Thread.CurrentThread.CurrentCulture = currentCulture;
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetSortedCountriesTest1()
{
try
{
IList<Country> countries = GeographicProvider.Current.GetCountries(CountryFields.CountryID);
Assert.AreEqual(countries.Count, 4); // AR, BR, UY and CL
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetSortedCountriesTest2()
{
try
{
IList<Country> countries = GeographicProvider.Current.GetCountries(CountryFields.CountryID);
Assert.AreEqual("AR", countries[0].CountryID);
Assert.AreEqual("BR", countries[1].CountryID);
Assert.AreEqual("CL", countries[2].CountryID);
Assert.AreEqual("UY", countries[3].CountryID);
Assert.AreEqual("Argentina", countries[0].NeutralName);
Assert.AreEqual("Brazil", countries[1].NeutralName);
Assert.AreEqual("Chile", countries[2].NeutralName);
Assert.AreEqual("Uruguay", countries[3].NeutralName);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetSortedCountriesTest3()
{
try
{
IList<Country> countries = GeographicProvider.Current.GetCountries(CountryFields.NeutralName);
Assert.AreEqual("AR", countries[0].CountryID);
Assert.AreEqual("BR", countries[1].CountryID);
Assert.AreEqual("CL", countries[2].CountryID);
Assert.AreEqual("UY", countries[3].CountryID);
Assert.AreEqual("Argentina", countries[0].NeutralName);
Assert.AreEqual("Brazil", countries[1].NeutralName);
Assert.AreEqual("Chile", countries[2].NeutralName);
Assert.AreEqual("Uruguay", countries[3].NeutralName);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetSortedCountriesTest4()
{
try
{
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("es-ES");
IList<Country> countries = GeographicProvider.Current.GetCountries(CountryFields.Name);
Assert.AreEqual("AR", countries[0].CountryID);
Assert.AreEqual("BR", countries[1].CountryID);
Assert.AreEqual("CL", countries[2].CountryID);
Assert.AreEqual("UY", countries[3].CountryID);
Assert.AreEqual("Argentina", countries[0].NeutralName);
Assert.AreEqual("Brazil", countries[1].NeutralName);
Assert.AreEqual("Chile", countries[2].NeutralName);
Assert.AreEqual("Uruguay", countries[3].NeutralName);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetSortedCountriesTest5()
{
try
{
IList<Country> countries = GeographicProvider.Current.GetCountries(CountryFields.None);
Assert.AreEqual("AR", countries[0].CountryID);
Assert.AreEqual("BR", countries[1].CountryID);
Assert.AreEqual("CL", countries[2].CountryID);
Assert.AreEqual("UY", countries[3].CountryID);
Assert.AreEqual("Argentina", countries[0].NeutralName);
Assert.AreEqual("Brazil", countries[1].NeutralName);
Assert.AreEqual("Chile", countries[2].NeutralName);
Assert.AreEqual("Uruguay", countries[3].NeutralName);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetCountriesFilteredTest1()
{
try
{
IList<Country> countries = GeographicProvider.Current.GetCountries("AR,UY");
Assert.AreEqual(countries.Count, 2); // AR, and UY
Assert.AreEqual("AR", countries[0].CountryID);
Assert.AreEqual("UY", countries[1].CountryID);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetCountriesFilteredTest2()
{
try
{
IList<Country> countries = GeographicProvider.Current.GetCountries("LongFilter");
Assert.Fail("Should've thrown an ArgumentException");
}
catch (ArgumentException)
{
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetFilteredSortedCountriesTest1()
{
try
{
IList<Country> countries = GeographicProvider.Current.GetCountries("AR,UY", CountryFields.CountryID);
Assert.AreEqual(countries.Count, 2); // AR, UY
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetFilteredSortedCountriesTest2()
{
try
{
IList<Country> countries = GeographicProvider.Current.GetCountries("AR,UY", CountryFields.CountryID);
Assert.AreEqual("AR", countries[0].CountryID);
Assert.AreEqual("UY", countries[1].CountryID);
Assert.AreEqual("Argentina", countries[0].NeutralName);
Assert.AreEqual("Uruguay", countries[1].NeutralName);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetFilteredSortedCountriesTest3()
{
try
{
IList<Country> countries = GeographicProvider.Current.GetCountries("AR,UY", CountryFields.NeutralName);
Assert.AreEqual("AR", countries[0].CountryID);
Assert.AreEqual("UY", countries[1].CountryID);
Assert.AreEqual("Argentina", countries[0].NeutralName);
Assert.AreEqual("Uruguay", countries[1].NeutralName);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetFilteredSortedCountriesTest4()
{
try
{
IList<Country> countries = GeographicProvider.Current.GetCountries("AR,UY", CountryFields.CountryID);
Assert.AreEqual("AR", countries[0].CountryID);
Assert.AreEqual("UY", countries[1].CountryID);
Assert.AreEqual("Argentina", countries[0].NeutralName);
Assert.AreEqual("Uruguay", countries[1].NeutralName);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetFilteredSortedCountriesTest5()
{
try
{
IList<Country> countries = GeographicProvider.Current.GetCountries("AR,UY", CountryFields.None);
Assert.AreEqual("AR", countries[0].CountryID);
Assert.AreEqual("UY", countries[1].CountryID);
Assert.AreEqual("Argentina", countries[0].NeutralName);
Assert.AreEqual("Uruguay", countries[1].NeutralName);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetSortedCountriesNoCountryFilterTest1()
{
try
{
GeographicProvider.Current.CountriesFilter = string.Empty;
IList<Country> countries = GeographicProvider.Current.GetCountries(CountryFields.CountryID);
Assert.AreEqual(countries.Count, 237);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetSortedCountriesNoCountryFilterTest2()
{
try
{
GeographicProvider.Current.CountriesFilter = string.Empty;
IList<Country> countries = GeographicProvider.Current.GetCountries(CountryFields.CountryID);
Assert.AreEqual("AD", countries[0].CountryID);
Assert.AreEqual("AE", countries[1].CountryID);
Assert.AreEqual("AF", countries[2].CountryID);
Assert.AreEqual("ZW", countries[236].CountryID);
Assert.AreEqual("Andorra", countries[0].NeutralName);
Assert.AreEqual("United Arab Emirates", countries[1].NeutralName);
Assert.AreEqual("Afghanistan", countries[2].NeutralName);
Assert.AreEqual("Zimbabwe", countries[236].NeutralName);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetSortedCountriesNoCountryFilterTest3()
{
try
{
GeographicProvider.Current.CountriesFilter = string.Empty;
IList<Country> countries = GeographicProvider.Current.GetCountries(CountryFields.NeutralName);
Assert.AreEqual("AF", countries[0].CountryID);
Assert.AreEqual("AL", countries[1].CountryID);
Assert.AreEqual("ZM", countries[235].CountryID);
Assert.AreEqual("ZW", countries[236].CountryID);
Assert.AreEqual("Afghanistan", countries[0].NeutralName);
Assert.AreEqual("Albania", countries[1].NeutralName);
Assert.AreEqual("Zambia", countries[235].NeutralName);
Assert.AreEqual("Zimbabwe", countries[236].NeutralName);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetSortedCountriesNoCountryFilterTest4()
{
try
{
GeographicProvider.Current.CountriesFilter = string.Empty;
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("es-ES");
IList<Country> countries = GeographicProvider.Current.GetCountries(CountryFields.Name);
Assert.AreEqual("AF", countries[0].CountryID);
Assert.AreEqual("AL", countries[1].CountryID);
Assert.AreEqual("ZM", countries[235].CountryID);
Assert.AreEqual("ZW", countries[236].CountryID);
Assert.AreEqual("Afghanistan", countries[0].NeutralName);
Assert.AreEqual("Albania", countries[1].NeutralName);
Assert.AreEqual("Zambia", countries[235].NeutralName);
Assert.AreEqual("Zimbabwe", countries[236].NeutralName);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetSortedCountriesNoCountryFilterTest5()
{
try
{
GeographicProvider.Current.CountriesFilter = string.Empty;
IList<Country> countries = GeographicProvider.Current.GetCountries(CountryFields.None);
Assert.AreEqual("AD", countries[0].CountryID);
Assert.AreEqual("AE", countries[1].CountryID);
Assert.AreEqual("ZM", countries[235].CountryID);
Assert.AreEqual("ZW", countries[236].CountryID);
Assert.AreEqual("Andorra", countries[0].NeutralName);
Assert.AreEqual("United Arab Emirates", countries[1].NeutralName);
Assert.AreEqual("Zambia", countries[235].NeutralName);
Assert.AreEqual("Zimbabwe", countries[236].NeutralName);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetCountriesFilteredNoCountryFilterTest1()
{
try
{
GeographicProvider.Current.CountriesFilter = string.Empty;
IList<Country> countries = GeographicProvider.Current.GetCountries("AR,UY");
Assert.AreEqual(countries.Count, 2); // AR, and UY
Assert.AreEqual("AR", countries[0].CountryID);
Assert.AreEqual("UY", countries[1].CountryID);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetCountriesFilteredNoCountryFilterTest2()
{
try
{
GeographicProvider.Current.CountriesFilter = string.Empty;
IList<Country> countries = GeographicProvider.Current.GetCountries("LongFilter");
Assert.Fail("Should've thrown an ArgumentException");
}
catch (ArgumentException)
{
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetCountriesSortedNoCountryFilterTest1()
{
try
{
GeographicProvider.Current.CountriesFilter = string.Empty;
IList<Country> countries = GeographicProvider.Current.GetCountries(CountryFields.CountryID);
Assert.AreEqual(countries.Count, 237); // AR, BR, UY and CL
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetFilteredSortedCountriesNoCountryFilterTest1()
{
try
{
GeographicProvider.Current.CountriesFilter = string.Empty;
IList<Country> countries = GeographicProvider.Current.GetCountries("AR,UY", CountryFields.CountryID);
Assert.AreEqual(countries.Count, 2); // AR, UY
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetFilteredSortedCountriesNoCountryFilterTest2()
{
try
{
GeographicProvider.Current.CountriesFilter = string.Empty;
IList<Country> countries = GeographicProvider.Current.GetCountries("AR,UY", CountryFields.CountryID);
Assert.AreEqual("AR", countries[0].CountryID);
Assert.AreEqual("UY", countries[1].CountryID);
Assert.AreEqual("Argentina", countries[0].NeutralName);
Assert.AreEqual("Uruguay", countries[1].NeutralName);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetFilteredSortedCountriesNoCountryFilterTest3()
{
try
{
GeographicProvider.Current.CountriesFilter = string.Empty;
IList<Country> countries = GeographicProvider.Current.GetCountries("AR,UY", CountryFields.NeutralName);
Assert.AreEqual("AR", countries[0].CountryID);
Assert.AreEqual("UY", countries[1].CountryID);
Assert.AreEqual("Argentina", countries[0].NeutralName);
Assert.AreEqual("Uruguay", countries[1].NeutralName);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetFilteredSortedCountriesNoCountryFilterTest4()
{
try
{
GeographicProvider.Current.CountriesFilter = string.Empty;
IList<Country> countries = GeographicProvider.Current.GetCountries("AR,UY", CountryFields.CountryID);
Assert.AreEqual("AR", countries[0].CountryID);
Assert.AreEqual("UY", countries[1].CountryID);
Assert.AreEqual("Argentina", countries[0].NeutralName);
Assert.AreEqual("Uruguay", countries[1].NeutralName);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetFilteredSortedCountriesNoCountryFilterTest5()
{
try
{
GeographicProvider.Current.CountriesFilter = string.Empty;
IList<Country> countries = GeographicProvider.Current.GetCountries("AR,UY", CountryFields.None);
Assert.AreEqual("AR", countries[0].CountryID);
Assert.AreEqual("UY", countries[1].CountryID);
Assert.AreEqual("Argentina", countries[0].NeutralName);
Assert.AreEqual("Uruguay", countries[1].NeutralName);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetUnfilteredCountriesTest1()
{
try
{
IList<Country> allCountries = GeographicProvider.Current.GetUnfilteredCountries();
Assert.AreEqual(237, allCountries.Count);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetCountryStatesTest1()
{
try
{
IList<State> states = GeographicProvider.Current.GetCountryStates("AE");
Assert.AreEqual(4, states.Count);
foreach (State s in states)
{
switch (s.StateID)
{
case 599:
Assert.AreEqual("Abu Dhabi", s.NeutralName);
Assert.AreEqual("AE", s.CountryID);
break;
case 2082:
Assert.AreEqual("Ash Shariqah", s.NeutralName);
Assert.AreEqual("AE", s.CountryID);
break;
case 9470:
Assert.AreEqual("Dubai", s.NeutralName);
Assert.AreEqual("AE", s.CountryID);
break;
case 9217877:
Assert.AreEqual("Al l'Ayn", s.NeutralName);
Assert.AreEqual("AE", s.CountryID);
break;
default:
Assert.Fail();
break;
}
}
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetCountryStatesTest2()
{
try
{
IList<State> states = GeographicProvider.Current.GetCountryStates("PP");
Assert.AreEqual(0, states.Count);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetCountryDisplayNameTest1()
{
string displayName = GeographicProvider.Current.GetCountryDisplayName("BR", new CultureInfo("es-ES"));
Assert.AreEqual("Brasil", displayName);
}
[Test]
public void GetCountryDisplayNameTest2()
{
try
{
string displayName = GeographicProvider.Current.GetCountryDisplayName("ZZ", new CultureInfo("es-ES"));
Assert.Fail("ZZ isn't a CountryID");
}
catch (CountryNotFoundException)
{
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetStateDisplayNameTest1()
{
string displayName = GeographicProvider.Current.GetStateDisplayName(1003, new CultureInfo("en-US"));
Assert.AreEqual("Alabama", displayName);
}
[Test]
public void GetStateDisplayNameTest2()
{
try
{
string displayName = GeographicProvider.Current.GetStateDisplayName(-40, new CultureInfo("en-US"));
Assert.Fail("-40 is not a valid StateID");
}
catch (StateNotFoundException)
{
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetAdministrativeDivisionNameTest1()
{
string displayName = GeographicProvider.Current.GetAdministrativeDivisionName("Department", new CultureInfo("es-ES"));
Assert.AreEqual("Department", displayName);
}
[Test]
public void GetCountryTest1()
{
Country c = GeographicProvider.Current.GetCountry("US");
Assert.AreEqual("US", c.CountryID);
Assert.AreEqual("United States", c.NeutralName);
}
[Test]
public void GetCountryTest2()
{
Country c = GeographicProvider.Current.GetCountry("US");
CultureInfo currentCulture = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");
Assert.AreEqual("Vereinigte Staaten von Amerika", c.Name);
System.Threading.Thread.CurrentThread.CurrentCulture = currentCulture;
}
[Test]
public void GetCountryTest3()
{
try
{
Country c = GeographicProvider.Current.GetCountry("..");
Assert.Fail("Country .. doesn't exist");
}
catch (CountryNotFoundException)
{
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void GetStateTest1()
{
State state = GeographicProvider.Current.GetState(1003);
Assert.AreEqual("Alabama", state.NeutralName);
Assert.AreEqual(1003, state.StateID);
Assert.AreEqual("US", state.CountryID);
}
[Test]
public void GetStateTest2()
{
try
{
State c = GeographicProvider.Current.GetState(-100);
Assert.Fail("State -100 doesn't exist");
}
catch (StateNotFoundException)
{
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void CurrentCountryTest1()
{
Country actual = GeographicProvider.Current.CurrentCountry;
Country expected = GeographicProvider.Current.GetCountry(RegionInfo.CurrentRegion.Name);
Assert.AreEqual(expected, actual);
}
}
}
| |
// 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.Diagnostics;
using Xunit;
namespace System.Linq.Tests
{
public class ConcatTests : EnumerableTests
{
private static List<Func<IEnumerable<T>, IEnumerable<T>>> IdentityTransforms<T>()
{
// All of these transforms should take an enumerable and produce
// another enumerable with the same contents.
return new List<Func<IEnumerable<T>, IEnumerable<T>>>
{
e => e,
e => e.ToArray(),
e => e.ToList(),
e => e.Select(i => i),
e => e.Concat(Array.Empty<T>()),
e => ForceNotCollection(e),
e => e.Concat(ForceNotCollection(Array.Empty<T>()))
};
}
[Theory]
[InlineData(new int[] { 2, 3, 2, 4, 5 }, new int[] { 1, 9, 4 })]
public void SameResultsWithQueryAndRepeatCalls(IEnumerable<int> first, IEnumerable<int> second)
{
// workaround: xUnit type inference doesn't work if the input type is not T (like IEnumerable<T>)
SameResultsWithQueryAndRepeatCallsWorker(first, second);
}
[Theory]
[InlineData(new[] { "AAA", "", "q", "C", "#", "!@#$%^", "0987654321", "Calling Twice" }, new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS" })]
public void SameResultsWithQueryAndRepeatCalls(IEnumerable<string> first, IEnumerable<string> second)
{
// workaround: xUnit type inference doesn't work if the input type is not T (like IEnumerable<T>)
SameResultsWithQueryAndRepeatCallsWorker(first, second);
}
private static void SameResultsWithQueryAndRepeatCallsWorker<T>(IEnumerable<T> first, IEnumerable<T> second)
{
first = from item in first select item;
second = from item in second select item;
VerifyEqualsWorker(first.Concat(second), first.Concat(second));
VerifyEqualsWorker(second.Concat(first), second.Concat(first));
}
[Theory]
[InlineData(new int[] { }, new int[] { }, new int[] { })] // Both inputs are empty
[InlineData(new int[] { }, new int[] { 2, 6, 4, 6, 2 }, new int[] { 2, 6, 4, 6, 2 })] // One is empty
[InlineData(new int[] { 2, 3, 5, 9 }, new int[] { 8, 10 }, new int[] { 2, 3, 5, 9, 8, 10 })] // Neither side is empty
public void PossiblyEmptyInputs(IEnumerable<int> first, IEnumerable<int> second, IEnumerable<int> expected)
{
VerifyEqualsWorker(expected, first.Concat(second));
VerifyEqualsWorker(expected.Skip(first.Count()).Concat(expected.Take(first.Count())), second.Concat(first)); // Swap the inputs around
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerate()
{
var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Concat(Enumerable.Range(0, 3));
// Don't insist on this behaviour, but check it's correct if it happens
var en = iterator as IEnumerator<int>;
Assert.False(en != null && en.MoveNext());
}
[Fact]
public void FirstNull()
{
Assert.Throws<ArgumentNullException>("first", () => ((IEnumerable<int>)null).Concat(Enumerable.Range(0, 0)));
Assert.Throws<ArgumentNullException>("first", () => ((IEnumerable<int>)null).Concat(null)); // If both inputs are null, throw for "first" first
}
[Fact]
public void SecondNull()
{
Assert.Throws<ArgumentNullException>("second", () => Enumerable.Range(0, 0).Concat(null));
}
[Theory]
[MemberData(nameof(ArraySourcesData))]
[MemberData(nameof(SelectArraySourcesData))]
[MemberData(nameof(EnumerableSourcesData))]
[MemberData(nameof(NonCollectionSourcesData))]
[MemberData(nameof(ListSourcesData))]
[MemberData(nameof(ConcatOfConcatsData))]
[MemberData(nameof(ConcatWithSelfData))]
[MemberData(nameof(ChainedCollectionConcatData))]
public void VerifyEquals(IEnumerable<int> expected, IEnumerable<int> actual)
{
// workaround: xUnit type inference doesn't work if the input type is not T (like IEnumerable<T>)
VerifyEqualsWorker(expected, actual);
}
private static void VerifyEqualsWorker<T>(IEnumerable<T> expected, IEnumerable<T> actual)
{
// Returns a list of functions that, when applied to enumerable, should return
// another one that has equivalent contents.
var identityTransforms = IdentityTransforms<T>();
// We run the transforms N^2 times, by testing all transforms
// of expected against all transforms of actual.
foreach (var outTransform in identityTransforms)
{
foreach (var inTransform in identityTransforms)
{
Assert.Equal(outTransform(expected), inTransform(actual));
}
}
}
public static IEnumerable<object[]> ArraySourcesData() => GenerateSourcesData(outerTransform: e => e.ToArray());
public static IEnumerable<object[]> SelectArraySourcesData() => GenerateSourcesData(outerTransform: e => e.Select(i => i).ToArray());
public static IEnumerable<object[]> EnumerableSourcesData() => GenerateSourcesData();
public static IEnumerable<object[]> NonCollectionSourcesData() => GenerateSourcesData(outerTransform: e => ForceNotCollection(e));
public static IEnumerable<object[]> ListSourcesData() => GenerateSourcesData(outerTransform: e => e.ToList());
public static IEnumerable<object[]> ConcatOfConcatsData()
{
yield return new object[]
{
Enumerable.Range(0, 20),
Enumerable.Concat(
Enumerable.Concat(
Enumerable.Range(0, 4),
Enumerable.Range(4, 6)),
Enumerable.Concat(
Enumerable.Range(10, 3),
Enumerable.Range(13, 7)))
};
}
public static IEnumerable<object[]> ConcatWithSelfData()
{
IEnumerable<int> source = Enumerable.Repeat(1, 4).Concat(Enumerable.Repeat(1, 5));
source = source.Concat(source);
yield return new object[] { Enumerable.Repeat(1, 18), source };
}
public static IEnumerable<object[]> ChainedCollectionConcatData() => GenerateSourcesData(innerTransform: e => e.ToList());
private static IEnumerable<object[]> GenerateSourcesData(
Func<IEnumerable<int>, IEnumerable<int>> outerTransform = null,
Func<IEnumerable<int>, IEnumerable<int>> innerTransform = null)
{
outerTransform = outerTransform ?? (e => e);
innerTransform = innerTransform ?? (e => e);
for (int i = 0; i <= 6; i++)
{
var expected = Enumerable.Range(0, i * 3);
var actual = Enumerable.Empty<int>();
for (int j = 0; j < i; j++)
{
actual = outerTransform(actual.Concat(innerTransform(Enumerable.Range(j * 3, 3))));
}
yield return new object[] { expected, actual };
}
}
[Theory]
[MemberData(nameof(ManyConcatsData))]
public void ManyConcats(IEnumerable<IEnumerable<int>> sources, IEnumerable<int> expected)
{
foreach (var transform in IdentityTransforms<int>())
{
IEnumerable<int> concatee = Enumerable.Empty<int>();
foreach (var source in sources)
{
concatee = concatee.Concat(transform(source));
}
Assert.Equal(sources.Sum(s => s.Count()), concatee.Count());
VerifyEqualsWorker(sources.SelectMany(s => s), concatee);
}
}
public static IEnumerable<object[]> ManyConcatsData()
{
yield return new object[] { Enumerable.Repeat(Enumerable.Empty<int>(), 256), Enumerable.Empty<int>() };
yield return new object[] { Enumerable.Repeat(Enumerable.Repeat(6, 1), 256), Enumerable.Repeat(6, 256) };
// Make sure Concat doesn't accidentally swap around the sources, e.g. [3, 4], [1, 2] should not become [1..4]
yield return new object[] { Enumerable.Range(0, 500).Select(i => Enumerable.Repeat(i, 1)).Reverse(), Enumerable.Range(0, 500).Reverse() };
}
[Fact]
public void CountOfConcatIteratorShouldThrowExceptionOnIntegerOverflow()
{
var supposedlyLargeCollection = new DelegateBasedCollection<int> { CountWorker = () => int.MaxValue };
var tinyCollection = new DelegateBasedCollection<int> { CountWorker = () => 1 };
// We need to use checked arithmetic summing up the collections' counts.
Assert.Throws<OverflowException>(() => supposedlyLargeCollection.Concat(tinyCollection).Count());
Assert.Throws<OverflowException>(() => tinyCollection.Concat(tinyCollection).Concat(supposedlyLargeCollection).Count());
Assert.Throws<OverflowException>(() => tinyCollection.Concat(tinyCollection).Concat(tinyCollection).Concat(supposedlyLargeCollection).Count());
}
}
}
| |
using System;
using Org.BouncyCastle.Crypto.Parameters;
namespace Org.BouncyCastle.Crypto.Modes
{
/**
* implements Cipher-Block-Chaining (CBC) mode on top of a simple cipher.
*/
public class CbcBlockCipher
: IBlockCipher
{
private byte[] IV, cbcV, cbcNextV;
private int blockSize;
private IBlockCipher cipher;
private bool encrypting;
/**
* Basic constructor.
*
* @param cipher the block cipher to be used as the basis of chaining.
*/
public CbcBlockCipher(
IBlockCipher cipher)
{
this.cipher = cipher;
this.blockSize = cipher.GetBlockSize();
this.IV = new byte[blockSize];
this.cbcV = new byte[blockSize];
this.cbcNextV = new byte[blockSize];
}
/**
* return the underlying block cipher that we are wrapping.
*
* @return the underlying block cipher that we are wrapping.
*/
public IBlockCipher GetUnderlyingCipher()
{
return cipher;
}
/**
* Initialise the cipher and, possibly, the initialisation vector (IV).
* If an IV isn't passed as part of the parameter, the IV will be all zeros.
*
* @param forEncryption if true the cipher is initialised for
* encryption, if false for decryption.
* @param param the key and other data required by the cipher.
* @exception ArgumentException if the parameters argument is
* inappropriate.
*/
public void Init(
bool forEncryption,
ICipherParameters parameters)
{
this.encrypting = forEncryption;
if (parameters is ParametersWithIV)
{
ParametersWithIV ivParam = (ParametersWithIV)parameters;
byte[] iv = ivParam.GetIV();
if (iv.Length != blockSize)
{
throw new ArgumentException("initialisation vector must be the same length as block size");
}
Array.Copy(iv, 0, IV, 0, iv.Length);
parameters = ivParam.Parameters;
}
Reset();
cipher.Init(encrypting, parameters);
}
/**
* return the algorithm name and mode.
*
* @return the name of the underlying algorithm followed by "/CBC".
*/
public string AlgorithmName
{
get { return cipher.AlgorithmName + "/CBC"; }
}
public bool IsPartialBlockOkay
{
get { return false; }
}
/**
* return the block size of the underlying cipher.
*
* @return the block size of the underlying cipher.
*/
public int GetBlockSize()
{
return cipher.GetBlockSize();
}
/**
* Process one block of input from the array in and write it to
* the out array.
*
* @param in the array containing the input data.
* @param inOff offset into the in array the data starts at.
* @param out the array the output data will be copied into.
* @param outOff the offset into the out array the output will start at.
* @exception DataLengthException if there isn't enough data in in, or
* space in out.
* @exception InvalidOperationException if the cipher isn't initialised.
* @return the number of bytes processed and produced.
*/
public int ProcessBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
return (encrypting)
? EncryptBlock(input, inOff, output, outOff)
: DecryptBlock(input, inOff, output, outOff);
}
/**
* reset the chaining vector back to the IV and reset the underlying
* cipher.
*/
public void Reset()
{
Array.Copy(IV, 0, cbcV, 0, IV.Length);
Array.Clear(cbcNextV, 0, cbcNextV.Length);
cipher.Reset();
}
/**
* Do the appropriate chaining step for CBC mode encryption.
*
* @param in the array containing the data to be encrypted.
* @param inOff offset into the in array the data starts at.
* @param out the array the encrypted data will be copied into.
* @param outOff the offset into the out array the output will start at.
* @exception DataLengthException if there isn't enough data in in, or
* space in out.
* @exception InvalidOperationException if the cipher isn't initialised.
* @return the number of bytes processed and produced.
*/
private int EncryptBlock(
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
if ((inOff + blockSize) > input.Length)
{
throw new DataLengthException("input buffer too short");
}
/*
* XOR the cbcV and the input,
* then encrypt the cbcV
*/
for (int i = 0; i < blockSize; i++)
{
cbcV[i] ^= input[inOff + i];
}
int length = cipher.ProcessBlock(cbcV, 0, outBytes, outOff);
/*
* copy ciphertext to cbcV
*/
Array.Copy(outBytes, outOff, cbcV, 0, cbcV.Length);
return length;
}
/**
* Do the appropriate chaining step for CBC mode decryption.
*
* @param in the array containing the data to be decrypted.
* @param inOff offset into the in array the data starts at.
* @param out the array the decrypted data will be copied into.
* @param outOff the offset into the out array the output will start at.
* @exception DataLengthException if there isn't enough data in in, or
* space in out.
* @exception InvalidOperationException if the cipher isn't initialised.
* @return the number of bytes processed and produced.
*/
private int DecryptBlock(
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
if ((inOff + blockSize) > input.Length)
{
throw new DataLengthException("input buffer too short");
}
Array.Copy(input, inOff, cbcNextV, 0, blockSize);
int length = cipher.ProcessBlock(input, inOff, outBytes, outOff);
/*
* XOR the cbcV and the output
*/
for (int i = 0; i < blockSize; i++)
{
outBytes[outOff + i] ^= cbcV[i];
}
/*
* swap the back up buffer into next position
*/
byte[] tmp;
tmp = cbcV;
cbcV = cbcNextV;
cbcNextV = tmp;
return length;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hyak.Common;
using Microsoft.WindowsAzure.Management;
using Microsoft.WindowsAzure.Management.Models;
namespace Microsoft.WindowsAzure.Management
{
/// <summary>
/// The Service Management API includes operations for listing the
/// available data center locations for a hosted service in your
/// subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/gg441299.aspx for
/// more information)
/// </summary>
internal partial class LocationOperations : IServiceOperations<ManagementClient>, ILocationOperations
{
/// <summary>
/// Initializes a new instance of the LocationOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal LocationOperations(ManagementClient client)
{
this._client = client;
}
private ManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.ManagementClient.
/// </summary>
public ManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// The List Locations operation lists all of the data center locations
/// that are valid for your subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/gg441293.aspx
/// for more information)
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Locations operation response.
/// </returns>
public async Task<LocationsListResponse> ListAsync(CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/locations";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-10-01");
// 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
LocationsListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new LocationsListResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement locationsSequenceElement = responseDoc.Element(XName.Get("Locations", "http://schemas.microsoft.com/windowsazure"));
if (locationsSequenceElement != null)
{
foreach (XElement locationsElement in locationsSequenceElement.Elements(XName.Get("Location", "http://schemas.microsoft.com/windowsazure")))
{
LocationsListResponse.Location locationInstance = new LocationsListResponse.Location();
result.Locations.Add(locationInstance);
XElement nameElement = locationsElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
locationInstance.Name = nameInstance;
}
XElement displayNameElement = locationsElement.Element(XName.Get("DisplayName", "http://schemas.microsoft.com/windowsazure"));
if (displayNameElement != null)
{
string displayNameInstance = displayNameElement.Value;
locationInstance.DisplayName = displayNameInstance;
}
XElement availableServicesSequenceElement = locationsElement.Element(XName.Get("AvailableServices", "http://schemas.microsoft.com/windowsazure"));
if (availableServicesSequenceElement != null)
{
foreach (XElement availableServicesElement in availableServicesSequenceElement.Elements(XName.Get("AvailableService", "http://schemas.microsoft.com/windowsazure")))
{
locationInstance.AvailableServices.Add(availableServicesElement.Value);
}
}
XElement storageCapabilitiesElement = locationsElement.Element(XName.Get("StorageCapabilities", "http://schemas.microsoft.com/windowsazure"));
if (storageCapabilitiesElement != null)
{
StorageCapabilities storageCapabilitiesInstance = new StorageCapabilities();
locationInstance.StorageCapabilities = storageCapabilitiesInstance;
XElement storageAccountTypesSequenceElement = storageCapabilitiesElement.Element(XName.Get("StorageAccountTypes", "http://schemas.microsoft.com/windowsazure"));
if (storageAccountTypesSequenceElement != null)
{
storageCapabilitiesInstance.StorageAccountTypes = new List<string>();
foreach (XElement storageAccountTypesElement in storageAccountTypesSequenceElement.Elements(XName.Get("StorageAccountType", "http://schemas.microsoft.com/windowsazure")))
{
storageCapabilitiesInstance.StorageAccountTypes.Add(storageAccountTypesElement.Value);
}
}
}
XElement computeCapabilitiesElement = locationsElement.Element(XName.Get("ComputeCapabilities", "http://schemas.microsoft.com/windowsazure"));
if (computeCapabilitiesElement != null)
{
ComputeCapabilities computeCapabilitiesInstance = new ComputeCapabilities();
locationInstance.ComputeCapabilities = computeCapabilitiesInstance;
XElement virtualMachinesRoleSizesSequenceElement = computeCapabilitiesElement.Element(XName.Get("VirtualMachinesRoleSizes", "http://schemas.microsoft.com/windowsazure"));
if (virtualMachinesRoleSizesSequenceElement != null)
{
foreach (XElement virtualMachinesRoleSizesElement in virtualMachinesRoleSizesSequenceElement.Elements(XName.Get("RoleSize", "http://schemas.microsoft.com/windowsazure")))
{
computeCapabilitiesInstance.VirtualMachinesRoleSizes.Add(virtualMachinesRoleSizesElement.Value);
}
}
XElement webWorkerRoleSizesSequenceElement = computeCapabilitiesElement.Element(XName.Get("WebWorkerRoleSizes", "http://schemas.microsoft.com/windowsazure"));
if (webWorkerRoleSizesSequenceElement != null)
{
foreach (XElement webWorkerRoleSizesElement in webWorkerRoleSizesSequenceElement.Elements(XName.Get("RoleSize", "http://schemas.microsoft.com/windowsazure")))
{
computeCapabilitiesInstance.WebWorkerRoleSizes.Add(webWorkerRoleSizesElement.Value);
}
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Runtime.Serialization;
using ASC.Core;
using ASC.Core.Common.Settings;
using ASC.Files.Core;
namespace ASC.Web.Files.Classes
{
[Serializable]
[DataContract]
public class FilesSettings : BaseSettings<FilesSettings>
{
[DataMember(Name = "EnableThirdpartySettings")]
public bool EnableThirdpartySetting { get; set; }
[DataMember(Name = "FastDelete")]
public bool FastDeleteSetting { get; set; }
[DataMember(Name = "StoreOriginalFiles")]
public bool StoreOriginalFilesSetting { get; set; }
[DataMember(Name = "UpdateIfExist")]
public bool UpdateIfExistSetting { get; set; }
[DataMember(Name = "ConvertNotify")]
public bool ConvertNotifySetting { get; set; }
[DataMember(Name = "SortedBy")]
public SortedByType DefaultSortedBySetting { get; set; }
[DataMember(Name = "SortedAsc")]
public bool DefaultSortedAscSetting { get; set; }
[DataMember(Name = "HideConfirmConvertSave")]
public bool HideConfirmConvertSaveSetting { get; set; }
[DataMember(Name = "HideConfirmConvertOpen")]
public bool HideConfirmConvertOpenSetting { get; set; }
[DataMember(Name = "Forcesave")]
public bool ForcesaveSetting { get; set; }
[DataMember(Name = "StoreForcesave")]
public bool StoreForcesaveSetting { get; set; }
[DataMember(Name = "HideRecent")]
public bool HideRecentSetting { get; set; }
[DataMember(Name = "HideFavorites")]
public bool HideFavoritesSetting { get; set; }
[DataMember(Name = "HideTemplates")]
public bool HideTemplatesSetting { get; set; }
[DataMember(Name = "DownloadZip")]
private bool DownloadTarGzSetting { get; set; }
public override ISettings GetDefault()
{
return new FilesSettings
{
FastDeleteSetting = false,
EnableThirdpartySetting = true,
StoreOriginalFilesSetting = true,
UpdateIfExistSetting = false,
ConvertNotifySetting = true,
DefaultSortedBySetting = SortedByType.DateAndTime,
DefaultSortedAscSetting = false,
HideConfirmConvertSaveSetting = false,
HideConfirmConvertOpenSetting = false,
ForcesaveSetting = false,
StoreForcesaveSetting = false,
HideFavoritesSetting = false,
HideRecentSetting = false,
HideTemplatesSetting = false,
DownloadTarGzSetting = false,
};
}
public override Guid ID
{
get { return new Guid("{03B382BD-3C20-4f03-8AB9-5A33F016316E}"); }
}
public static bool ConfirmDelete
{
set
{
var setting = LoadForCurrentUser();
setting.FastDeleteSetting = !value;
setting.SaveForCurrentUser();
}
get { return !LoadForCurrentUser().FastDeleteSetting; }
}
public static bool EnableThirdParty
{
set
{
var setting = Load();
setting.EnableThirdpartySetting = value;
setting.Save();
}
get { return Load().EnableThirdpartySetting; }
}
public static bool StoreOriginalFiles
{
set
{
var setting = LoadForCurrentUser();
setting.StoreOriginalFilesSetting = value;
setting.SaveForCurrentUser();
}
get { return LoadForCurrentUser().StoreOriginalFilesSetting; }
}
public static bool UpdateIfExist
{
set
{
var setting = LoadForCurrentUser();
setting.UpdateIfExistSetting = value;
setting.SaveForCurrentUser();
}
get { return LoadForCurrentUser().UpdateIfExistSetting; }
}
public static bool ConvertNotify
{
set
{
var setting = LoadForCurrentUser();
setting.ConvertNotifySetting = value;
setting.SaveForCurrentUser();
}
get { return LoadForCurrentUser().ConvertNotifySetting; }
}
public static bool HideConfirmConvertSave
{
set
{
var setting = LoadForCurrentUser();
setting.HideConfirmConvertSaveSetting = value;
setting.SaveForCurrentUser();
}
get { return LoadForCurrentUser().HideConfirmConvertSaveSetting; }
}
public static bool HideConfirmConvertOpen
{
set
{
var setting = LoadForCurrentUser();
setting.HideConfirmConvertOpenSetting = value;
setting.SaveForCurrentUser();
}
get { return LoadForCurrentUser().HideConfirmConvertOpenSetting; }
}
public static OrderBy DefaultOrder
{
set
{
var setting = LoadForCurrentUser();
setting.DefaultSortedBySetting = value.SortedBy;
setting.DefaultSortedAscSetting = value.IsAsc;
setting.SaveForCurrentUser();
}
get
{
var setting = LoadForCurrentUser();
return new OrderBy(setting.DefaultSortedBySetting, setting.DefaultSortedAscSetting);
}
}
public static bool Forcesave
{
set
{
var setting = LoadForCurrentUser();
setting.ForcesaveSetting = value;
setting.SaveForCurrentUser();
}
get { return LoadForCurrentUser().ForcesaveSetting; }
}
public static bool StoreForcesave
{
set
{
if (CoreContext.Configuration.Personal) throw new NotSupportedException();
var setting = Load();
setting.StoreForcesaveSetting = value;
setting.Save();
}
get { return !CoreContext.Configuration.Personal && Load().StoreForcesaveSetting; }
}
public static bool RecentSection
{
set
{
var setting = LoadForCurrentUser();
setting.HideRecentSetting = !value;
setting.SaveForCurrentUser();
}
get { return !LoadForCurrentUser().HideRecentSetting; }
}
public static bool FavoritesSection
{
set
{
var setting = LoadForCurrentUser();
setting.HideFavoritesSetting = !value;
setting.SaveForCurrentUser();
}
get { return !LoadForCurrentUser().HideFavoritesSetting; }
}
public static bool TemplatesSection
{
set
{
var setting = LoadForCurrentUser();
setting.HideTemplatesSetting = !value;
setting.SaveForCurrentUser();
}
get { return !LoadForCurrentUser().HideTemplatesSetting; }
}
public static bool DownloadTarGz
{
set
{
var setting = LoadForCurrentUser();
setting.DownloadTarGzSetting = value;
setting.SaveForCurrentUser();
}
get => LoadForCurrentUser().DownloadTarGzSetting;
}
}
}
| |
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 AbovetheTreeline.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;
}
}
}
| |
/*
FluorineFx open source library
Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.Text;
using System.Collections;
using System.IO;
using System.Globalization;
using System.Runtime.Serialization;
using System.Reflection;
using System.Data.SqlTypes;
using System.Xml;
using FluorineFx.Util;
namespace FluorineFx.Json
{
/// <summary>
/// Provides methods for converting between common language runtime types and JavaScript types.
/// </summary>
public class JavaScriptConvert
{
/// <summary>
/// Represents JavaScript's boolean value true as a string. This field is read-only.
/// </summary>
public static readonly string True;
/// <summary>
/// Represents JavaScript's boolean value false as a string. This field is read-only.
/// </summary>
public static readonly string False;
/// <summary>
/// Represents JavaScript's null as a string. This field is read-only.
/// </summary>
public static readonly string Null;
/// <summary>
/// Represents JavaScript's undefined as a string. This field is read-only.
/// </summary>
public static readonly string Undefined;
internal static long InitialJavaScriptDateTicks;
internal static DateTime MinimumJavaScriptDate;
static JavaScriptConvert()
{
True = "true";
False = "false";
Null = "null";
Undefined = "undefined";
InitialJavaScriptDateTicks = (new DateTime(1970, 1, 1)).Ticks;
MinimumJavaScriptDate = new DateTime(100, 1, 1);
}
/// <summary>
/// Converts the <see cref="DateTime"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="DateTime"/>.</returns>
public static string ToString(DateTime value)
{
long javaScriptTicks = ConvertDateTimeToJavaScriptTicks(value);
return "new Date(" + javaScriptTicks + ")";
}
internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime)
{
if (dateTime < MinimumJavaScriptDate)
dateTime = MinimumJavaScriptDate;
long javaScriptTicks = (dateTime.Ticks - InitialJavaScriptDateTicks) / (long)10000;
return javaScriptTicks;
}
internal static DateTime ConvertJavaScriptTicksToDateTime(long javaScriptTicks)
{
DateTime dateTime = new DateTime((javaScriptTicks * 10000) + InitialJavaScriptDateTicks);
return dateTime;
}
/// <summary>
/// Converts the <see cref="Boolean"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="Boolean"/>.</returns>
public static string ToString(bool value)
{
return (value) ? True : False;
}
/// <summary>
/// Converts the <see cref="Char"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="Char"/>.</returns>
public static string ToString(char value)
{
return ToString(char.ToString(value));
}
/// <summary>
/// Converts the <see cref="Enum"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="Enum"/>.</returns>
public static string ToString(Enum value)
{
return value.ToString();
}
/// <summary>
/// Converts the <see cref="Int32"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="Int32"/>.</returns>
public static string ToString(int value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Int16"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="Int16"/>.</returns>
public static string ToString(short value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt16"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="UInt16"/>.</returns>
[CLSCompliant(false)]
public static string ToString(ushort value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt32"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="UInt32"/>.</returns>
[CLSCompliant(false)]
public static string ToString(uint value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Int64"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="Int64"/>.</returns>
public static string ToString(long value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt64"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="UInt64"/>.</returns>
[CLSCompliant(false)]
public static string ToString(ulong value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Single"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="Single"/>.</returns>
public static string ToString(float value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Double"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="Double"/>.</returns>
public static string ToString(double value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Byte"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="Byte"/>.</returns>
public static string ToString(byte value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="SByte"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="SByte"/>.</returns>
[CLSCompliant(false)]
public static string ToString(sbyte value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Decimal"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="SByte"/>.</returns>
public static string ToString(decimal value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Guid"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="Guid"/>.</returns>
public static string ToString(Guid value)
{
return '"' + value.ToString("D", CultureInfo.InvariantCulture) + '"';
}
/// <summary>
/// Converts the <see cref="String"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="String"/>.</returns>
public static string ToString(string value)
{
return ToString(value, '"');
}
/// <summary>
/// Converts the <see cref="String"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="delimter">The string delimiter character.</param>
/// <returns>A Json string representation of the <see cref="String"/>.</returns>
public static string ToString(string value, char delimter)
{
return JavaScriptUtils.ToEscapedJavaScriptString(value, delimter, true);
}
/// <summary>
/// Converts the <see cref="Object"/> to it's JavaScript string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A Json string representation of the <see cref="Object"/>.</returns>
public static string ToString(object value)
{
if (value == null)
{
return Null;
}
else if (value is IConvertible)
{
IConvertible convertible = value as IConvertible;
switch (convertible.GetTypeCode())
{
case TypeCode.String:
return ToString((string)convertible);
case TypeCode.Char:
return ToString((char)convertible);
case TypeCode.Boolean:
return ToString((bool)convertible);
case TypeCode.SByte:
return ToString((sbyte)convertible);
case TypeCode.Int16:
return ToString((short)convertible);
case TypeCode.UInt16:
return ToString((ushort)convertible);
case TypeCode.Int32:
return ToString((int)convertible);
case TypeCode.Byte:
return ToString((byte)convertible);
case TypeCode.UInt32:
return ToString((uint)convertible);
case TypeCode.Int64:
return ToString((long)convertible);
case TypeCode.UInt64:
return ToString((ulong)convertible);
case TypeCode.Single:
return ToString((float)convertible);
case TypeCode.Double:
return ToString((double)convertible);
case TypeCode.DateTime:
return ToString((DateTime)convertible);
case TypeCode.Decimal:
return ToString((decimal)convertible);
}
}
throw new ArgumentException(string.Format("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.", value.GetType()));
}
/// <summary>
/// Serializes the specified object to a Json object.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <returns>A Json string representation of the object.</returns>
public static string SerializeObject(object value)
{
return SerializeObject(value, null);
}
public static string SerializeObject(object value, params JsonConverter[] converters)
{
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
JsonSerializer jsonSerializer = new JsonSerializer();
#if (NET_1_1)
if (!CollectionUtils.IsNullOrEmpty(converters))
#else
if (!CollectionUtils.IsNullOrEmpty<JsonConverter>(converters))
#endif
{
for (int i = 0; i < converters.Length; i++)
{
jsonSerializer.Converters.Add(converters[i]);
}
}
using (JsonWriter jsonWriter = new JsonWriter(sw))
{
//jsonWriter.Formatting = Formatting.Indented;
jsonSerializer.Serialize(jsonWriter, value);
}
return sw.ToString();
}
/// <summary>
/// Deserializes the specified object to a Json object.
/// </summary>
/// <param name="value">The object to deserialize.</param>
/// <returns>The deserialized object from the Json string.</returns>
public static object DeserializeObject(string value)
{
return DeserializeObject(value, null, null);
}
/// <summary>
/// Deserializes the specified object to a Json object.
/// </summary>
/// <param name="value">The object to deserialize.</param>
/// <param name="type">The <see cref="Type"/> of object being deserialized.</param>
/// <returns>The deserialized object from the Json string.</returns>
public static object DeserializeObject(string value, Type type)
{
return DeserializeObject(value, type, null);
}
#if (NET_1_1)
#else
/// <summary>
/// Deserializes the specified object to a Json object.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize.</typeparam>
/// <param name="value">The object to deserialize.</param>
/// <returns>The deserialized object from the Json string.</returns>
public static T DeserializeObject<T>(string value)
{
return DeserializeObject<T>(value, null);
}
/// <summary>
/// Deserializes the specified object to a Json object.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize.</typeparam>
/// <param name="value">The object to deserialize.</param>
/// <param name="converters">Converters to use while deserializing.</param>
/// <returns>The deserialized object from the Json string.</returns>
public static T DeserializeObject<T>(string value, params JsonConverter[] converters)
{
return (T)DeserializeObject(value, typeof(T), converters);
}
#endif
public static object DeserializeObject(string value, Type type, params JsonConverter[] converters)
{
StringReader sr = new StringReader(value);
JsonSerializer jsonSerializer = new JsonSerializer();
#if (NET_1_1)
if (!CollectionUtils.IsNullOrEmpty(converters))
#else
if (!CollectionUtils.IsNullOrEmpty<JsonConverter>(converters))
#endif
{
for (int i = 0; i < converters.Length; i++)
{
jsonSerializer.Converters.Add(converters[i]);
}
}
object deserializedValue;
using (JsonReader jsonReader = new JsonReader(sr))
{
deserializedValue = jsonSerializer.Deserialize(jsonReader, type);
}
return deserializedValue;
}
public static object DeserializeObject(TextReader reader)
{
JsonSerializer jsonSerializer = new JsonSerializer();
object deserializedValue;
using (JsonReader jsonReader = new JsonReader(reader))
{
deserializedValue = jsonSerializer.Deserialize(jsonReader);
}
return deserializedValue;
}
public static bool IsNull(object o)
{
//
// Equals a null reference?
//
if (o == null)
return true;
//
// Equals self, of course?
//
if (o.Equals(JavaScriptConvert.Null))
return true;
//
// Equals the logical null value used in database applications?
//
if (System.Convert.IsDBNull(o))
return true;
//
// Instance is not one of the known logical null values.
//
return false;
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.IO;
public class TimelineWindow : EditorWindow
{
#region Constants
public const float VerticalTimeLineVisibleWidth = 1;
public const float VerticalTimeLineGrabWidth = 20;
public class EventSelectionData
{
public CutsceneTrackItem ItemToSelect;
public bool UnselectPreviousItems;
public EventSelectionData(CutsceneTrackItem itemToSelect, bool unselectPreviousItems)
{
ItemToSelect = itemToSelect;
UnselectPreviousItems = unselectPreviousItems;
}
}
public enum CollisionResolutionType
{
None,
Snap,
MoveDown,
Collision_Test,
}
// Track groups
public const float SpaceBetweenFoldouts = 4.5f;
public const float SpaceBetweenLabels = 2;
public const int TrackGroupIndent = 20;
// tool bar
public const float ViewTypeButtonWidth = 100;
public const float PlayButtonWidth = 20;
public const float PointerModeButtonWidth = 40;
public const float ZoomSliderWidth = 200;
public const float PlaySpeedSliderWidth = 125;
public const float MinZoom = 0.3f;
public const float MaxZoom = 15.0f;
public const float ToolBarHeight = 20;
public const float FileButtonWidth = 30;
// scene view
public const float CutsceneListWidth = 200;
// cutscene view
public const float CutsceneSelectionBoxWidth = 150;
public const float CutsceneEventsListWidth = 0;
public const float CutsceneTrackGroupsListWidth = 230;
public const float EventNameColumnWidth = 100;
public const float EventGroupColumnWidth = 100;
public const float EventDataWidth = 300;
public const float EventDataWidth_MIN = 300;
public const float EventDataWidth_MAX = 500;
public const float VerticalScrollBarWidth = 16;
public const float HorizontalScrollBarHeight = 16;
public const float NoteBoxHeight = 100;
// timeline
public const float TimeSliderHeight = 20;
public const int NumTimeDivisions = 10;
public const float PixelSpaceBetweenTimeIntervals = 50;
public const float DefaultTimeDivisionInterval = 1; //seconds
public const float TimeLineHeight = 20;
public const float TimeLineStartingY = ToolBarHeight + TimeSliderHeight;
// Track Groups
public const float GroupStartingXOffset = 20;
public const float GroupStartingX = CutsceneEventsListWidth + GroupStartingXOffset;
// Tracks
public const float TrackStartingX = CutsceneEventsListWidth + CutsceneTrackGroupsListWidth + 10;
public const float TrackStartingY = ToolBarHeight + TimeSliderHeight + TimeLineHeight;
public const float ScrollStartingY = TrackStartingY - TimeSliderHeight - TimeLineHeight;
public const float TrackWidthSubtractor = TrackStartingX + /*EventDataWidth +*/ 20;
public const float TrackHeightSubtractor = ScrollStartingY;
public const float TrackHeight = 20;
public const float DefaultScrollWidth = 1000;
public const float DefaultScrollHeight = 10000;
public const float EventWidth = 10;
public const float ScrollerWidth = 15;
// Events
public static Color AlphaWhite = new Color(1, 1, 1, 0.5f);
public static Color SelectionBoxColor = new Color(46f / 255f, 185f / 255f, 215f / 255f);
public static Color Transparent = new Color(1, 1, 1, 0);
public const string EventControlName = "EventControlHeader";
#endregion
#region Variables
protected GUIContent m_TooltipContent = new GUIContent();
protected float m_Zoom = 1;
public CutsceneTrackGroupManager m_TrackGroupManager;
//public Sequence m_EventManager;
//protected List<CutsceneTrackItem> m_SelectedEvents = new List<CutsceneTrackItem>();
public string MachinimaFolderLocation = string.Empty;
public string UnitySequencerFolderLocation = string.Empty;
protected Vector2 m_CutsceneViewDataList;
protected Vector2 m_CutsceneEventDataScrollPos;
protected bool m_ShowNotes = true;
// Textures
public Texture FoldOutExpandedTex;
public Texture FoldOutNotExpandedTex;
public Texture TimeSliderVerticalLine;
public Texture TimeSliderArrow;
public Texture VerticalTimeLine;
public Texture PlayButton;
public Texture ResetButton;
public Texture StopButton;
// time line
public Rect m_TimeNumberPosition = new Rect();
public Rect m_TimeSliderPosition = new Rect();
public Rect m_CurrentTimeTextPosition = new Rect();
public Rect m_VerticalTimeLinePosition = new Rect();
public Rect m_VerticalTimeLineGrabArea = new Rect();
public Rect m_ClickableTimeLineArea = new Rect();
// Tracks
public Vector2 m_TrackScrollPos;
public float m_TimeSliderTime;
public Rect m_TrackStartingPosition = new Rect(TrackStartingX, TrackStartingY, 1, TrackHeight);
public Rect m_TrackArea = new Rect();
public Rect m_TrackScrollArea = new Rect();
public Rect m_AllTrackPositions = new Rect();
public Rect m_TrackBackground = new Rect();
// groups (left-hand side)
public Vector2 m_TrackGroupScrollPos;
public Rect m_TrackGroupArea = new Rect();
public Rect m_TrackGroupScrollArea = new Rect();
public Rect m_SelectedTrackGroupArea = new Rect(GroupStartingX, 0, CutsceneTrackGroupsListWidth - 10, TrackHeight);
public Rect m_TrackGroupDropArea = new Rect(GroupStartingX, 0, CutsceneTrackGroupsListWidth - 10, TrackHeight);
public float m_MoveToTime;
// lists
public List<CutsceneTrackItem> m_ItemsToBeAdded = new List<CutsceneTrackItem>();
protected List<EventSelectionData> m_ItemsToBeSelected = new List<EventSelectionData>();
// input
protected TimelineInput m_InputController;
protected float m_CurrentTime;
protected float m_PreviousTime;
protected CutsceneTrackGroup m_SelectedTrackGroup;
protected CutsceneTrackGroup m_DropLocationTrackGroup;
protected bool m_VerboseText = true;
public bool m_MockPlaying;
public Stack<CutsceneTrackItem> m_DeletedEvents = new Stack<CutsceneTrackItem>(); // used as an undo stack during runtime
protected int m_SelectedIndex;
protected List<string> m_TimeObjectNames = new List<string>();
protected float m_TimeScale = 1;
protected float m_EventDataColumnWidth = EventDataWidth;
#endregion
#region Properties
virtual public string SavedWindowPosXKey { get { return ""; } }
virtual public string SavedWindowPosYKey { get { return ""; } }
virtual public string SavedWindowWKey { get { return ""; } }
virtual public string SavedWindowHKey { get { return ""; } }
virtual public float StartTime
{
get { return 0; }
set { }
}
virtual public float EndTime
{
get { return 1; }
set { }
}
virtual public float Length
{
get { return 1; }
set { }
}
virtual public EditorTimelineObjectManager TimelineObjectManager
{
get { return null; }
}
virtual public CutsceneTrackGroupManager GroupManager { get { return null; } }
public float Zoom
{
get { return m_Zoom; }
set { m_Zoom = value; m_Zoom = Mathf.Clamp(m_Zoom, MinZoom, MaxZoom); }
}
protected TimelineInput InputController { get { return m_InputController; } }
public float CurrentTime { get { return m_CurrentTime; } }
virtual public CutsceneTrackItem SelectedEvent { get { return/* m_SelectedEvents.Count > 0 ? m_SelectedEvents[0] : */null; } }
virtual public List<CutsceneTrackItem> SelectedEvents
{
get { return null; }// m_SelectedEvents; }
}
virtual public int NumSelectedEvents
{
get { return 0; }// m_SelectedEvents.Count; }
}
public List<EventSelectionData> EventsQueuedForSelection
{
get { return m_ItemsToBeSelected; }
}
public CutsceneTrackGroup SelectedTrackGroup
{
get { return m_SelectedTrackGroup; }
}
public GUIContent TooltipContent
{
get { return m_TooltipContent; }
}
public float TimeScale
{
get { return m_TimeScale; }
}
#endregion
#region Functions
protected virtual void OnDestroy()
{
SaveLocation();
}
void OnFocus()
{
Setup();
}
public virtual void LoadTextures()
{
TimeSliderVerticalLine = (Texture)AssetDatabase.LoadAssetAtPath(MachinimaFolderLocation + "Gizmos/VerticalTimeSlider.png", typeof(Texture));
TimeSliderArrow = (Texture2D)AssetDatabase.LoadAssetAtPath(MachinimaFolderLocation + "Gizmos/TimeSliderArrow.png", typeof(Texture2D));
VerticalTimeLine = (Texture2D)AssetDatabase.LoadAssetAtPath(MachinimaFolderLocation + "Gizmos/VerticalLine.png", typeof(Texture2D));
FoldOutNotExpandedTex = (Texture)AssetDatabase.LoadAssetAtPath(MachinimaFolderLocation + "Gizmos/FoldOutArrow_NotExpanded.png", typeof(Texture));
FoldOutExpandedTex = (Texture)AssetDatabase.LoadAssetAtPath(MachinimaFolderLocation + "Gizmos/FoldOutArrow_Expanded.png", typeof(Texture));
PlayButton = (Texture)AssetDatabase.LoadAssetAtPath(MachinimaFolderLocation + "Gizmos/Button_Play.png", typeof(Texture));
ResetButton = (Texture)AssetDatabase.LoadAssetAtPath(MachinimaFolderLocation + "Gizmos/Button_Reset.png", typeof(Texture));
StopButton = (Texture)AssetDatabase.LoadAssetAtPath(MachinimaFolderLocation + "Gizmos/Button_Stop.png", typeof(Texture));
}
protected void SaveLocation()
{
PlayerPrefs.SetFloat(SavedWindowPosXKey, position.x);
PlayerPrefs.SetFloat(SavedWindowPosYKey, position.y);
PlayerPrefs.SetFloat(SavedWindowWKey, position.width);
PlayerPrefs.SetFloat(SavedWindowHKey, position.height);
}
public virtual void Setup() { }
protected virtual void Update() { }
protected virtual void UpdateMockPlay() { }
#region GUI Functions
protected virtual void OnGUI() { }
/// <summary>
/// Handles the drawing of the scene tabs, play button, options, etc
/// </summary>
protected virtual void DrawToolbar() { }
protected virtual void DrawZoomer()
{
if (GUILayout.Button("-", EditorStyles.toolbarButton, GUILayout.Width(PlayButtonWidth)))
{
m_Zoom -= 0.1f;
}
if (GUILayout.Button("+", EditorStyles.toolbarButton, GUILayout.Width(PlayButtonWidth)))
{
m_Zoom += 0.1f;
}
m_Zoom = EditorGUILayout.Slider(m_Zoom, MinZoom, MaxZoom, GUILayout.Width(ZoomSliderWidth));
}
protected virtual void DrawPlaySpeed()
{
m_TimeScale = EditorGUILayout.Slider(m_TimeScale, 1, 10, GUILayout.Width(ZoomSliderWidth));
}
/// <summary>
/// Draws all track groups and their nested children if they are expanded. Does not use recursion, uses depth first traversal
/// </summary>
protected void DrawTrackGroups()
{
if (GroupManager == null || GroupManager.NumGroups == 0)
{
return;
}
m_TrackGroupArea.Set(GroupStartingX - GroupStartingXOffset, ToolBarHeight, CutsceneTrackGroupsListWidth - 15 + GroupStartingXOffset, position.height);
m_TrackGroupScrollPos.y = m_TrackScrollPos.y; // maintain the same y between the 2 scroll views
m_TrackGroupScrollArea.Set(m_TrackGroupArea.x, m_TrackGroupArea.y, 1000, m_TrackScrollArea.height);
m_TrackGroupScrollPos = GUI.BeginScrollView(m_TrackGroupArea, m_TrackGroupScrollPos, m_TrackGroupScrollArea);
{
m_TrackScrollPos.y = m_TrackGroupScrollPos.y; // maintain the same y between the 2 scroll views
Color prev = GUI.color;
if (m_SelectedTrackGroup != null && !m_SelectedTrackGroup.Hidden)
{
GUI.color = CutsceneTrackItem.SelectedColor;
m_SelectedTrackGroupArea.y = m_SelectedTrackGroup.GroupNamePosition.y;
GUI.Box(m_SelectedTrackGroupArea, "");
GUI.color = prev;
}
if (m_DropLocationTrackGroup != null)
{
GUI.color = SelectionBoxColor;
m_TrackGroupDropArea.y = m_DropLocationTrackGroup.GroupNamePosition.y;
GUI.Box(m_TrackGroupDropArea, "");
GUI.color = prev;
}
int indentAmount = 0;
float yPos = TrackStartingY;
// depth first traversal
Stack<CutsceneTrackGroup> stack = new Stack<CutsceneTrackGroup>();
Stack<int> indentLevel = new Stack<int>();
CutsceneTrackGroup currGroup = null;
Rect foldoutPos = new Rect();
foreach (CutsceneTrackGroup group in GroupManager.m_TrackGroups)
{
indentAmount = 0;
stack.Clear();
indentLevel.Clear();
stack.Push(group);
indentLevel.Push(indentAmount);
while (stack.Count > 0)
{
currGroup = stack.Pop();
indentAmount = indentLevel.Pop();
currGroup.GroupNamePosition.Set(GroupStartingX + indentAmount, yPos, CutsceneTrackGroupsListWidth, TrackHeight);
currGroup.TrackPosition.Set(TrackStartingX, yPos, position.width, TrackHeight);
currGroup.GroupNamePosition.width -= indentAmount;
if (currGroup.HasChildren)
{
foldoutPos = currGroup.GroupNamePosition;
foldoutPos.width = 15;
foldoutPos.x -= foldoutPos.width;
bool previouslyExpanded = currGroup.Expanded;
prev = GUI.color;
GUI.color = Transparent;
currGroup.Expanded = GUI.Toggle(foldoutPos, currGroup.Expanded, "");
GUI.color = prev;
GUI.DrawTexture(foldoutPos, currGroup.Expanded ? FoldOutExpandedTex : FoldOutNotExpandedTex);
if (currGroup.EditingName)
{
currGroup.GroupName = GUI.TextField(currGroup.GroupNamePosition, currGroup.GroupName);
}
else
{
GUI.Label(currGroup.GroupNamePosition, currGroup.GroupName);
}
if (previouslyExpanded != currGroup.Expanded)
{
// it changed this frame
GroupManager.ChangedExpanded(currGroup, currGroup.Expanded);
// hidden track items can't be selected, so unselect them
List<CutsceneTrackItem> selectedTrackItems = GroupManager.GetSelectedTrackItems(currGroup);
selectedTrackItems.ForEach(ti => UnSelectTrackItem(ti));
}
}
else
{
if (currGroup.EditingName)
{
currGroup.GroupName = GUI.TextField(currGroup.GroupNamePosition, currGroup.GroupName);
}
else
{
GUI.Label(currGroup.GroupNamePosition, currGroup.GroupName);
}
}
// draw children only if expanded
if (currGroup.Expanded)
{
for (int i = currGroup.NumChildren - 1; i >= 0; i--)
{
stack.Push(currGroup.Children[i]);
indentLevel.Push(indentAmount + TrackGroupIndent);
}
}
yPos += TrackHeight;
}
}
}
GUI.EndScrollView();
}
protected void SetupTrackPositions(float cutsceneLength)
{
// setup rectangles to be the correct sizes based on the window width/height
m_TrackArea.Set(TrackStartingX, ScrollStartingY, position.width - (TrackWidthSubtractor + m_EventDataColumnWidth), position.height - TrackHeightSubtractor);
m_TrackScrollArea.Set(TrackStartingX, ScrollStartingY, CalculateTrackScrollAreaWidth(cutsceneLength), DefaultScrollHeight);
m_AllTrackPositions.Set(m_TrackScrollArea.x, TrackStartingY, m_TrackScrollArea.width, m_TrackScrollArea.height);
}
/// <summary>
/// Searchs for all timeline objects of type T in the scene and loads them into the list
/// </summary>
/// <typeparam name="T"></typeparam>
public void LoadAllTimelineObjects<T>() where T : TimelineObject
{
TimelineObjectManager.FindTimelineObjects<T>();
LoadTimelineObjectNames(TimelineObjectManager.GetAllTimelineObjects());
if (m_SelectedIndex >= TimelineObjectManager.NumObjects)
{
m_SelectedIndex = Mathf.Max(0, TimelineObjectManager.NumObjects - 1);
}
}
/// <summary>
/// Setups up the drop down list that has all the timeline object names in it
/// </summary>
/// <param name="timelineObjects"></param>
public void LoadTimelineObjectNames(List<TimelineObject> timelineObjects)
{
m_TimeObjectNames.Clear();
for (int i = 0; i < timelineObjects.Count; i++)
{
m_TimeObjectNames.Add(timelineObjects[i].NameIdentifier);
}
}
void DrawCutsceneTracks(CutsceneTrackGroupManager trackGroupManager)
{
if (trackGroupManager == null)
{
return;
}
Color col = GUI.color;
GUI.color = AlphaWhite;
m_TrackBackground.Set(m_TrackArea.x, m_TrackArea.y, m_TrackArea.width, m_TrackScrollArea.height);
m_TrackBackground.width = Mathf.Max(m_TrackScrollArea.width, m_TrackArea.width);
m_TrackBackground.height = Mathf.Max(m_TrackScrollArea.height, m_TrackArea.height);
GUI.Box(m_TrackBackground, "");
GUI.color = col;
// draw tracks
m_TrackStartingPosition.width = Mathf.Max(m_TrackScrollArea.width, m_TrackArea.width);
trackGroupManager.SetStartingPosition(m_TrackStartingPosition);
trackGroupManager.Draw(TrackHeight);
if (InputController.IsRubberBandSelecting)
{
col = GUI.color;
GUI.color = SelectionBoxColor;
GUI.Box(InputController.RubberBandSelectionArea, "");
GUI.color = col;
}
}
bool DrawCutsceneTrackItem(CutsceneTrackItem trackItem, float timelineStartTime, float timelineEndTime, Rect scrollArea)
{
Color prevCol = GUI.color;
// update position based on start time
trackItem.GuiPosition.x = GetPositionFromTime(timelineStartTime, timelineEndTime, trackItem.StartTime, scrollArea);
if (trackItem.LengthRepresented)
{
trackItem.GuiPosition.width = GetWidthFromTime(timelineStartTime, timelineEndTime,
trackItem.StartTime + trackItem.Length, trackItem.GuiPosition.x, scrollArea);
}
bool pressed = trackItem.Draw(m_VerboseText, m_TooltipContent);
GUI.color = prevCol;
return pressed;
}
void DrawCutsceneEvents(Cutscene cutscene)
{
if (cutscene == null)
{
return;
}
Color prevCol = GUI.color;
foreach (CutsceneEvent ce in cutscene.CutsceneEvents)
{
GUI.SetNextControlName(EventControlName + ce.UniqueId);
if (DrawCutsceneTrackItem(ce, cutscene.StartTime, cutscene.EndTime, m_TrackScrollArea)) { }
}
GUI.color = prevCol;
}
protected virtual void SetupTimeSliderData() { }
protected void DrawTimeSlider(float startTime, float endTime)
{
float timelinePosX = GetPositionFromTime(startTime, endTime, m_CurrentTime, m_TrackScrollArea) - 7f; // TODO: fix offset
m_TimeSliderPosition.Set(timelinePosX, ToolBarHeight + m_TrackScrollPos.y, 15, TrackHeight);
m_CurrentTimeTextPosition.Set(m_TimeSliderPosition.x + 20, m_TimeSliderPosition.y, 50, TrackHeight);
m_ClickableTimeLineArea.Set(TrackStartingX, m_TimeSliderPosition.y, m_TrackArea.width - ScrollerWidth, m_TimeSliderPosition.height + TrackHeight);
GUI.Label(m_CurrentTimeTextPosition, m_CurrentTime.ToString("f2"));
GUI.DrawTexture(m_TimeSliderPosition, TimeSliderArrow);
m_VerticalTimeLinePosition.Set(timelinePosX + 7.5f, m_TimeSliderPosition.y, VerticalTimeLineVisibleWidth, m_TrackArea.height - 18);
// same as the vertical position, but wider so that it's easier to grab with the mouse
m_VerticalTimeLineGrabArea.Set(m_VerticalTimeLinePosition.x - VerticalTimeLineGrabWidth * 0.5f, m_VerticalTimeLinePosition.y, VerticalTimeLineGrabWidth, m_VerticalTimeLinePosition.height);
GUI.DrawTexture(m_VerticalTimeLinePosition, TimeSliderVerticalLine);
}
protected void DrawTimeLine(float startTime)
{
// TODO: on large cutscenes this causes a huge slow down. CLEAN THIS UP
// always draw the startime time
DrawTimeInterval(startTime, 0, 0);
int numIntervals = CalculateNumIntervalsShown(Mathf.Max(m_TrackArea.width, m_TrackScrollArea.width));
for (int i = 0; i < numIntervals; i++)
{
DrawTimeInterval(startTime, i + 1, i + 1);
}
}
protected void DrawTimeInterval(float startTime, int offset, int interval)
{
// draw the text
float posX = TrackStartingX + (float)(offset) * PixelSpaceBetweenTimeIntervals * m_Zoom;
m_TimeNumberPosition.Set(posX, TimeLineStartingY + m_TrackScrollPos.y, 60, TrackHeight);
GUI.Label(m_TimeNumberPosition, CalculateScaledTimeDivisionInterval(startTime, interval).ToString("f0"));
// draw the vertical line
m_TimeNumberPosition.Set(posX, TrackStartingY + m_TrackScrollPos.y, 1, m_TrackBackground.height);
GUI.DrawTexture(m_TimeNumberPosition, VerticalTimeLine);
}
protected virtual void DrawEventData(List<CutsceneTrackItem> selectedEvents) { }
#endregion
#region Data Functions
#region Button Handlers
public virtual void ChangedData() { }
protected virtual void SimulatePlay(Cutscene cutscene, bool play) { }
protected virtual void StopCutscene(Cutscene cutscene, bool resetPlayHead) { }
void PauseCutscene(Cutscene cutscene)
{
EditorApplication.ExecuteMenuItem("Edit/Pause");
}
public void AddTrackGroup()
{
GroupManager.AddTrack("Track");
}
public void AddTrackGroup(CutsceneTrackGroupManager groupManager)
{
groupManager.AddTrack("Track");
ChangedData();
}
virtual public void RemoveTrackGroup(CutsceneTrackGroup group)
{
RemoveTrackGroup(GroupManager, group);
}
virtual public void RemoveTrackGroup(CutsceneTrackGroupManager groupManager, CutsceneTrackGroup group) { }
virtual public CutsceneTrackItem DuplicateEvent(CutsceneTrackItem ce)
{
return DuplicateEvent(ce, CollisionResolutionType.MoveDown);
}
virtual public CutsceneTrackItem DuplicateEvent(CutsceneTrackItem ce, CollisionResolutionType resolutionType)
{
CutsceneTrackItem newEvent = CreateEventAtPosition(new Vector2(ce.GuiPosition.x, ce.GuiPosition.y), resolutionType);
newEvent.Name += "(Dup)";
//UnSelectTrackItem(ce);
return newEvent;
}
public CutsceneTrackItem CreateEventAtPosition(Vector2 position)
{
return CreateEventAtPosition(position, CollisionResolutionType.MoveDown);
}
public virtual CutsceneTrackItem CreateEventAtPosition(Vector2 position, CollisionResolutionType resolutionType)
{
return null;
}
virtual public void RemoveSelectedEvents()
{
List<CutsceneTrackItem> selected = SelectedEvents;
for (int i = 0; i < selected.Count; i++)
{
selected[i].SetSelected(false);
}
}
virtual public void RemoveEvent(CutsceneTrackItem ce) { }
#endregion
#region Time Calculations
/// <summary>
/// Shift the list of given events to the specific time while maintaining their time offsets.
/// The event with the earliest start time will be placed exactly at the provided time
/// </summary>
/// <param name="events"></param>
/// <param name="time"></param>
public void MoveEventsToTime(List<CutsceneTrackItem> events, float time)
{
events.Sort((a, b) => a.StartTime < b.StartTime ? -1 : 1);
float earliest = events[0].StartTime;
foreach (CutsceneTrackItem ce in events)
{
float currStartTime = ce.StartTime;
SetTrackItemTime(ce, time + (currStartTime - earliest), CollisionResolutionType.MoveDown);
}
ChangedData();
}
/// <summary>
/// Tests to see if one track item is collidiing horizontally with another. If there is a collision
/// the collider is returned. Null if there is no collision
/// </summary>
/// <param name="trackItem"></param>
/// <param name="testTime"></param>
/// <returns></returns>
public CutsceneTrackItem TestHorizontalCollision(CutsceneTrackItem trackItem, float testTime)
{
float prevStartTime = trackItem.StartTime;
trackItem.StartTime = testTime;
trackItem.StartTime = Mathf.Max(0, trackItem.StartTime); // can't be less than 0
Rect prevPos = trackItem.GuiPosition;
trackItem.GuiPosition.x = GetPositionFromTime(StartTime, EndTime, trackItem.StartTime, m_TrackScrollArea);
CutsceneTrackItem collider = InputController.GetHorizontalCollider(GroupManager, trackItem);
// reset the time and position
trackItem.StartTime = prevStartTime;
trackItem.GuiPosition = prevPos;
return collider;
}
/// <summary>
/// Offsets the time of the specified trackitem by the given amount. Returns true if a collision occured
/// </summary>
/// <param name="trackItem"></param>
/// <param name="offset"></param>
/// <param name="resolution"></param>
/// <returns></returns>
public bool OffsetTrackItemTime(CutsceneTrackItem trackItem, float offset, CollisionResolutionType resolution)
{
return SetTrackItemTime(trackItem, trackItem.StartTime + offset, resolution);
}
/// <summary>
/// Sets the time of the specified track item. Returns true if a collision occured
/// </summary>
/// <param name="trackItem"></param>
/// <param name="time"></param>
/// <param name="resolution"></param>
public bool SetTrackItemTime(CutsceneTrackItem trackItem, float time, CollisionResolutionType resolution)
{
if (trackItem.Locked)
{
return false;
}
float prevStartTime = trackItem.StartTime;
trackItem.StartTime = time;
trackItem.StartTime = Mathf.Max(0, trackItem.StartTime); // can't be less than 0
Rect prevPos = trackItem.GuiPosition;
trackItem.GuiPosition.x = GetPositionFromTime(StartTime, EndTime, trackItem.StartTime, m_TrackScrollArea);
// update the cutscene length and starttime based on the event's new time
StartTime = Mathf.Min(StartTime, trackItem.StartTime);
Length = CalculateTimelineLength();
bool collision = time < 0 || InputController.IsCollidingHorizontally(GroupManager, trackItem);
switch (resolution)
{
case CollisionResolutionType.Collision_Test:
if (collision)
{
// we don't want to actually move the track item, we're only checking to see if it's new position
// will cause a collision.
trackItem.StartTime = prevStartTime;
trackItem.GuiPosition = prevPos;
return collision;
}
break;
case CollisionResolutionType.Snap:
if (collision)
{
trackItem.StartTime = prevStartTime;
trackItem.GuiPosition = prevPos;
}
break;
case CollisionResolutionType.MoveDown:
if (collision)
{
InputController.ResolveHorizontalCollision(GroupManager, trackItem);
}
break;
}
if (trackItem == SelectedEvent)
{
// only scroll based off the event that is selected. This prevents weird jumping when moving an event group
InputController.CheckHorizontalScroll(trackItem.GuiPosition, prevStartTime < trackItem.StartTime);
}
return collision;
}
/// <summary>
/// Helper for drawing vertical time line intervals on the time line
/// </summary>
/// <param name="cutsceneLength"></param>
/// <returns></returns>
public float CalculateTrackScrollAreaWidth(float cutsceneLength)
{
return cutsceneLength * PixelSpaceBetweenTimeIntervals * m_Zoom;
}
/// <summary>
/// Helper for drawing vertical time line intervals on the time line
/// </summary>
/// <param name="startTime"></param>
/// <param name="interval"></param>
/// <returns></returns>
public float CalculateScaledTimeDivisionInterval(float startTime, int interval)
{
return startTime + DefaultTimeDivisionInterval * (float)interval;
}
/// <summary>
/// Returns the number of vertical time line intervals that should be shown based on zoom and pixel space between them
/// </summary>
/// <param name="trackAreaWidth"></param>
/// <returns></returns>
public int CalculateNumIntervalsShown(float trackAreaWidth)
{
return (int)((trackAreaWidth - VerticalScrollBarWidth) / (PixelSpaceBetweenTimeIntervals * m_Zoom));
}
/// <summary>
/// Returns the timeline time based on a gui position in the timeline
/// </summary>
/// <param name="itemPosition"></param>
/// <returns></returns>
public float GetTimeFromScrollPosition(Vector2 itemPosition)
{
return GetTimeFromScrollPosition(new Rect(itemPosition.x, itemPosition.y, 1, 1));
}
/// <summary>
/// Returns the timeline time based on a gui position in the timeline
/// </summary>
/// <param name="itemPosition"></param>
/// <returns></returns>
public float GetTimeFromScrollPosition(Rect itemPosition)
{
return GetTimeFromScrollPosition(StartTime, EndTime, m_TrackScrollArea, itemPosition);
}
/// <summary>
/// Returns the timeline time based on a gui position in the timeline
/// </summary>
/// <param name="cutsceneStartTime"></param>
/// <param name="cutsceneEndTime"></param>
/// <param name="scollerPosition"></param>
/// <param name="itemPosition"></param>
/// <returns></returns>
public float GetTimeFromScrollPosition(float cutsceneStartTime, float cutsceneEndTime, Rect scollerPosition, Rect itemPosition)
{
// I don't use unity's lerp because it clamps time between 0 and 1
return cutsceneStartTime + (cutsceneEndTime - cutsceneStartTime) * (itemPosition.x - scollerPosition.x) / (scollerPosition.width);
}
/// <summary>
/// Get the x pixel coordinate of a track item base on it start time on the timeline
/// </summary>
/// <param name="trackItemStartTime"></param>
/// <returns></returns>
public float GetPositionFromTime(float trackItemStartTime)
{
return GetPositionFromTime(StartTime, EndTime, trackItemStartTime, m_TrackScrollArea);
}
/// <summary>
/// Get the x pixel coordinate of a track item base on it start time on the timeline
/// </summary>
/// <param name="cutsceneStartTime"></param>
/// <param name="cutsceneEndTime"></param>
/// <param name="trackItemStartTime"></param>
/// <param name="scollerPosition"></param>
/// <returns></returns>
public float GetPositionFromTime(float cutsceneStartTime, float cutsceneEndTime, float trackItemStartTime, Rect scollerPosition)
{
return Mathf.Lerp(scollerPosition.x, scollerPosition.x + scollerPosition.width, (trackItemStartTime - cutsceneStartTime) / (Mathf.Max(cutsceneEndTime, 1) - cutsceneStartTime));
}
/// <summary>
/// Get the gui width in pixels of a track item based on it's duration on the timeline
/// </summary>
/// <param name="trackItemEndTime"></param>
/// <param name="trackItemPosX"></param>
/// <returns></returns>
public float GetWidthFromTime(float trackItemEndTime, float trackItemPosX)
{
return GetWidthFromTime(StartTime, EndTime, trackItemEndTime, trackItemPosX, m_TrackScrollArea);
}
/// <summary>
/// Get the gui width in pixels of a track item based on it's duration on the timeline
/// </summary>
/// <param name="cutsceneStartTime"></param>
/// <param name="cutsceneEndTime"></param>
/// <param name="trackItemEndTime"></param>
/// <param name="trackItemPosX"></param>
/// <param name="scrollerPosition"></param>
/// <returns></returns>
public float GetWidthFromTime(float cutsceneStartTime, float cutsceneEndTime, float trackItemEndTime, float trackItemPosX, Rect scrollerPosition)
{
return GetPositionFromTime(cutsceneStartTime, cutsceneEndTime,
trackItemEndTime, scrollerPosition) - trackItemPosX;
}
public virtual void OffsetTime(float time) { }
public virtual void SetTime(float time) { }
#endregion
#endregion
#region Selection Functions
/// <summary>
/// Returns true if the given event is selected
/// </summary>
/// <param name="trackItem"></param>
/// <returns></returns>
public bool IsEventSelected(CutsceneTrackItem trackItem)
{
return trackItem.Selected;
//return m_SelectedEvents.FindIndex(ce => ce.UniqueId == trackItem.UniqueId) != -1;
}
/// <summary>
/// Selects/highlights a track item and allows you to see the data associated with it
/// </summary>
/// <param name="trackItem"></param>
/// <param name="unselectPrevious"></param>
public void SelectTrackItem(CutsceneTrackItem trackItem, bool unselectPrevious)
{
m_ItemsToBeSelected.Add(new EventSelectionData(trackItem, unselectPrevious));
}
/// <summary>
/// This function should only be used in this class and in the update loop. See comment in Update()
/// </summary>
/// <param name="trackItem"></param>
/// <param name="unselectPrevious"></param>
protected virtual void INTERNAL_SelectTrackItem(CutsceneTrackItem trackItem, bool unselectPrevious) { }
public void SelectTrackGroup(CutsceneTrackGroup group)
{
m_SelectedTrackGroupArea.y = group.GroupNamePosition.y;
group.SelectTrack(true);
if (m_SelectedTrackGroup != group)
{
// new group selected, unselect the previous
UnSelectTrackGroup();
m_SelectedTrackGroup = group;
}
}
public void SetTrackGroupDropLocation(CutsceneTrackGroup group)
{
m_TrackGroupDropArea.y = group.GroupNamePosition.y;
m_DropLocationTrackGroup = group;
Repaint();
}
/// <summary>
/// Unselects all track items and clears the selected event list
/// </summary>
public void UnSelectAll()
{
List<CutsceneTrackItem> selected = SelectedEvents;
foreach (CutsceneTrackItem item in selected)
{
UnSelectTrackItem(item);
}
//for (int i = 0; i < m_SelectedEvents.Count; i++)
//{
// UnSelectTrackItem(m_SelectedEvents[i]);
// // unselect track item removes from this list
// i--;
//}
//m_SelectedEvents.Clear();
try
{
// for catching errors in unity 3.5
GUI.FocusControl("");
}
catch { }
}
/// <summary>
/// Unselects the specific track item if it is selected
/// </summary>
/// <param name="trackItem"></param>
virtual public void UnSelectTrackItem(CutsceneTrackItem trackItem)
{
//foreach (CutsceneTrackItem item in SelectedEvents)
//{
// if (trackItem == item)
// {
// UnSelectTrackItem(item);
// trackItem.SetSelected(false);
// }
//}
if (trackItem != null)
{
trackItem.SetSelected(false);
}
// search for it based on its unique id
int index = SelectedEvents.FindIndex(ce => ce.UniqueId == trackItem.UniqueId);
if (index != -1)
{
SelectedEvents.RemoveAt(index);
}
// I MIGHT NEED THIS!!
/*if (m_SelectedEvents.Count > 0)
{
try
{
GUI.FocusControl(EventControlName + m_SelectedEvents[0].UniqueId);
}
catch { }
}*/
}
/// <summary>
/// Unsselects the currently selected track group
/// </summary>
public void UnSelectTrackGroup()
{
if (m_SelectedTrackGroup != null)
{
m_SelectedTrackGroup.SelectTrack(false);
m_SelectedTrackGroup.EditingName = false;
}
m_SelectedTrackGroup = null;
}
/// <summary>
/// Clears gui drawing associated the track group drop area
/// </summary>
public void ClearDropArea()
{
m_DropLocationTrackGroup = null;
Repaint();
}
public virtual void AttachAllEventsToTracks() { }
public virtual float CalculateTimelineLength() { return 10; }
public virtual CutsceneTrackItem GetTrackItemContainingPoint(Vector2 point) { return null; }
#endregion
#endregion
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace MvcApplication4.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
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);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.