context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
//
// TableHeapBuffer.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2010 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Text;
using Mono.Cecil.PE;
using RVA = System.UInt32;
#if !READ_ONLY
namespace Mono.Cecil.Metadata {
sealed class TableHeapBuffer : HeapBuffer {
readonly ModuleDefinition module;
readonly MetadataBuilder metadata;
internal MetadataTable [] tables = new MetadataTable [45];
bool large_string;
bool large_blob;
readonly int [] coded_index_sizes = new int [13];
readonly Func<Table, int> counter;
public override bool IsEmpty {
get { return false; }
}
public TableHeapBuffer (ModuleDefinition module, MetadataBuilder metadata)
: base (24)
{
this.module = module;
this.metadata = metadata;
this.counter = GetTableLength;
}
int GetTableLength (Table table)
{
var md_table = tables [(int) table];
return md_table != null ? md_table.Length : 0;
}
public TTable GetTable<TTable> (Table table) where TTable : MetadataTable, new ()
{
var md_table = (TTable) tables [(int) table];
if (md_table != null)
return md_table;
md_table = new TTable ();
tables [(int) table] = md_table;
return md_table;
}
public void WriteBySize (uint value, int size)
{
if (size == 4)
WriteUInt32 (value);
else
WriteUInt16 ((ushort) value);
}
public void WriteBySize (uint value, bool large)
{
if (large)
WriteUInt32 (value);
else
WriteUInt16 ((ushort) value);
}
public void WriteString (uint @string)
{
WriteBySize (@string, large_string);
}
public void WriteBlob (uint blob)
{
WriteBySize (blob, large_blob);
}
public void WriteRID (uint rid, Table table)
{
var md_table = tables [(int) table];
WriteBySize (rid, md_table == null ? false : md_table.IsLarge);
}
int GetCodedIndexSize (CodedIndex coded_index)
{
var index = (int) coded_index;
var size = coded_index_sizes [index];
if (size != 0)
return size;
return coded_index_sizes [index] = coded_index.GetSize (counter);
}
public void WriteCodedRID (uint rid, CodedIndex coded_index)
{
WriteBySize (rid, GetCodedIndexSize (coded_index));
}
public void WriteTableHeap ()
{
WriteUInt32 (0); // Reserved
WriteByte (GetTableHeapVersion ()); // MajorVersion
WriteByte (0); // MinorVersion
WriteByte (GetHeapSizes ()); // HeapSizes
WriteByte (10); // Reserved2
WriteUInt64 (GetValid ()); // Valid
WriteUInt64 (0x0016003301fa00); // Sorted
WriteRowCount ();
WriteTables ();
}
void WriteRowCount ()
{
for (int i = 0; i < tables.Length; i++) {
var table = tables [i];
if (table == null || table.Length == 0)
continue;
WriteUInt32 ((uint) table.Length);
}
}
void WriteTables ()
{
for (int i = 0; i < tables.Length; i++) {
var table = tables [i];
if (table == null || table.Length == 0)
continue;
table.Write (this);
}
}
ulong GetValid ()
{
ulong valid = 0;
for (int i = 0; i < tables.Length; i++) {
var table = tables [i];
if (table == null || table.Length == 0)
continue;
table.Sort ();
valid |= (1UL << i);
}
return valid;
}
byte GetHeapSizes ()
{
byte heap_sizes = 0;
if (metadata.string_heap.IsLarge) {
large_string = true;
heap_sizes |= 0x01;
}
if (metadata.blob_heap.IsLarge) {
large_blob = true;
heap_sizes |= 0x04;
}
return heap_sizes;
}
byte GetTableHeapVersion ()
{
switch (module.Runtime) {
case TargetRuntime.Net_1_0:
case TargetRuntime.Net_1_1:
return 1;
default:
return 2;
}
}
public void FixupData (RVA data_rva)
{
var table = GetTable<FieldRVATable> (Table.FieldRVA);
if (table.length == 0)
return;
var field_idx_size = GetTable<FieldTable> (Table.Field).IsLarge ? 4 : 2;
var previous = this.position;
base.position = table.position;
for (int i = 0; i < table.length; i++) {
var rva = ReadUInt32 ();
base.position -= 4;
WriteUInt32 (rva + data_rva);
base.position += field_idx_size;
}
base.position = previous;
}
}
sealed class ResourceBuffer : ByteBuffer {
public ResourceBuffer ()
: base (0)
{
}
public uint AddResource (byte [] resource)
{
var offset = (uint) this.position;
WriteInt32 (resource.Length);
WriteBytes (resource);
return offset;
}
}
sealed class DataBuffer : ByteBuffer {
public DataBuffer ()
: base (0)
{
}
public RVA AddData (byte [] data)
{
var rva = (RVA) position;
WriteBytes (data);
return rva;
}
}
abstract class HeapBuffer : ByteBuffer {
public bool IsLarge {
get { return base.length > 65536; }
}
public abstract bool IsEmpty { get; }
protected HeapBuffer (int length)
: base (length)
{
}
}
class StringHeapBuffer : HeapBuffer {
readonly Dictionary<string, uint> strings = new Dictionary<string, uint> ();
public sealed override bool IsEmpty {
get { return length <= 1; }
}
public StringHeapBuffer ()
: base (1)
{
WriteByte (0);
}
public uint GetStringIndex (string @string)
{
uint index;
if (strings.TryGetValue (@string, out index))
return index;
index = (uint) base.position;
WriteString (@string);
strings.Add (@string, index);
return index;
}
protected virtual void WriteString (string @string)
{
WriteBytes (Encoding.UTF8.GetBytes (@string));
WriteByte (0);
}
}
sealed class BlobHeapBuffer : HeapBuffer {
readonly Dictionary<ByteBuffer, uint> blobs = new Dictionary<ByteBuffer, uint> (new ByteBufferEqualityComparer ());
public override bool IsEmpty {
get { return length <= 1; }
}
public BlobHeapBuffer ()
: base (1)
{
WriteByte (0);
}
public uint GetBlobIndex (ByteBuffer blob)
{
uint index;
if (blobs.TryGetValue (blob, out index))
return index;
index = (uint) base.position;
WriteBlob (blob);
blobs.Add (blob, index);
return index;
}
void WriteBlob (ByteBuffer blob)
{
WriteCompressedUInt32 ((uint) blob.length);
WriteBytes (blob);
}
}
sealed class UserStringHeapBuffer : StringHeapBuffer {
protected override void WriteString (string @string)
{
WriteCompressedUInt32 ((uint) @string.Length * 2 + 1);
byte special = 0;
for (int i = 0; i < @string.Length; i++) {
var @char = @string [i];
WriteUInt16 (@char);
if (special == 1)
continue;
if (@char < 0x20 || @char > 0x7e) {
if (@char > 0x7e
|| (@char >= 0x01 && @char <= 0x08)
|| (@char >= 0x0e && @char <= 0x1f)
|| @char == 0x27
|| @char == 0x2d) {
special = 1;
}
}
}
WriteByte (special);
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Internal.TypeSystem
{
public static class TypeSystemHelpers
{
public static bool IsWellKnownType(this TypeDesc type, WellKnownType wellKnownType)
{
return type == type.Context.GetWellKnownType(wellKnownType, false);
}
public static InstantiatedType MakeInstantiatedType(this MetadataType typeDef, Instantiation instantiation)
{
return typeDef.Context.GetInstantiatedType(typeDef, instantiation);
}
public static InstantiatedType MakeInstantiatedType(this MetadataType typeDef, params TypeDesc[] genericParameters)
{
return typeDef.Context.GetInstantiatedType(typeDef, new Instantiation(genericParameters));
}
public static InstantiatedMethod MakeInstantiatedMethod(this MethodDesc methodDef, Instantiation instantiation)
{
return methodDef.Context.GetInstantiatedMethod(methodDef, instantiation);
}
public static InstantiatedMethod MakeInstantiatedMethod(this MethodDesc methodDef, params TypeDesc[] genericParameters)
{
return methodDef.Context.GetInstantiatedMethod(methodDef, new Instantiation(genericParameters));
}
public static ArrayType MakeArrayType(this TypeDesc type)
{
return type.Context.GetArrayType(type);
}
/// <summary>
/// Creates a multidimensional array type with the specified rank.
/// To create a vector, use the <see cref="MakeArrayType(TypeDesc)"/> overload.
/// </summary>
public static ArrayType MakeArrayType(this TypeDesc type, int rank)
{
return type.Context.GetArrayType(type, rank);
}
public static ByRefType MakeByRefType(this TypeDesc type)
{
return type.Context.GetByRefType(type);
}
public static PointerType MakePointerType(this TypeDesc type)
{
return type.Context.GetPointerType(type);
}
public static TypeDesc GetParameterType(this TypeDesc type)
{
ParameterizedType paramType = (ParameterizedType) type;
return paramType.ParameterType;
}
public static LayoutInt GetElementSize(this TypeDesc type)
{
if (type.IsValueType)
{
return ((DefType)type).InstanceFieldSize;
}
else
{
return type.Context.Target.LayoutPointerSize;
}
}
/// <summary>
/// Gets the parameterless instance constructor on the specified type. To get the default constructor, use <see cref="TypeDesc.GetDefaultConstructor"/>.
/// </summary>
public static MethodDesc GetParameterlessConstructor(this TypeDesc type)
{
// TODO: Do we want check for specialname/rtspecialname? Maybe add another overload on GetMethod?
var sig = new MethodSignature(0, 0, type.Context.GetWellKnownType(WellKnownType.Void), TypeDesc.EmptyTypes);
return type.GetMethod(".ctor", sig);
}
public static bool HasExplicitOrImplicitDefaultConstructor(this TypeDesc type)
{
return type.IsValueType || type.GetDefaultConstructor() != null;
}
internal static MethodDesc FindMethodOnExactTypeWithMatchingTypicalMethod(this TypeDesc type, MethodDesc method)
{
MethodDesc methodTypicalDefinition = method.GetTypicalMethodDefinition();
var instantiatedType = type as InstantiatedType;
if (instantiatedType != null)
{
Debug.Assert(instantiatedType.GetTypeDefinition() == methodTypicalDefinition.OwningType);
return method.Context.GetMethodForInstantiatedType(methodTypicalDefinition, instantiatedType);
}
else if (type.IsArray)
{
Debug.Assert(method.OwningType.IsArray);
return ((ArrayType)type).GetArrayMethod(((ArrayMethod)method).Kind);
}
else
{
Debug.Assert(type == methodTypicalDefinition.OwningType);
return methodTypicalDefinition;
}
}
/// <summary>
/// Returns method as defined on a non-generic base class or on a base
/// instantiation.
/// For example, If Foo<T> : Bar<T> and overrides method M,
/// if method is Bar<string>.M(), then this returns Bar<T>.M()
/// but if Foo : Bar<string>, then this returns Bar<string>.M()
/// </summary>
/// <param name="targetType">A potentially derived type</param>
/// <param name="method">A base class's virtual method</param>
public static MethodDesc FindMethodOnTypeWithMatchingTypicalMethod(this TypeDesc targetType, MethodDesc method)
{
// If method is nongeneric and on a nongeneric type, then it is the matching method
if (!method.HasInstantiation && !method.OwningType.HasInstantiation)
{
return method;
}
// Since method is an instantiation that may or may not be the same as typeExamine's hierarchy,
// find a matching base class on an open type and then work from the instantiation in typeExamine's
// hierarchy
TypeDesc typicalTypeOfTargetMethod = method.GetTypicalMethodDefinition().OwningType;
TypeDesc targetOrBase = targetType;
do
{
TypeDesc openTargetOrBase = targetOrBase;
if (openTargetOrBase is InstantiatedType)
{
openTargetOrBase = openTargetOrBase.GetTypeDefinition();
}
if (openTargetOrBase == typicalTypeOfTargetMethod)
{
// Found an open match. Now find an equivalent method on the original target typeOrBase
MethodDesc matchingMethod = targetOrBase.FindMethodOnExactTypeWithMatchingTypicalMethod(method);
return matchingMethod;
}
targetOrBase = targetOrBase.BaseType;
} while (targetOrBase != null);
Debug.Fail("method has no related type in the type hierarchy of type");
return null;
}
/// <summary>
/// Attempts to resolve constrained call to <paramref name="interfaceMethod"/> into a concrete non-unboxing
/// method on <paramref name="constrainedType"/>.
/// The ability to resolve constraint methods is affected by the degree of code sharing we are performing
/// for generic code.
/// </summary>
/// <returns>The resolved method or null if the constraint couldn't be resolved.</returns>
public static MethodDesc TryResolveConstraintMethodApprox(this TypeDesc constrainedType, TypeDesc interfaceType, MethodDesc interfaceMethod, out bool forceRuntimeLookup)
{
forceRuntimeLookup = false;
// We can't resolve constraint calls effectively for reference types, and there's
// not a lot of perf. benefit in doing it anyway.
if (!constrainedType.IsValueType)
{
return null;
}
// Non-virtual methods called through constraints simply resolve to the specified method without constraint resolution.
if (!interfaceMethod.IsVirtual)
{
return null;
}
MethodDesc method;
MethodDesc genInterfaceMethod = interfaceMethod.GetMethodDefinition();
if (genInterfaceMethod.OwningType.IsInterface)
{
// Sometimes (when compiling shared generic code)
// we don't have enough exact type information at JIT time
// even to decide whether we will be able to resolve to an unboxed entry point...
// To cope with this case we always go via the helper function if there's any
// chance of this happening by checking for all interfaces which might possibly
// be compatible with the call (verification will have ensured that
// at least one of them will be)
// Enumerate all potential interface instantiations
// TODO: this code assumes no shared generics
Debug.Assert(interfaceType == interfaceMethod.OwningType);
method = constrainedType.ResolveInterfaceMethodToVirtualMethodOnType(genInterfaceMethod);
}
else if (genInterfaceMethod.IsVirtual)
{
method = constrainedType.FindVirtualFunctionTargetMethodOnObjectType(genInterfaceMethod);
}
else
{
// The method will be null if calling a non-virtual instance
// methods on System.Object, i.e. when these are used as a constraint.
method = null;
}
if (method == null)
{
// Fall back to VSD
return null;
}
//#TryResolveConstraintMethodApprox_DoNotReturnParentMethod
// Only return a method if the value type itself declares the method,
// otherwise we might get a method from Object or System.ValueType
if (!method.OwningType.IsValueType)
{
// Fall back to VSD
return null;
}
// We've resolved the method, ignoring its generic method arguments
// If the method is a generic method then go and get the instantiated descriptor
if (interfaceMethod.HasInstantiation)
{
method = method.MakeInstantiatedMethod(interfaceMethod.Instantiation);
}
Debug.Assert(method != null);
//assert(!pMD->IsUnboxingStub());
return method;
}
/// <summary>
/// Retrieves the namespace qualified name of a <see cref="DefType"/>.
/// </summary>
public static string GetFullName(this DefType metadataType)
{
string ns = metadataType.Namespace;
return ns.Length > 0 ? String.Concat(ns, ".", metadataType.Name) : metadataType.Name;
}
/// <summary>
/// Retrieves all methods on a type, including the ones injected by the type system context.
/// </summary>
public static IEnumerable<MethodDesc> GetAllMethods(this TypeDesc type)
{
return type.Context.GetAllMethods(type);
}
public static IEnumerable<MethodDesc> EnumAllVirtualSlots(this TypeDesc type)
{
return type.Context.GetVirtualMethodAlgorithmForType(type).ComputeAllVirtualSlots(type);
}
/// <summary>
/// Resolves interface method '<paramref name="interfaceMethod"/>' to a method on '<paramref name="type"/>'
/// that implements the the method.
/// </summary>
public static MethodDesc ResolveInterfaceMethodToVirtualMethodOnType(this TypeDesc type, MethodDesc interfaceMethod)
{
return type.Context.GetVirtualMethodAlgorithmForType(type).ResolveInterfaceMethodToVirtualMethodOnType(interfaceMethod, type);
}
public static MethodDesc ResolveVariantInterfaceMethodToVirtualMethodOnType(this TypeDesc type, MethodDesc interfaceMethod)
{
return type.Context.GetVirtualMethodAlgorithmForType(type).ResolveVariantInterfaceMethodToVirtualMethodOnType(interfaceMethod, type);
}
/// <summary>
/// Resolves a virtual method call.
/// </summary>
public static MethodDesc FindVirtualFunctionTargetMethodOnObjectType(this TypeDesc type, MethodDesc targetMethod)
{
return type.Context.GetVirtualMethodAlgorithmForType(type).FindVirtualFunctionTargetMethodOnObjectType(targetMethod, type);
}
/// <summary>
/// Creates an open instantiation of a type. Given Foo<T>, returns Foo<!0>.
/// If the type is not generic, returns the <paramref name="type"/>.
/// </summary>
public static TypeDesc InstantiateAsOpen(this TypeDesc type)
{
if (!type.IsGenericDefinition)
{
Debug.Assert(!type.HasInstantiation);
return type;
}
TypeSystemContext context = type.Context;
var inst = new TypeDesc[type.Instantiation.Length];
for (int i = 0; i < inst.Length; i++)
{
inst[i] = context.GetSignatureVariable(i, false);
}
return context.GetInstantiatedType((MetadataType)type, new Instantiation(inst));
}
/// <summary>
/// Creates an open instantiation of a field. Given Foo<T>.Field, returns
/// Foo<!0>.Field. If the owning type is not generic, returns the <paramref name="field"/>.
/// </summary>
public static FieldDesc InstantiateAsOpen(this FieldDesc field)
{
Debug.Assert(field.GetTypicalFieldDefinition() == field);
TypeDesc owner = field.OwningType;
if (owner.HasInstantiation)
{
var instantiatedOwner = (InstantiatedType)owner.InstantiateAsOpen();
return field.Context.GetFieldForInstantiatedType(field, instantiatedOwner);
}
return field;
}
/// <summary>
/// Creates an open instantiation of a method. Given Foo<T>.Method, returns
/// Foo<!0>.Method. If the owning type is not generic, returns the <paramref name="method"/>.
/// </summary>
public static MethodDesc InstantiateAsOpen(this MethodDesc method)
{
Debug.Assert(method.IsMethodDefinition && !method.HasInstantiation);
TypeDesc owner = method.OwningType;
if (owner.HasInstantiation)
{
MetadataType instantiatedOwner = (MetadataType)owner.InstantiateAsOpen();
return method.Context.GetMethodForInstantiatedType(method, (InstantiatedType)instantiatedOwner);
}
return method;
}
/// <summary>
/// Scan the type and its base types for an implementation of an interface method. Returns null if no
/// implementation is found.
/// </summary>
public static MethodDesc ResolveInterfaceMethodTarget(this TypeDesc thisType, MethodDesc interfaceMethodToResolve)
{
Debug.Assert(interfaceMethodToResolve.OwningType.IsInterface);
MethodDesc result = null;
TypeDesc currentType = thisType;
do
{
result = currentType.ResolveInterfaceMethodToVirtualMethodOnType(interfaceMethodToResolve);
currentType = currentType.BaseType;
}
while (result == null && currentType != null);
return result;
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.IO;
using System.Collections; // for IDictionary;
using System.Compiler;
using System.Diagnostics.Contracts;
using System.Diagnostics;
using Microsoft.Win32;
namespace Microsoft.Contracts.Foxtrot.Driver
{
/// <summary>
/// Main program for Foxtrot.
/// </summary>
public sealed class Program
{
// Private fields
private static TypeNode userSpecifiedContractType;
private static ContractNodes DefaultContractLibrary;
private static ContractNodes BackupContractLibrary;
private static string originalAssemblyName = null;
private static FoxtrotOptions options;
private const int LeaderBoard_RewriterId = 0x1;
private const int LeaderBoardFeatureMask_Rewriter = LeaderBoard_RewriterId << 12;
[Flags]
private enum LeaderBoardFeatureId
{
StandardMode = 0x10,
ThrowOnFailure = 0x20,
}
private static int LeaderBoardFeature(FoxtrotOptions options)
{
Contract.Requires(options != null);
var result = options.level | LeaderBoardFeatureMask_Rewriter;
if (options.assemblyMode == FoxtrotOptions.AssemblyMode.standard)
{
result |= (int) LeaderBoardFeatureId.StandardMode;
}
if (options.throwOnFailure)
{
result |= (int) LeaderBoardFeatureId.ThrowOnFailure;
}
return result;
}
/// <summary>
/// Parses command line arguments and extracts, verifies, and/or rewrites a given assembly.
/// </summary>
/// <param name="args">Command line arguments, or <c>null</c> for help to be written to the console.</param>
public static int Main(string[] args)
{
var stopWatch = new Stopwatch();
stopWatch.Start();
try
{
var r = InternalMain(args);
return r;
}
finally
{
var delta = stopWatch.Elapsed;
Console.WriteLine("elapsed time: {0}ms", delta.TotalMilliseconds);
}
}
private static int InternalMain(string[] args)
{
options = new FoxtrotOptions();
options.Parse(args);
if (!options.nologo)
{
var version = typeof (FoxtrotOptions).Assembly.GetName().Version;
Console.WriteLine("Microsoft (R) .NET Contract Rewriter Version {0}", version);
Console.WriteLine("Copyright (C) Microsoft Corporation. All rights reserved.");
Console.WriteLine("");
}
if (options.HasErrors)
{
options.PrintErrorsAndExit(Console.Out);
return -1;
}
if (options.HelpRequested)
{
options.PrintOptions("", Console.Out);
return 0;
}
if (options.breakIntoDebugger)
{
Debugger.Launch();
}
#if DEBUG
if (options.nobox)
{
Debug.Listeners.Clear();
// listen for failed assertions
Debug.Listeners.Add(new ExitTraceListener());
}
#else
Debug.Listeners.Clear();
#endif
if (options.repro)
{
WriteReproFile(args);
}
var resolver = new AssemblyResolver(
options.resolvedPaths, options.libpaths, options.debug,
options.shortBranches, options.verbose > 2,
PostLoadExtractionHook);
GlobalAssemblyCache.probeGAC = options.useGAC;
// Connect to LeaderBoard
SendLeaderBoardRewriterFeature(options);
int errorReturnValue = -1;
IDictionary assemblyCache = new Hashtable();
// Trigger static initializer of SystemTypes
var savedGACFlag = GlobalAssemblyCache.probeGAC;
GlobalAssemblyCache.probeGAC = false;
TypeNode dummy = SystemTypes.Object;
TargetPlatform.Clear();
TargetPlatform.AssemblyReferenceFor = null;
GlobalAssemblyCache.probeGAC = savedGACFlag;
try
{
// Validate the command-line arguments.
if (options.output != "same")
{
if (!Path.IsPathRooted(options.output))
{
string s = Directory.GetCurrentDirectory();
options.output = Path.Combine(s, options.output);
}
}
if (options.assembly == null && options.GeneralArguments.Count == 1)
{
options.assembly = options.GeneralArguments[0];
}
if (!File.Exists(options.assembly))
{
throw new FileNotFoundException(String.Format("The given assembly '{0}' does not exist.", options.assembly));
}
InitializePlatform(resolver, assemblyCache);
if (options.passthrough)
{
options.rewrite = false;
}
if (!(options.rewrite || options.passthrough))
{
Console.WriteLine("Error: Need to specify at least one of: /rewrite, /pass");
options.PrintOptions("", Console.Out);
return errorReturnValue;
}
if (options.extractSourceText && !options.debug)
{
Console.WriteLine("Error: Cannot specify /sourceText without also specifying /debug");
options.PrintOptions("", Console.Out);
return errorReturnValue;
}
if (!(0 <= options.level && options.level <= 4))
{
Console.WriteLine("Error: incorrect /level: {0}. /level must be between 0 and 4 (inclusive)", options.level);
return errorReturnValue;
}
if (options.automaticallyLookForOOBs && options.contracts != null && 0 < options.contracts.Count)
{
Console.WriteLine("Error: Out of band contracts are being automatically applied, all files specified using the contracts option are ignored.");
return errorReturnValue;
}
// Sanity check: just make sure that all files specified for out-of-band contracts actually exist
bool atLeastOneOobNotFound = false;
if (options.contracts != null)
{
foreach (string oob in options.contracts)
{
bool found = false;
if (File.Exists(oob)) found = true;
if (!found)
{
if (options.libpaths != null)
{
foreach (string dir in options.libpaths)
{
if (File.Exists(Path.Combine(dir, oob)))
{
found = true;
break;
}
}
}
if (!found)
{
Console.WriteLine("Error: Contract file '" + oob + "' could not be found");
atLeastOneOobNotFound = true;
}
}
}
}
if (atLeastOneOobNotFound)
{
return errorReturnValue;
}
// Load the assembly to be rewritten
originalAssemblyName = Path.GetFileNameWithoutExtension(options.assembly);
AssemblyNode assemblyNode = AssemblyNode.GetAssembly(options.assembly,
TargetPlatform.StaticAssemblyCache, true, options.debug, true, options.shortBranches
, delegate(AssemblyNode a)
{
//Console.WriteLine("Loaded '" + a.Name + "' from '" + a.Location.ToString() + "'");
PossiblyLoadOOB(resolver, a, originalAssemblyName);
});
if (assemblyNode == null)
throw new FileLoadException("The given assembly could not be loaded.", options.assembly);
// Check to see if any metadata errors were reported
if (assemblyNode.MetadataImportWarnings != null && assemblyNode.MetadataImportWarnings.Count > 0)
{
string msg = "\tThere were warnings reported in " + assemblyNode.Name + "'s metadata.\n";
foreach (Exception e in assemblyNode.MetadataImportWarnings)
{
msg += "\t" + e.Message;
}
Console.WriteLine(msg);
}
if (assemblyNode.MetadataImportErrors != null && assemblyNode.MetadataImportErrors.Count > 0)
{
string msg = "\tThere were errors reported in " + assemblyNode.Name + "'s metadata.\n";
foreach (Exception e in assemblyNode.MetadataImportErrors)
{
msg += "\t" + e.Message;
}
Console.WriteLine(msg);
throw new InvalidOperationException("Foxtrot: " + msg);
}
else
{
//Console.WriteLine("\tThere were no errors reported in {0}'s metadata.", assemblyNode.Name);
}
// Load the rewriter assembly if any
AssemblyNode rewriterMethodAssembly = null;
if (options.rewriterMethods != null && 0 < options.rewriterMethods.Length)
{
string[] pieces = options.rewriterMethods.Split(',');
if (!(pieces.Length == 2 || pieces.Length == 3))
{
Console.WriteLine("Error: Need to provide two or three comma separated arguments to /rewriterMethods");
options.PrintOptions("", Console.Out);
return errorReturnValue;
}
string assemName = pieces[0];
rewriterMethodAssembly = resolver.ProbeForAssembly(assemName, null, resolver.AllExt);
if (rewriterMethodAssembly == null)
{
Console.WriteLine("Error: Could not open assembly '" + assemName + "'");
return errorReturnValue;
}
string nameSpaceName = null;
string bareClassName = null;
if (pieces.Length == 2)
{
// interpret A.B.C as namespace A.B and class C
// no nested classes allowed.
string namespaceAndClassName = pieces[1];
int lastDot = namespaceAndClassName.LastIndexOf('.');
nameSpaceName = lastDot == -1 ? "" : namespaceAndClassName.Substring(0, lastDot);
bareClassName = namespaceAndClassName.Substring(lastDot + 1);
userSpecifiedContractType = rewriterMethodAssembly.GetType(Identifier.For(nameSpaceName),
Identifier.For(bareClassName));
}
else
{
// pieces.Length == 3
// namespace can be A.B and class can be C.D
nameSpaceName = pieces[1];
bareClassName = pieces[2];
userSpecifiedContractType = GetPossiblyNestedType(rewriterMethodAssembly, nameSpaceName, bareClassName);
}
if (userSpecifiedContractType == null)
{
Console.WriteLine("Error: Could not find type '" + bareClassName + "' in the namespace '" +
nameSpaceName + "' in the assembly '" + assemName + "'");
return errorReturnValue;
}
}
// Load the ASTs for all of the contract methods
AssemblyNode contractAssembly = null;
if (!options.passthrough)
{
// The contract assembly should be determined in the following order:
// 0. if the option contractLibrary was specified, use that.
// 1. the assembly being rewritten
// 2. the system assembly
// 3. the microsoft.contracts library
if (options.contractLibrary != null)
{
contractAssembly = resolver.ProbeForAssembly(options.contractLibrary,
Path.GetDirectoryName(options.assembly), resolver.EmptyAndDllExt);
if (contractAssembly != null)
DefaultContractLibrary = ContractNodes.GetContractNodes(contractAssembly, options.EmitError);
if (contractAssembly == null || DefaultContractLibrary == null)
{
Console.WriteLine("Error: could not load Contracts API from assembly '{0}'", options.contractLibrary);
return -1;
}
}
else
{
if (DefaultContractLibrary == null)
{
// See if contracts are in the assembly we're rewriting
DefaultContractLibrary = ContractNodes.GetContractNodes(assemblyNode, options.EmitError);
}
if (DefaultContractLibrary == null)
{
// See if contracts are in Mscorlib
DefaultContractLibrary = ContractNodes.GetContractNodes(SystemTypes.SystemAssembly,
options.EmitError);
}
// try to load Microsoft.Contracts.dll
var microsoftContractsLibrary = resolver.ProbeForAssembly("Microsoft.Contracts",
Path.GetDirectoryName(options.assembly), resolver.DllExt);
if (microsoftContractsLibrary != null)
{
BackupContractLibrary = ContractNodes.GetContractNodes(microsoftContractsLibrary, options.EmitError);
}
if (DefaultContractLibrary == null && BackupContractLibrary != null)
{
DefaultContractLibrary = BackupContractLibrary;
}
}
}
if (DefaultContractLibrary == null)
{
if (options.output == "same")
{
Console.WriteLine(
"Warning: Runtime Contract Checking requested, but contract class could not be found. Did you forget to reference the contracts assembly?");
return 0; // Returning success so that it doesn't break any build processes.
}
else
{
// Then an output file was specified (assume it is not the same as the input assembly, but that could be checked here).
// In that case, consider it an error to not have found a contract class.
// No prinicpled reason, but this is a common pitfall that several users have run into and the rewriter just
// didn't do anything without giving any reason.
Console.WriteLine(
"Error: Runtime Contract Checking requested, but contract class could not be found. Did you forget to reference the contracts assembly?");
return errorReturnValue;
}
}
if (0 < options.verbose)
{
Console.WriteLine("Trace: Using '" + DefaultContractLibrary.ContractClass.DeclaringModule.Location +
"' for the definition of the contract class");
}
// Make sure we extract contracts from the system assembly and the system.dll assemblies.
// As they are already loaded, they will never trigger the post assembly load event.
// But even if we are rewriting one of these assemblies (and so *not* trying to extract
// the contracts at this point), still need to hook up our resolver to them. If this
// isn't done, then any references chased down from them might not get resolved.
bool isPreloadedAssembly = false;
CheckIfPreloaded(resolver, assemblyNode, SystemTypes.SystemAssembly, ref isPreloadedAssembly);
CheckIfPreloaded(resolver, assemblyNode, SystemTypes.SystemDllAssembly, ref isPreloadedAssembly);
//CheckIfPreloaded(resolver, assemblyNode, SystemTypes.SystemRuntimeWindowsRuntimeAssembly, ref isPreloadedAssembly);
//CheckIfPreloaded(resolver, assemblyNode, SystemTypes.SystemRuntimeWindowsRuntimeUIXamlAssembly, ref isPreloadedAssembly);
if (!isPreloadedAssembly)
{
assemblyNode.AssemblyReferenceResolution += resolver.ResolveAssemblyReference;
}
MikesArchitecture(resolver, assemblyNode, DefaultContractLibrary, BackupContractLibrary);
return options.GetErrorCount();
}
catch (Exception exception)
{
SendLeaderBoardFailure();
// Redirect the exception message to the console and quit.
Console.Error.WriteLine(new System.CodeDom.Compiler.CompilerError(exception.Source, 0, 0, null, exception.Message));
return errorReturnValue;
}
finally
{
// Reset statics
userSpecifiedContractType = null;
DefaultContractLibrary = null;
BackupContractLibrary = null;
originalAssemblyName = null;
options = null;
// eagerly close all assemblies due to pdb file locking issues
DisposeAssemblies(assemblyCache.Values);
// copy needed since Dispose actually removes things from the StaticAssemblyCache
object[] assemblies = new object[TargetPlatform.StaticAssemblyCache.Values.Count];
TargetPlatform.StaticAssemblyCache.Values.CopyTo(assemblies, 0);
DisposeAssemblies(assemblies);
}
}
private static void CheckIfPreloaded(AssemblyResolver resolver, AssemblyNode assemblyNode,
AssemblyNode preloaded, ref bool isPreloadedAssembly)
{
Contract.Requires(preloaded == null || resolver != null);
if (preloaded == null) return;
resolver.PostLoadHook(preloaded);
if (assemblyNode == preloaded)
{
isPreloadedAssembly = true;
}
}
private static void InitializePlatform(AssemblyResolver resolver, System.Collections.IDictionary assemblyCache)
{
// Initialize CCI's platform if necessary
if (options.targetplatform != null && options.targetplatform != "")
{
string platformDir = Path.GetDirectoryName(options.targetplatform);
if (platformDir == "")
{
platformDir = ".";
}
if (!Directory.Exists(platformDir))
throw new ArgumentException("Directory '" + platformDir + "' doesn't exist.");
if (!File.Exists(options.targetplatform))
throw new ArgumentException("Cannot find the file '" + options.targetplatform +
"' to use as the system assembly.");
TargetPlatform.GetDebugInfo = options.debug;
switch (options.framework)
{
case "v4.5":
TargetPlatform.SetToV4_5(platformDir);
break;
case "v4.0":
TargetPlatform.SetToV4(platformDir);
break;
case "v3.5":
case "v3.0":
case "v2.0":
TargetPlatform.SetToV2(platformDir);
break;
default:
if (platformDir.Contains("v4.0"))
{
TargetPlatform.SetToV4(platformDir);
}
else if (platformDir.Contains("v4.5"))
{
TargetPlatform.SetToV4_5(platformDir);
}
else if (platformDir.Contains("v3.5"))
{
TargetPlatform.SetToV2(platformDir);
}
else
{
TargetPlatform.SetToPostV2(platformDir);
}
break;
}
SystemAssemblyLocation.Location = options.targetplatform;
// When rewriting the framework assemblies, it might not be the case that the input assembly (e.g., System.dll)
// is in the same directory as the target platform that the rewriter has been asked to run on.
SystemRuntimeWindowsRuntimeAssemblyLocation.Location =
SetPlatformAssemblyLocation("System.Runtime.WindowsRuntime.dll");
SystemRuntimeWindowsRuntimeUIXamlAssemblyLocation.Location =
SetPlatformAssemblyLocation("System.Runtime.WindowsRuntime.UI.Xaml.dll");
SystemDllAssemblyLocation.Location = SetPlatformAssemblyLocation("System.dll");
SystemAssemblyLocation.SystemAssemblyCache = assemblyCache;
}
else
{
if (options.resolvedPaths != null)
{
foreach (var path in options.resolvedPaths)
{
if (path == null) continue;
if (string.IsNullOrEmpty(path.Trim())) continue;
var candidate = Path.GetFullPath(path);
if (candidate.EndsWith(@"\mscorlib.dll", StringComparison.OrdinalIgnoreCase) &&
File.Exists(candidate))
{
// found our platform
var dir = Path.Combine(Path.GetPathRoot(candidate), Path.GetDirectoryName(candidate));
SelectPlatform(assemblyCache, dir, candidate);
goto doneWithLibPaths;
}
}
}
if (options.libpaths != null)
{
// try to infer platform from libpaths
foreach (var path in options.libpaths)
{
if (path == "") continue;
var corlib = Path.Combine(path, "mscorlib.dll");
if (File.Exists(corlib))
{
// this should be our platform mscorlib.dll
SelectPlatform(assemblyCache, path, corlib);
goto doneWithLibPaths;
}
}
}
}
doneWithLibPaths:
;
if (string.IsNullOrEmpty(options.targetplatform))
{
SystemTypes.Initialize(false, true);
// try to use mscorlib of assembly to rewrite
AssemblyNode target = AssemblyNode.GetAssembly(options.assembly, TargetPlatform.StaticAssemblyCache,
true, false, true);
if (target != null)
{
var majorTargetVersion = target.MetadataFormatMajorVersion;
var corlib = SystemTypes.SystemAssembly.Location;
var path = Path.GetDirectoryName(corlib);
if (SystemTypes.SystemAssembly.Version.Major != majorTargetVersion)
{
var versionDir = String.Format(@"..\{0}", target.TargetRuntimeVersion);
path = Path.Combine(path, versionDir);
corlib = Path.Combine(path, "mscorlib.dll");
if (!File.Exists(corlib))
{
throw new ArgumentException(
"Cannot determine target runtime version. Please specify /resolvedPaths, /libpaths or /targetplatform");
}
}
if (majorTargetVersion == 2)
{
TargetPlatform.SetToV2(path);
}
else
{
TargetPlatform.SetToV4(path);
}
SystemAssemblyLocation.Location = corlib;
Contract.Assume(path != null);
SystemDllAssemblyLocation.Location = Path.Combine(path, "System.dll");
SystemRuntimeWindowsRuntimeAssemblyLocation.Location = Path.Combine(path,
"System.Runtime.WindowsRuntime.dll");
SystemRuntimeWindowsRuntimeUIXamlAssemblyLocation.Location = Path.Combine(path,
"System.Runtime.WindowsRuntime.UI.Xaml.dll");
SystemAssemblyLocation.SystemAssemblyCache = assemblyCache;
options.targetplatform = corlib;
}
}
// always make sure we have the platform assemblies loaded
if (TargetPlatform.PlatformAssembliesLocation == null)
{
throw new ArgumentException("Could not find the platform assemblies.");
}
if (!string.IsNullOrEmpty(options.targetplatform))
{
TargetPlatform.AssemblyReferenceFor = null;
assemblyCache.Clear();
SystemTypes.Initialize(false, true, resolver.PostLoadHook);
}
// Force SystemTypes.Initialize() to be run before attaching any out-of-band contracts
// Otherwise, if there is an out-of-band contract for mscorlib, then types in SystemTypes
// get loaded twice.
AssemblyNode corlibAssembly = SystemTypes.SystemAssembly;
// Add the system assembly to the cache so if we rewrite it itself we won't load it twice
TargetPlatform.UseGenerics = true;
TargetPlatform.StaticAssemblyCache.Add(corlibAssembly.Name, corlibAssembly);
}
private static string SetPlatformAssemblyLocation(string platformAssemblyName)
{
Contract.Requires(platformAssemblyName != null);
var result = Path.Combine(Path.GetDirectoryName(options.targetplatform), platformAssemblyName);
;
var assemblyFileName = Path.GetFileName(options.assembly);
if (assemblyFileName.Equals(platformAssemblyName, StringComparison.OrdinalIgnoreCase) &&
File.Exists(options.assembly))
{
result = options.assembly;
}
return result;
}
private static void SelectPlatform(IDictionary assemblyCache, string path, string corlib)
{
Contract.Requires(corlib != null);
Contract.Requires(path != null);
Debug.Assert(corlib.StartsWith(path));
SystemTypes.Clear();
TargetPlatform.GetDebugInfo = options.debug;
TargetPlatform.Clear();
if (path.Contains("v4.0") || path.Contains("v4.5"))
{
TargetPlatform.SetToV4(path);
}
else
{
TargetPlatform.SetToV2(path);
}
SystemAssemblyLocation.Location = corlib;
SystemRuntimeWindowsRuntimeAssemblyLocation.Location = Path.Combine(path,
"System.Runtime.WindowsRuntime.dll");
SystemRuntimeWindowsRuntimeUIXamlAssemblyLocation.Location = Path.Combine(path,
"System.Runtime.WindowsRuntime.UI.Xaml.dll");
SystemDllAssemblyLocation.Location = Path.Combine(path, "System.dll");
SystemAssemblyLocation.SystemAssemblyCache = assemblyCache;
options.targetplatform = corlib;
}
private static void SendLeaderBoardFailure()
{
#if LeaderBoard
var version = typeof(FoxtrotOptions).Assembly.GetName().Version;
LeaderBoard.LeaderBoardAPI.SendLeaderBoardFailure(LeaderBoard_RewriterId, version);
#endif
}
private static void SendLeaderBoardRewriterFeature(FoxtrotOptions options)
{
#if LeaderBoard
LeaderBoard.LeaderBoardAPI.SendLeaderBoardFeatureUse(LeaderBoardFeature(options));
#endif
}
private static void WriteReproFile(string[] args)
{
try
{
var file = new StreamWriter("repro.bat");
#if false
file.Write(@"c:\users\maf\cci1\foxtrot\driver\bin\debug\foxtrot.exe ");
foreach (var arg in args)
{
file.Write("\"{0}\" ", arg);
}
#else
file.Write(Environment.CommandLine.Replace("-repro", ""));
#endif
file.WriteLine(" %1 %2 %3 %4 %5");
file.Close();
}
catch
{
}
}
private static TypeNode GetPossiblyNestedType(AssemblyNode assem, string namespaceName, string className)
{
Contract.Requires(assem != null);
Contract.Requires(className != null);
var ns = Identifier.For(namespaceName);
string[] pieces = className.Split('.');
// Get outermost type
string outerMost = pieces[0];
TypeNode t = assem.GetType(ns, Identifier.For(outerMost));
if (t == null) return null;
for (int i = 1; i < pieces.Length; i++)
{
var piece = pieces[i];
t = t.GetNestedType(Identifier.For(piece));
if (t == null) return null;
}
return t;
}
private static void DisposeAssemblies(IEnumerable assemblies)
{
try
{
Contract.Assume(assemblies != null);
foreach (Module assembly in assemblies)
{
if (assembly != null)
{
assembly.Dispose();
}
}
}
catch
{
}
}
#if false
/// <summary>
/// Resolves assembly references based on the library paths specified.
/// Tries to resolve to ".dll" or ".exe". First found wins.
/// </summary>
/// <param name="assemblyReference">Reference to resolve.</param>
/// <param name="referencingModule">Referencing module.</param>
/// <returns>The resolved assembly node (null if not found).</returns>
private static AssemblyNode AssemblyReferenceResolution (AssemblyReference assemblyReference, Module referencingModule) {
AssemblyNode a = ProbeForAssembly(assemblyReference.Name, referencingModule.Directory, DllAndExeExt);
return a;
}
private static AssemblyNode ProbeForAssemblyWithExtension(string directory, string assemblyName, string[] exts)
{
do
{
var result = ProbeForAssemblyWithExtensionAtomic(directory, assemblyName, exts);
if (result != null) return result;
if (directory.EndsWith("CodeContracts")) return null;
// if directory is a profile directory, we need to look in parent directory too
if (directory.Contains("Profile") || directory.Contains("profile"))
{
try
{
var parent = Directory.GetParent(directory);
directory = parent.FullName;
}
catch
{
break;
}
}
else
{
break;
}
}
while (!String.IsNullOrWhiteSpace(directory));
return null;
}
private static AssemblyNode ProbeForAssemblyWithExtensionAtomic(string directory, string assemblyName, string[] exts)
{
foreach (string ext in exts)
{
bool tempDebugInfo = options.debug;
string fullName = Path.Combine(directory, assemblyName + ext);
LoadTracing("Attempting load from:");
LoadTracing(fullName);
if (File.Exists(fullName))
{
if (tempDebugInfo)
{
// Don't pass the debugInfo flag to GetAssembly unless the PDB file exists.
string pdbFullName;
if (ext == "")
{
pdbFullName = Path.Combine(directory, Path.GetFileNameWithoutExtension(assemblyName) + ".pdb");
}
else
{
pdbFullName = Path.Combine(directory, assemblyName + ".pdb");
}
if (!File.Exists(pdbFullName))
{
Trace.WriteLine(String.Format("Can not find PDB file. Debug info will not be available for assembly '{0}'.", assemblyName));
tempDebugInfo = false;
}
}
Trace.WriteLine(string.Format("Resolved assembly reference '{0}' to '{1}'. (Using directory {2})", assemblyName, fullName, directory));
var result = AssemblyNode.GetAssembly(
fullName, // path to assembly
TargetPlatform.StaticAssemblyCache, // global cache to use for assemblies
true, // doNotLockFile
tempDebugInfo, // getDebugInfo
true, // useGlobalCache
options.shortBranches, // preserveShortBranches
PostLoadExtractionHook
);
return result;
}
}
return null;
}
private static void LoadTracing(string msg)
{
if (options.verbose > 2)
{
Console.WriteLine("Trace: {0}", msg);
}
Trace.WriteLine(msg);
}
static string[] EmptyExt = new[] { "" };
static string[] DllExt = new[] { ".dll", ".winmd" };
static string[] DllAndExeExt = new[] { ".dll", ".winmd", ".exe" };
static string[] EmptyAndDllExt = new[] { "", ".dll", ".winmd" };
static string[] AllExt = new[] { "", ".dll", ".winmd", ".exe" };
private static AssemblyNode ProbeForAssembly (string assemblyName, string referencingModuleDirectory, string[] exts) {
AssemblyNode a = null;
try {
LoadTracing("Attempting to load");
LoadTracing(assemblyName);
// Location Priority (in decreasing order):
// 0. list of candidate full paths specified by client
// 1. list of directories specified by client
// 2. referencing Module's directory
// 3. directory original assembly was in
//
// Extension Priority (in decreasing order):
// dll, exe, (any others?)
// Check user-supplied candidate paths
LoadTracing("AssemblyResolver: Attempting user-supplied candidates.");
if (options.resolvedPaths != null)
{
foreach (string candidate in options.resolvedPaths)
{
var candidateAssemblyName = Path.GetFileNameWithoutExtension(candidate);
if (String.Compare(candidateAssemblyName, assemblyName, StringComparison.OrdinalIgnoreCase) != 0) continue;
if (File.Exists(candidate))
{
a = ProbeForAssemblyWithExtension("", candidate, EmptyExt);
break;
}
}
}
else
{
Trace.WriteLine("\tAssemblyResolver: No user-supplied resolvedPaths.");
}
if (a == null)
{
if (options.resolvedPaths != null)
{
Trace.WriteLine("\tAssemblyResolver: Did not find assembly in user-supplied resolvedPaths candidates.");
}
}
else
{
goto End;
}
// Check user-supplied search directories
LoadTracing("AssemblyResolver: Attempting user-supplied directories.");
if (options.libpaths != null)
{
foreach (string dir in options.libpaths)
{
a = ProbeForAssemblyWithExtension(dir, assemblyName, exts);
if (a != null)
break;
}
}
else
{
Trace.WriteLine("\tAssemblyResolver: No user-supplied directories.");
}
if (a == null)
{
if (options.libpaths != null)
{
Trace.WriteLine("\tAssemblyResolver: Did not find assembly in user-supplied directories.");
}
}
else
{
goto End;
}
// Check referencing module's directory
Trace.WriteLine("\tAssemblyResolver: Attempting referencing assembly's directory.");
if (referencingModuleDirectory != null) {
a = ProbeForAssemblyWithExtension(referencingModuleDirectory, assemblyName, exts);
}
else
{
Trace.WriteLine("\t\tAssemblyResolver: Referencing assembly's directory is null.");
}
if (a == null) {
if (referencingModuleDirectory != null) {
Trace.WriteLine("\tAssemblyResolver: Did not find assembly in referencing assembly's directory.");
}
} else {
goto End;
}
// Check input directory
Trace.WriteLine("\tAssemblyResolver: Attempting input directory.");
a = ProbeForAssemblyWithExtension("", assemblyName, exts);
if (a == null) {
Trace.WriteLine("\tAssemblyResolver: Did not find assembly in input directory.");
} else {
goto End;
}
End:
if (a == null)
{
Trace.WriteLine("AssemblyResolver: Unable to resolve reference. (It still might be found, e.g., in the GAC.)");
}
} catch (Exception e) {
Trace.WriteLine("AssemblyResolver: Exception occurred. Unable to resolve reference.");
Trace.WriteLine("Inner exception: " + e.ToString());
}
return a;
}
#endif
/// <summary>
/// Moves external resource files referenced in an assembly node to the specified path.
/// </summary>
/// <param name="assemblyNode">Assembly node containing the resource references.</param>
/// <param name="path">Directory to move the external files to.</param>
private static void MoveModuleResources(AssemblyNode assemblyNode, string directory)
{
Contract.Requires(assemblyNode != null);
for (int i = 0, n = assemblyNode.Resources == null ? 0 : assemblyNode.Resources.Count; i < n; i++)
{
Resource r = assemblyNode.Resources[i];
if (r.Data != null) continue; // not an external resource
if (r.DefiningModule == null) continue; // error? should have a defining module that represents the file
string newPath = Path.Combine(directory, r.Name);
if (!directory.Equals(r.DefiningModule.Directory, StringComparison.OrdinalIgnoreCase))
{
if (File.Exists(newPath))
{
Console.WriteLine("The file '" + newPath +
"' already exists, so is not being copied. Make sure this is okay!");
}
else
{
File.Copy(r.DefiningModule.Location, newPath);
}
}
r.DefiningModule.Location = newPath;
}
}
#if KAEL
private static void KaelsArchitecture(AssemblyNode assemblyNode) {
// Finish decompiling expressions where CCI left off.
new Abnormalizer().Visit(assemblyNode);
// Check and extract all inline foxtrot contracts and place them in the object model.
Checker checker = new Checker(new ContractNodes(assemblyNode));
bool errorFound = false;
checker.ErrorFound += delegate(System.CodeDom.Compiler.CompilerError error) {
if (!error.IsWarning || warningLevel > 0) {
Console.WriteLine(error.ToString());
}
errorFound |= !error.IsWarning;
};
checker.Visit(assemblyNode);
if (errorFound)
return;
if (verify) {
throw new NotImplementedException("Static verification is not yet implemented.");
}
// Write out the assembly, possibly injecting the runtime checks
if (rewrite || passthrough) {
// Reload the assembly to flush out the abnormalized contracts since the rewriter can't handle them yet.
assemblyNode = LoadAssembly();
if (!passthrough) {
// Rewrite the assembly in memory.
Rewriter rewriter = new Rewriter(new ContractNodes(assemblyNode));
rewriter.InlinePreconditions = false;
rewriter.InlinePostconditions = false;
rewriter.InlineInvariant = false;
rewriter.Verbose = verbose;
rewriter.Decompile = decompile;
rewriter.Visit(assemblyNode);
}
if (output == "same") {
// Save the rewritten assembly to a temporary location.
output = Path.Combine(Path.GetTempPath(), Path.GetFileName(assembly));
// Re-attach external file resources to the new output assembly.
MoveModuleResources(assemblyNode, output);
// Save the rewritten assembly.
assemblyNode.WriteModule(output, debug);
// Make a copy of the original assembly and PDB.
File.Delete(assembly + ".original");
File.Delete(Path.ChangeExtension(assembly, ".pdb") + ".original");
File.Move(assembly, assembly + ".original");
File.Move(Path.ChangeExtension(assembly, ".pdb"), Path.ChangeExtension(assembly, ".pdb") + ".original");
// Move the rewritten assembly and PDB to the original location.
File.Move(output, assembly);
File.Move(Path.ChangeExtension(output, ".pdb"), Path.ChangeExtension(assembly, ".pdb"));
} else {
// Re-attach external file resources to the new output assembly.
MoveModuleResources(assemblyNode, output);
// Save the rewritten assembly.
assemblyNode.WriteModule(output, debug);
}
}
}
#endif
private static void LogFileLoads(AssemblyNode assemblyNode)
{
if (options.verbose > 0 && assemblyNode != null)
{
Console.WriteLine("Trace: Assembly '{0}' loaded from '{1}'", assemblyNode.Name, assemblyNode.Location);
}
}
private static void PossiblyLoadOOB(AssemblyResolver resolver, AssemblyNode assemblyNode, string originalAssemblyName)
{
Contract.Requires(assemblyNode != null);
Contract.Requires(originalAssemblyName != null);
// Do NOT automatically attach an out-of-band contract to the main assembly being worked on,
// but only for the assemblies it references.
// That is because there might be a contract assembly X.Contracts for an assembly X that contains
// contracts and we don't want to be confused or get duplicate contracts if that contract assembly
// is found the next time X is rewritten.
// So attach the contract only if it is explicitly listed in the options
if (assemblyNode.Name.ToLower() == originalAssemblyName.ToLower())
{
assemblyNode.AssemblyReferenceResolution +=
new Module.AssemblyReferenceResolver(resolver.ResolveAssemblyReference);
LogFileLoads(assemblyNode);
return;
}
resolver.PostLoadHook(assemblyNode);
}
private static void PostLoadExtractionHook(AssemblyResolver resolver, AssemblyNode assemblyNode)
{
Contract.Requires(assemblyNode != null);
LogFileLoads(assemblyNode);
// If ends in ".Contracts", no need to do anything. Just return
if (assemblyNode.Name.EndsWith(".Contracts")) return;
// Possibly load OOB contract assembly for assemblyNode. If found, run extractor on the pair.
if (options.automaticallyLookForOOBs)
{
string contractFileName = Path.GetFileNameWithoutExtension(assemblyNode.Location) + ".Contracts";
// if (contractFileName != null)
{
AssemblyNode contractAssembly = resolver.ProbeForAssembly(contractFileName, assemblyNode.Directory, resolver.DllExt);
if (contractAssembly != null)
{
ContractNodes usedContractNodes;
Extractor.ExtractContracts(assemblyNode, contractAssembly, DefaultContractLibrary,
BackupContractLibrary, DefaultContractLibrary, out usedContractNodes, null, false);
}
}
}
else
{
// use only if specified
if (options.contracts != null)
{
foreach (var contractAssemblyName in options.contracts)
{
string contractFileName = Path.GetFileNameWithoutExtension(contractAssemblyName);
var assemblyName = assemblyNode.Name + ".Contracts";
if (contractFileName == assemblyName)
{
AssemblyNode contractAssembly = resolver.ProbeForAssembly(assemblyName, assemblyNode.Directory, resolver.DllExt);
if (contractAssembly != null)
{
ContractNodes usedContractNodes;
Extractor.ExtractContracts(assemblyNode, contractAssembly, DefaultContractLibrary,
BackupContractLibrary, DefaultContractLibrary, out usedContractNodes, null, false);
}
break; // only do the one
}
}
}
}
}
private static int PEVerify(string assemblyFile)
{
var path = Path.GetDirectoryName(assemblyFile);
var file = Path.GetFileName(assemblyFile);
if (file == "mscorlib.dll") return -1; // peverify returns 0 for mscorlib without verifying.
var oldCWD = Environment.CurrentDirectory;
if (string.IsNullOrEmpty(path)) path = oldCWD;
try
{
Environment.CurrentDirectory = path;
object winsdkfolder =
Registry.GetValue(
@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v7.0A\WinSDK-NetFx40Tools",
"InstallationFolder", null);
if (winsdkfolder == null)
{
winsdkfolder = Registry.GetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Microsoft SDKs\Windows",
"CurrentInstallFolder", null);
}
string peVerifyPath = null;
if (winsdkfolder != null)
{
peVerifyPath = (string) winsdkfolder + @"\peverify.exe";
if (!File.Exists(peVerifyPath))
{
peVerifyPath = (string) winsdkfolder + @"\bin\peverify.exe";
}
if (!File.Exists(peVerifyPath))
{
peVerifyPath = null;
}
}
if (peVerifyPath == null)
{
peVerifyPath =
Environment.ExpandEnvironmentVariables(
@"%ProgramFiles%\Microsoft Visual Studio 8\Common7\IDE\PEVerify.exe");
}
if (String.IsNullOrEmpty(peVerifyPath) || !File.Exists(peVerifyPath))
{
return -2;
}
ProcessStartInfo i = new ProcessStartInfo(peVerifyPath, "/unique \"" + file + "\"");
i.RedirectStandardOutput = true;
i.UseShellExecute = false;
i.ErrorDialog = false;
i.CreateNoWindow = true;
using (Process p = Process.Start(i))
{
if (!(p.WaitForExit(10000))) return -1;
#if false
if (p.ExitCode != 0)
{
var s = p.StandardOutput.ReadToEnd();
Console.WriteLine("{0}", s);
}
#endif
return p.ExitCode;
}
}
catch
{
return -1;
}
finally
{
Environment.CurrentDirectory = oldCWD;
}
}
private static void MikesArchitecture(AssemblyResolver resolver, AssemblyNode assemblyNode,
ContractNodes contractNodes, ContractNodes backupContracts)
{
#if false
var originalsourceDir = Path.GetDirectoryName(assemblyNode.Location);
int oldPeVerifyCode = options.verify ? PEVerify(assemblyNode.Location, originalsourceDir) : -1;
#endif
// Check to see if the assembly has already been rewritten
if (!options.passthrough)
{
if (ContractNodes.IsAlreadyRewritten(assemblyNode))
{
if (!options.allowRewritten)
{
Console.WriteLine("Assembly '" + assemblyNode.Name +
"' has already been rewritten. I, your poor humble servant, cannot rewrite it. Instead I must give up without rewriting it. Help!");
}
return;
}
}
// Extract the contracts from the code (includes checking the contracts)
string contractFileName = Path.GetFileNameWithoutExtension(assemblyNode.Location) + ".Contracts";
if (options.contracts == null || options.contracts.Count <= 0) contractFileName = null;
if (options.contracts != null &&
!options.contracts.Exists(name => name.Equals(assemblyNode.Name + ".Contracts.dll", StringComparison.OrdinalIgnoreCase)))
{
contractFileName = null;
}
AssemblyNode contractAssembly = null;
if (contractFileName != null)
{
contractAssembly = resolver.ProbeForAssembly(contractFileName, assemblyNode.Directory,
resolver.DllExt);
}
if (!options.passthrough)
{
ContractNodes usedContractNodes;
Extractor.ExtractContracts(assemblyNode, contractAssembly, contractNodes, backupContracts, contractNodes,
out usedContractNodes, options.EmitError, false);
// important to extract source before we perform any more traversals due to contract instantiation. Otherwise,
// we might get copies of contracts due to instantiation that have no source text yet.
// Extract the text from the sources (optional)
if (usedContractNodes != null && options.extractSourceText)
{
GenerateDocumentationFromPDB gd = new GenerateDocumentationFromPDB(contractNodes);
gd.VisitForDoc(assemblyNode);
}
// After all contracts have been extracted in assembly, do some post-extractor checks
// we run these even if no contracts were extracted due to checks having to do with overrides
var contractNodesForChecks = usedContractNodes != null ? usedContractNodes : contractNodes;
if (contractNodesForChecks != null)
{
PostExtractorChecker pec = new PostExtractorChecker(contractNodesForChecks, options.EmitError, false,
options.fSharp, options.IsLegacyModeAssembly, options.addInterfaceWrappersWhenNeeded,
options.level);
if (contractAssembly != null)
{
pec.VisitForPostCheck(contractAssembly);
}
else
{
pec.VisitForPostCheck(assemblyNode);
}
}
// don't really need to test, since if they are the same, the assignment doesn't change that
// but this is to emphasize that the nodes used in the AST by the extractor are different
// than what we thought we were using.
if (options.GetErrorCount() > 0)
{
// we are done.
// But first, report any metadata errors so they are not masked by the errors
CheckForMetaDataErrors(assemblyNode);
return;
}
}
// If we have metadata errors, cop out
{
#if false
for (int i = 0; i < assemblyNode.ModuleReferences.Count; i++)
{
Module m = assemblyNode.ModuleReferences[i].Module;
Console.WriteLine("Location for referenced module '{0}' is '{1}'", m.Name, m.Location);
}
#endif
if (CheckForMetaDataErrors(assemblyNode))
{
throw new Exception("Rewrite aborted due to metadata errors. Check output window");
}
for (int i = 0; i < assemblyNode.AssemblyReferences.Count; i++)
{
AssemblyNode aref = assemblyNode.AssemblyReferences[i].Assembly;
if (CheckForMetaDataErrors(aref))
{
throw new Exception("Rewrite aborted due to metadata errors. Check output window");
}
}
}
// Inject the contracts into the code (optional)
if (options.rewrite && !options.passthrough)
{
// Rewrite the assembly in memory.
ContractNodes cnForRuntime = null;
// make sure to use the correct contract nodes for runtime code generation. We may have Contractnodes pointing to microsoft.Contracts even though
// the code relies on mscorlib to provide the contracts. So make sure the code references the contract nodes first.
if (contractNodes != null && contractNodes.ContractClass != null &&
contractNodes.ContractClass.DeclaringModule != SystemTypes.SystemAssembly)
{
string assemblyNameContainingContracts = contractNodes.ContractClass.DeclaringModule.Name;
for (int i = 0; i < assemblyNode.AssemblyReferences.Count; i++)
{
if (assemblyNode.AssemblyReferences[i].Name == assemblyNameContainingContracts)
{
cnForRuntime = contractNodes;
break; // runtime actually references the contract library
}
}
}
if (cnForRuntime == null)
{
// try to grab the system assembly contracts
cnForRuntime = ContractNodes.GetContractNodes(SystemTypes.SystemAssembly, null);
}
if (cnForRuntime == null)
{
// Can happen if the assembly does not use contracts directly, but inherits them from some other place
// Use the normal contractNodes in this case (actually we should generate whatever we grab from ContractNodes)
cnForRuntime = contractNodes;
}
RuntimeContractMethods runtimeContracts =
new RuntimeContractMethods(userSpecifiedContractType,
cnForRuntime, assemblyNode, options.throwOnFailure, options.level, options.publicSurfaceOnly,
options.callSiteRequires,
options.recursionGuard, options.hideFromDebugger, options.IsLegacyModeAssembly);
Rewriter rewriter = new Rewriter(assemblyNode, runtimeContracts, options.EmitError,
options.inheritInvariants, options.skipQuantifiers);
rewriter.Verbose = 0 < options.verbose;
rewriter.Visit(assemblyNode);
// Perform this check only when there are no out-of-band contracts in use due to rewriter bug #336
if (contractAssembly == null)
{
PostRewriteChecker checker = new PostRewriteChecker(options.EmitError);
checker.Visit(assemblyNode);
}
}
//Console.WriteLine(">>>Finished Rewriting<<<");
// Set metadata version for target the same as for the source
TargetPlatform.TargetRuntimeVersion = assemblyNode.TargetRuntimeVersion;
// Write out the assembly (optional)
if (options.rewrite || options.passthrough)
{
bool updateInPlace = options.output == "same";
string pdbFile = Path.ChangeExtension(options.assembly, ".pdb");
bool pdbExists = File.Exists(pdbFile);
string backupAssembly = options.assembly + ".original";
string backupPDB = pdbFile + ".original";
if (updateInPlace)
{
// Write the rewritten assembly in a temporary location.
options.output = options.assembly;
MoveAssemblyFileAndPDB(options.output, pdbFile, pdbExists, backupAssembly, backupPDB);
}
// Write the assembly.
// Don't pass the debugInfo flag to WriteModule unless the PDB file exists.
assemblyNode.WriteModule(options.output, options.debug && pdbExists && options.writePDBFile);
string outputDir = updateInPlace
? Path.GetDirectoryName(options.assembly)
: Path.GetDirectoryName(options.output);
// Re-attach external file resources to the new output assembly.
MoveModuleResources(assemblyNode, outputDir);
#if false
if (oldPeVerifyCode == 0)
{
var newPeVerifyCode = PEVerify(assemblyNode.Location, originalsourceDir);
if (newPeVerifyCode > 0)
{
if (updateInPlace)
{
// move original back in place
MoveAssemblyFileAndPDB(backupAssembly, backupPDB, pdbExists, options.output, pdbFile);
}
throw new Exception("Rewrite failed to produce verifiable assembly");
}
else if (newPeVerifyCode == 0)
{
Console.WriteLine("rewriter output verified");
}
}
#endif
if (updateInPlace)
{
if (!options.keepOriginalFiles)
{
try
{
File.Delete(backupAssembly);
}
catch
{
// there are situations where the exe is still in use
}
if (options.debug && pdbExists && options.writePDBFile)
{
try
{
File.Delete(backupPDB);
}
catch
{
// I know this is stupid, but somehow on some machines we get an AccessError trying to delete the pdb.
// so we leave it in place.
}
}
}
}
}
}
private static void MoveAssemblyFileAndPDB(string sourceAssembly, string sourcePDB, bool pdbExists,
string targetAssembly, string targetPDB)
{
// delete targets
try
{
Contract.Assume(!String.IsNullOrEmpty(sourceAssembly));
Contract.Assume(!String.IsNullOrEmpty(targetAssembly));
File.Delete(targetAssembly);
if (options.debug && pdbExists && options.writePDBFile)
{
File.Delete(targetPDB);
}
}
catch
{
}
// move things to target
try
{
File.Move(sourceAssembly, targetAssembly);
if (options.debug && pdbExists && options.writePDBFile)
{
Contract.Assume(!String.IsNullOrEmpty(sourcePDB));
File.Move(sourcePDB, targetPDB);
}
}
catch
{
}
}
private static bool CheckForMetaDataErrors(AssemblyNode aref)
{
Contract.Requires(aref != null);
if (aref.MetadataImportWarnings != null && aref.MetadataImportWarnings.Count > 0)
{
Console.WriteLine("Assembly '{0}' from '{1}' was skipped due to non-critical warnings.", aref.Name, aref.Location);
foreach (Exception e in aref.MetadataImportWarnings)
{
Console.WriteLine("\t" + e.Message);
}
}
bool result = false;
if (aref.MetadataImportErrors != null && aref.MetadataImportErrors.Count > 0)
{
Console.WriteLine("Reading assembly '{0}' from '{1}' resulted in errors.", aref.Name, aref.Location);
foreach (Exception ex in aref.MetadataImportErrors)
{
Console.WriteLine("\t" + ex.Message);
result = true;
}
}
if (options.ignoreMetadataErrors)
{
return false;
}
return result;
}
}
}
| |
using YAF.Lucene.Net.Support;
using System;
using System.Diagnostics;
namespace YAF.Lucene.Net.Util.Packed
{
/*
* 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 DataInput = YAF.Lucene.Net.Store.DataInput;
/// <summary>
/// Space optimized random access capable array of values with a fixed number of
/// bits/value. Values are packed contiguously.
/// <para/>
/// The implementation strives to perform af fast as possible under the
/// constraint of contiguous bits, by avoiding expensive operations. This comes
/// at the cost of code clarity.
/// <para/>
/// Technical details: this implementation is a refinement of a non-branching
/// version. The non-branching get and set methods meant that 2 or 4 atomics in
/// the underlying array were always accessed, even for the cases where only
/// 1 or 2 were needed. Even with caching, this had a detrimental effect on
/// performance.
/// Related to this issue, the old implementation used lookup tables for shifts
/// and masks, which also proved to be a bit slower than calculating the shifts
/// and masks on the fly.
/// See https://issues.apache.org/jira/browse/LUCENE-4062 for details.
/// </summary>
public class Packed64 : PackedInt32s.MutableImpl
{
internal const int BLOCK_SIZE = 64; // 32 = int, 64 = long
internal const int BLOCK_BITS = 6; // The #bits representing BLOCK_SIZE
internal static readonly int MOD_MASK = BLOCK_SIZE - 1; // x % BLOCK_SIZE
/// <summary>
/// Values are stores contiguously in the blocks array.
/// </summary>
private readonly long[] blocks;
/// <summary>
/// A right-aligned mask of width BitsPerValue used by <see cref="Get(int)"/>.
/// </summary>
private readonly long maskRight;
/// <summary>
/// Optimization: Saves one lookup in <see cref="Get(int)"/>.
/// </summary>
private readonly int bpvMinusBlockSize;
/// <summary>
/// Creates an array with the internal structures adjusted for the given
/// limits and initialized to 0. </summary>
/// <param name="valueCount"> The number of elements. </param>
/// <param name="bitsPerValue"> The number of bits available for any given value. </param>
public Packed64(int valueCount, int bitsPerValue)
: base(valueCount, bitsPerValue)
{
PackedInt32s.Format format = PackedInt32s.Format.PACKED;
int longCount = format.Int64Count(PackedInt32s.VERSION_CURRENT, valueCount, bitsPerValue);
this.blocks = new long[longCount];
// MaskRight = ~0L << (int)((uint)(BLOCK_SIZE - bitsPerValue) >> (BLOCK_SIZE - bitsPerValue)); //original
// MaskRight = (uint)(~0L << (BLOCK_SIZE - bitsPerValue)) >> (BLOCK_SIZE - bitsPerValue); //mod
/*var a = ~0L << (int)((uint)(BLOCK_SIZE - bitsPerValue) >> (BLOCK_SIZE - bitsPerValue)); //original
var b = (uint)(~0L << (BLOCK_SIZE - bitsPerValue)) >> (BLOCK_SIZE - bitsPerValue); //mod
Debug.Assert(a == b, "a: " + a, ", b: " + b);*/
maskRight = (long)((ulong)(~0L << (BLOCK_SIZE - bitsPerValue)) >> (BLOCK_SIZE - bitsPerValue)); //mod
//Debug.Assert((long)((ulong)(~0L << (BLOCK_SIZE - bitsPerValue)) >> (BLOCK_SIZE - bitsPerValue)) == (uint)(~0L << (BLOCK_SIZE - bitsPerValue)) >> (BLOCK_SIZE - bitsPerValue));
bpvMinusBlockSize = bitsPerValue - BLOCK_SIZE;
}
/// <summary>
/// Creates an array with content retrieved from the given <see cref="DataInput"/>. </summary>
/// <param name="in"> A <see cref="DataInput"/>, positioned at the start of Packed64-content. </param>
/// <param name="valueCount"> The number of elements. </param>
/// <param name="bitsPerValue"> The number of bits available for any given value. </param>
/// <exception cref="System.IO.IOException"> If the values for the backing array could not
/// be retrieved. </exception>
public Packed64(int packedIntsVersion, DataInput @in, int valueCount, int bitsPerValue)
: base(valueCount, bitsPerValue)
{
PackedInt32s.Format format = PackedInt32s.Format.PACKED;
long byteCount = format.ByteCount(packedIntsVersion, valueCount, bitsPerValue); // to know how much to read
int longCount = format.Int64Count(PackedInt32s.VERSION_CURRENT, valueCount, bitsPerValue); // to size the array
blocks = new long[longCount];
// read as many longs as we can
for (int i = 0; i < byteCount / 8; ++i)
{
blocks[i] = @in.ReadInt64();
}
int remaining = (int)(byteCount % 8);
if (remaining != 0)
{
// read the last bytes
long lastLong = 0;
for (int i = 0; i < remaining; ++i)
{
lastLong |= (@in.ReadByte() & 0xFFL) << (56 - i * 8);
}
blocks[blocks.Length - 1] = lastLong;
}
maskRight = (long)((ulong)(~0L << (BLOCK_SIZE - bitsPerValue)) >> (BLOCK_SIZE - bitsPerValue));
bpvMinusBlockSize = bitsPerValue - BLOCK_SIZE;
}
/// <param name="index"> The position of the value. </param>
/// <returns> The value at the given index. </returns>
public override long Get(int index)
{
// The abstract index in a bit stream
long majorBitPos = (long)index * m_bitsPerValue;
// The index in the backing long-array
int elementPos = (int)(((ulong)majorBitPos) >> BLOCK_BITS);
//int elementPos = (int)((long)((ulong)majorBitPos >> BLOCK_BITS));
// The number of value-bits in the second long
long endBits = (majorBitPos & MOD_MASK) + bpvMinusBlockSize;
if (endBits <= 0) // Single block
{
return ((long)((ulong)blocks[elementPos] >> (int)-endBits)) & maskRight;
}
// Two blocks
return ((blocks[elementPos] << (int)endBits) | ((long)((ulong)blocks[elementPos + 1] >> (int)(BLOCK_SIZE - endBits)))) & maskRight;
}
/*/// <param name="index"> the position of the value. </param>
/// <returns> the value at the given index. </returns>
public override long Get(int index)
{
// The abstract index in a bit stream
long majorBitPos = (long)index * bitsPerValue;
// The index in the backing long-array
int elementPos = (int)((long)((ulong)majorBitPos >> BLOCK_BITS));
// The number of value-bits in the second long
long endBits = (majorBitPos & MOD_MASK) + BpvMinusBlockSize;
if (endBits <= 0) // Single block
{
var mod = (long) ((ulong) (Blocks[elementPos]) >> (int) (-endBits)) & MaskRight;
var og = ((long) ((ulong) Blocks[elementPos] >> (int) -endBits)) & MaskRight;
Debug.Assert(mod == og);
//return (long)((ulong)(Blocks[elementPos]) >> (int)(-endBits)) & MaskRight;
return ((long)((ulong)Blocks[elementPos] >> (int)-endBits)) & MaskRight;
}
// Two blocks
var a = (((Blocks[elementPos] << (int)endBits) | (long)(((ulong)(Blocks[elementPos + 1])) >> (int)(BLOCK_SIZE - endBits))) & MaskRight);
var b = ((Blocks[elementPos] << (int)endBits) | ((long)((ulong)Blocks[elementPos + 1] >> (int)(BLOCK_SIZE - endBits)))) & MaskRight;
Debug.Assert(a == b);
//return (((Blocks[elementPos] << (int)endBits) | (long)(((ulong)(Blocks[elementPos + 1])) >> (int)(BLOCK_SIZE - endBits))) & MaskRight);
return ((Blocks[elementPos] << (int)endBits) | ((long)((ulong)Blocks[elementPos + 1] >> (int)(BLOCK_SIZE - endBits)))) & MaskRight;
}*/
public override int Get(int index, long[] arr, int off, int len)
{
Debug.Assert(len > 0, "len must be > 0 (got " + len + ")");
Debug.Assert(index >= 0 && index < m_valueCount);
len = Math.Min(len, m_valueCount - index);
Debug.Assert(off + len <= arr.Length);
int originalIndex = index;
PackedInt32s.IDecoder decoder = BulkOperation.Of(PackedInt32s.Format.PACKED, m_bitsPerValue);
// go to the next block where the value does not span across two blocks
int offsetInBlocks = index % decoder.Int64ValueCount;
if (offsetInBlocks != 0)
{
for (int i = offsetInBlocks; i < decoder.Int64ValueCount && len > 0; ++i)
{
arr[off++] = Get(index++);
--len;
}
if (len == 0)
{
return index - originalIndex;
}
}
// bulk get
Debug.Assert(index % decoder.Int64ValueCount == 0);
int blockIndex = (int)((ulong)((long)index * m_bitsPerValue) >> BLOCK_BITS);
Debug.Assert((((long)index * m_bitsPerValue) & MOD_MASK) == 0);
int iterations = len / decoder.Int64ValueCount;
decoder.Decode(blocks, blockIndex, arr, off, iterations);
int gotValues = iterations * decoder.Int64ValueCount;
index += gotValues;
len -= gotValues;
Debug.Assert(len >= 0);
if (index > originalIndex)
{
// stay at the block boundary
return index - originalIndex;
}
else
{
// no progress so far => already at a block boundary but no full block to get
Debug.Assert(index == originalIndex);
return base.Get(index, arr, off, len);
}
}
public override void Set(int index, long value)
{
// The abstract index in a contiguous bit stream
long majorBitPos = (long)index * m_bitsPerValue;
// The index in the backing long-array
int elementPos = (int)((long)((ulong)majorBitPos >> BLOCK_BITS)); // / BLOCK_SIZE
// The number of value-bits in the second long
long endBits = (majorBitPos & MOD_MASK) + bpvMinusBlockSize;
if (endBits <= 0) // Single block
{
blocks[elementPos] = blocks[elementPos] & ~(maskRight << (int)-endBits) | (value << (int)-endBits);
return;
}
// Two blocks
blocks[elementPos] = blocks[elementPos] & ~((long)((ulong)maskRight >> (int)endBits)) | ((long)((ulong)value >> (int)endBits));
blocks[elementPos + 1] = blocks[elementPos + 1] & ((long)(unchecked((ulong)~0L) >> (int)endBits)) | (value << (int)(BLOCK_SIZE - endBits));
}
public override int Set(int index, long[] arr, int off, int len)
{
Debug.Assert(len > 0, "len must be > 0 (got " + len + ")");
Debug.Assert(index >= 0 && index < m_valueCount);
len = Math.Min(len, m_valueCount - index);
Debug.Assert(off + len <= arr.Length);
int originalIndex = index;
PackedInt32s.IEncoder encoder = BulkOperation.Of(PackedInt32s.Format.PACKED, m_bitsPerValue);
// go to the next block where the value does not span across two blocks
int offsetInBlocks = index % encoder.Int64ValueCount;
if (offsetInBlocks != 0)
{
for (int i = offsetInBlocks; i < encoder.Int64ValueCount && len > 0; ++i)
{
Set(index++, arr[off++]);
--len;
}
if (len == 0)
{
return index - originalIndex;
}
}
// bulk set
Debug.Assert(index % encoder.Int64ValueCount == 0);
int blockIndex = (int)((ulong)((long)index * m_bitsPerValue) >> BLOCK_BITS);
Debug.Assert((((long)index * m_bitsPerValue) & MOD_MASK) == 0);
int iterations = len / encoder.Int64ValueCount;
encoder.Encode(arr, off, blocks, blockIndex, iterations);
int setValues = iterations * encoder.Int64ValueCount;
index += setValues;
len -= setValues;
Debug.Assert(len >= 0);
if (index > originalIndex)
{
// stay at the block boundary
return index - originalIndex;
}
else
{
// no progress so far => already at a block boundary but no full block to get
Debug.Assert(index == originalIndex);
return base.Set(index, arr, off, len);
}
}
public override string ToString()
{
return "Packed64(bitsPerValue=" + m_bitsPerValue + ", size=" + Count + ", elements.length=" + blocks.Length + ")";
}
public override long RamBytesUsed()
{
return RamUsageEstimator.AlignObjectSize(
RamUsageEstimator.NUM_BYTES_OBJECT_HEADER
+ 3 * RamUsageEstimator.NUM_BYTES_INT32 // bpvMinusBlockSize,valueCount,bitsPerValue
+ RamUsageEstimator.NUM_BYTES_INT64 // maskRight
+ RamUsageEstimator.NUM_BYTES_OBJECT_REF) // blocks ref
+ RamUsageEstimator.SizeOf(blocks);
}
public override void Fill(int fromIndex, int toIndex, long val)
{
Debug.Assert(PackedInt32s.BitsRequired(val) <= BitsPerValue);
Debug.Assert(fromIndex <= toIndex);
// minimum number of values that use an exact number of full blocks
int nAlignedValues = 64 / Gcd(64, m_bitsPerValue);
int span = toIndex - fromIndex;
if (span <= 3 * nAlignedValues)
{
// there needs be at least 2 * nAlignedValues aligned values for the
// block approach to be worth trying
base.Fill(fromIndex, toIndex, val);
return;
}
// fill the first values naively until the next block start
int fromIndexModNAlignedValues = fromIndex % nAlignedValues;
if (fromIndexModNAlignedValues != 0)
{
for (int i = fromIndexModNAlignedValues; i < nAlignedValues; ++i)
{
Set(fromIndex++, val);
}
}
Debug.Assert(fromIndex % nAlignedValues == 0);
// compute the long[] blocks for nAlignedValues consecutive values and
// use them to set as many values as possible without applying any mask
// or shift
int nAlignedBlocks = (nAlignedValues * m_bitsPerValue) >> 6;
long[] nAlignedValuesBlocks;
{
Packed64 values = new Packed64(nAlignedValues, m_bitsPerValue);
for (int i = 0; i < nAlignedValues; ++i)
{
values.Set(i, val);
}
nAlignedValuesBlocks = values.blocks;
Debug.Assert(nAlignedBlocks <= nAlignedValuesBlocks.Length);
}
int startBlock = (int)((ulong)((long)fromIndex * m_bitsPerValue) >> 6);
int endBlock = (int)((ulong)((long)toIndex * m_bitsPerValue) >> 6);
for (int block = startBlock; block < endBlock; ++block)
{
long blockValue = nAlignedValuesBlocks[block % nAlignedBlocks];
blocks[block] = blockValue;
}
// fill the gap
for (int i = (int)(((long)endBlock << 6) / m_bitsPerValue); i < toIndex; ++i)
{
Set(i, val);
}
}
private static int Gcd(int a, int b)
{
if (a < b)
{
return Gcd(b, a);
}
else if (b == 0)
{
return a;
}
else
{
return Gcd(b, a % b);
}
}
public override void Clear()
{
Arrays.Fill(blocks, 0L);
}
}
}
| |
using Signum.Engine.Basics;
using Signum.Entities;
using Signum.Entities.DynamicQuery;
using Signum.Entities.MachineLearning;
using Signum.Entities.UserQueries;
using Signum.Utilities;
using Signum.Utilities.DataStructures;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Signum.Engine.MachineLearning
{
public static class PredictorPredictLogic
{
public static RecentDictionary<Lite<PredictorEntity>, PredictorPredictContext> TrainedPredictorCache = new RecentDictionary<Lite<PredictorEntity>, PredictorPredictContext>(50);
public static Lite<PredictorEntity> GetCurrentPredictor(PredictorPublicationSymbol publication)
{
var predictor = Database.Query<PredictorEntity>().Where(a => a.Publication == publication).Select(a => a.ToLite()).SingleEx();
return predictor;
}
public static PredictorPredictContext GetPredictContext(this PredictorPublicationSymbol publication) => GetCurrentPredictor(publication).GetPredictContext();
public static PredictorPredictContext GetPredictContext(this Lite<PredictorEntity> predictor)
{
lock (TrainedPredictorCache)
return TrainedPredictorCache.GetOrCreate(predictor, () =>
{
using (ExecutionMode.Global())
using (var t = Transaction.ForceNew())
{
var p = predictor.RetrieveAndRemember();
if (p.State != PredictorState.Trained)
throw new InvalidOperationException($"Predictor '{p.Name}' not trained");
PredictorPredictContext ppc = CreatePredictContext(p);
return t.Commit(ppc);
}
});
}
public static PredictorPredictContext CreatePredictContext(this PredictorEntity p)
{
var codifications = p.RetrievePredictorCodifications();
var ppc = new PredictorPredictContext(p, PredictorLogic.Algorithms.GetOrThrow(p.Algorithm), codifications);
ppc.Algorithm.LoadModel(ppc);
return ppc;
}
public static PredictDictionary GetInputsFromEntity(this PredictorPredictContext ctx, Lite<Entity> entity, PredictionOptions? options = null)
{
var qd = QueryLogic.Queries.QueryDescription(ctx.Predictor.MainQuery.Query.ToQueryName());
var entityToken = QueryUtils.Parse("Entity", qd, 0);
return ctx.FromFilters(new List<Filter> { new FilterCondition(entityToken, FilterOperation.EqualTo, entity) }, options).SingleEx();
}
public static PredictDictionary GetInputsFromParentKeys(this PredictorPredictContext ctx, Dictionary<QueryToken, object?> parentKeyValues, PredictionOptions? options = null)
{
if (!ctx.Predictor.MainQuery.GroupResults)
{
var kvp = parentKeyValues.SingleEx();
if (kvp.Key.FullKey() != "Entity")
throw new InvalidOperationException("only Entity expected");
var filters = new List<Filter> { new FilterCondition(kvp.Key, FilterOperation.EqualTo, kvp.Value) };
return ctx.FromFilters(filters, options).SingleEx();
}
else
{
var filters = ctx.Predictor.MainQuery.Columns
.Select(a => a.Token.Token)
.Where(t => !(t is AggregateToken))
.Select(t => (Filter)new FilterCondition(t, FilterOperation.EqualTo, parentKeyValues.GetOrThrow(t)))
.ToList();
return ctx.FromFilters(filters, options).SingleEx();
}
}
public static PredictDictionary GetInputsEmpty(this PredictorPredictContext ctx, PredictionOptions? options = null)
{
var result = new PredictDictionary(ctx.Predictor, options, null)
{
MainQueryValues = ctx.Predictor.MainQuery.Columns.Select((c, i) => KeyValuePair.Create(c, (object?)null)).ToDictionaryEx(),
SubQueries = ctx.Predictor.SubQueries.ToDictionary(sq => sq, sq => new PredictSubQueryDictionary(sq)
{
SubQueryGroups = new Dictionary<object?[], Dictionary<PredictorSubQueryColumnEmbedded, object?>>(ObjectArrayComparer.Instance)
})
};
return result;
}
public static List<PredictDictionary> FromFilters(this PredictorPredictContext ctx, List<Filter> filters, PredictionOptions? options = null)
{
var qd = QueryLogic.Queries.QueryDescription(ctx.Predictor.MainQuery.Query.ToQueryName());
var qr = new QueryRequest
{
QueryName = qd.QueryName,
GroupResults = ctx.Predictor.MainQuery.GroupResults,
Filters = filters, /*Filters of Main Query not considered*/
Columns = ctx.Predictor.MainQuery.Columns.Select(c => new Column(c.Token.Token, null)).ToList(),
Pagination = new Pagination.All(),
Orders = Enumerable.Empty<Order>().ToList(),
};
var mainQueryKeys = PredictorLogic.GetParentKeys(ctx.Predictor.MainQuery);
var rt = QueryLogic.Queries.ExecuteQuery(qr);
var subQueryResults = ctx.Predictor.SubQueries.ToDictionaryEx(sq => sq, sqe =>
{
List<QueryToken> parentKeys = sqe.Columns.Where(a => a.Usage == PredictorSubQueryColumnUsage.ParentKey).Select(a => a.Token.Token).ToList();
QueryDescription sqd = QueryLogic.Queries.QueryDescription(sqe.Query.ToQueryName());
Dictionary<string, string> tokenReplacements = mainQueryKeys.ZipStrict(parentKeys, (m, p) => KeyValuePair.Create(m.FullKey(), p.FullKey())).ToDictionaryEx();
Filter[] mainFilters = filters.Select(f => Replace(f, tokenReplacements, sqd)).ToArray();
List<Filter> additionalFilters = sqe.Filters.ToFilterList();
List<Column> allColumns = sqe.Columns.Select(c => new Column(c.Token.Token, null)).ToList();
var qgr = new QueryRequest
{
QueryName = sqe.Query.ToQueryName(),
GroupResults = true,
Filters = mainFilters.Concat(additionalFilters).ToList(),
Columns = allColumns,
Orders = new List<Order>(),
Pagination = new Pagination.All(),
};
ResultTable resultTable = QueryLogic.Queries.ExecuteQuery(qgr);
var tuples = sqe.Columns.Zip(resultTable.Columns, (sqc, rc) => (sqc: sqc, rc: rc)).ToList();
ResultColumn[] entityGroupKey = tuples.Extract(t => t.sqc.Usage == PredictorSubQueryColumnUsage.ParentKey).Select(a=>a.rc).ToArray();
ResultColumn[] remainingKeys = tuples.Extract(t => t.sqc.Usage == PredictorSubQueryColumnUsage.SplitBy).Select(a => a.rc).ToArray();
var valuesTuples = tuples;
return resultTable.Rows.AgGroupToDictionary(
row => row.GetValues(entityGroupKey),
gr => gr.ToDictionaryEx(
row => row.GetValues(remainingKeys),
row => valuesTuples.ToDictionaryEx(t => t.sqc, t => row[t.rc]),
ObjectArrayComparer.Instance
)
);
});
var mainKeys = rt.Columns.Where(rc => !(rc.Column.Token is AggregateToken)).ToArray();
var result = rt.Rows.Select(row => new PredictDictionary(ctx.Predictor, options, row.TryEntity)
{
MainQueryValues = ctx.Predictor.MainQuery.Columns.Select((c, i) => KeyValuePair.Create(c, row[i])).ToDictionaryEx(),
SubQueries = ctx.Predictor.SubQueries.ToDictionary(sq => sq, sq => new PredictSubQueryDictionary(sq)
{
SubQueryGroups = subQueryResults.TryGetC(sq)?.TryGetC(row.GetValues(mainKeys)) ??
new Dictionary<object?[], Dictionary<PredictorSubQueryColumnEmbedded, object?>>(ObjectArrayComparer.Instance)
})
}).ToList();
return result;
}
private static Filter Replace(Filter filter, Dictionary<string, string> tokenReplacements, QueryDescription qd)
{
if (filter is FilterGroup fg)
return new FilterGroup(fg.GroupOperation, Replace(fg.Token!, tokenReplacements, qd), fg.Filters.Select(f => Replace(f, tokenReplacements, qd)).ToList());
if (filter is FilterCondition fc)
return new FilterCondition(Replace(fc.Token, tokenReplacements, qd), fc.Operation, fc.Value);
throw new UnexpectedValueException(filter);
}
private static QueryToken Replace(QueryToken token, Dictionary<string, string> tokenReplacements, QueryDescription qd)
{
var tokenFullKey = token.FullKey();
var bestKey = tokenReplacements.Keys.OrderByDescending(a => a.Length)
.Where(k => k == tokenFullKey || tokenFullKey.StartsWith(k + "."))
.FirstEx(() => "Impossible to use token '" + tokenFullKey + "' in SubQuery");
var newToken = bestKey == tokenFullKey ? tokenReplacements.GetOrThrow(bestKey) :
tokenReplacements.GetOrThrow(bestKey) + tokenFullKey.After(bestKey);
return QueryUtils.Parse(newToken, qd, SubTokensOptions.CanAggregate | SubTokensOptions.CanAnyAll | SubTokensOptions.CanElement);
}
public static Dictionary<ResultRow, PredictDictionary> ToPredictDictionaries(this PredictorTrainingContext ctx, PredictionOptions? options = null)
{
var subQueryResults = ctx.Predictor.SubQueries.ToDictionaryEx(sq => sq, sqe =>
{
var resultTable = ctx.SubQueries[sqe].ResultTable;
var tuples = sqe.Columns.Zip(resultTable.Columns, (sqc, rc) => (sqc: sqc, rc: rc)).ToList();
ResultColumn[] parentKeys = tuples.Extract(t => t.sqc.Usage == PredictorSubQueryColumnUsage.ParentKey).Select(a => a.rc).ToArray();
ResultColumn[] remainingKeys = tuples.Extract(t => t.sqc.Usage == PredictorSubQueryColumnUsage.SplitBy).Select(a => a.rc).ToArray();
var valuesTuples = tuples;
return resultTable.Rows.AgGroupToDictionary(
row => row.GetValues(parentKeys),
gr => gr.ToDictionaryEx(
row => row.GetValues(remainingKeys),
row => valuesTuples.ToDictionaryEx(t => t.sqc, t => row[t.rc]),
ObjectArrayComparer.Instance
)
);
});
var result = ctx.MainQuery.ResultTable.Rows.ToDictionaryEx(row => row, row => new PredictDictionary(ctx.Predictor, options, row.TryEntity)
{
MainQueryValues = ctx.Predictor.MainQuery.Columns.Select((c, i) => KeyValuePair.Create(c, row[i])).ToDictionaryEx(),
SubQueries = ctx.Predictor.SubQueries.ToDictionary(sq => sq, sq => new PredictSubQueryDictionary(sq)
{
SubQueryGroups = (subQueryResults.TryGetC(sq)?.TryGetC(ctx.MainQuery.GetParentKey(row))) ?? new Dictionary<object?[], Dictionary<PredictorSubQueryColumnEmbedded, object?>>(ObjectArrayComparer.Instance)
})
});
return result;
}
public static PredictDictionary PredictBasic(this PredictDictionary input)
{
var pctx = GetPredictContext(input.Predictor.ToLite());
return pctx.Algorithm.Predict(pctx, input);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="HtmlInputFile.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
* HtmlInputFile.cs
*
* Copyright (c) 2000 Microsoft Corporation
*/
namespace System.Web.UI.HtmlControls {
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
using System.Web;
using System.Web.UI;
using System.Security.Permissions;
/// <devdoc>
/// <para>
/// The <see langword='HtmlInputFile'/> class defines the
/// methods, properties, and events for the <see langword='HtmlInputFile'/> control. This class allows
/// programmatic access to the HTML <input type= file> element on the server.
/// It provides access to the stream, as well as a useful SaveAs functionality
/// provided by the <see cref='System.Web.UI.HtmlControls.HtmlInputFile.PostedFile'/>
/// property.
/// </para>
/// <note type="caution">
/// This class only works if the
/// HtmlForm.Enctype property is set to "multipart/form-data".
/// Also, it does not maintain its
/// state across multiple round trips between browser and server. If the user sets
/// this value after a round trip, the value is lost.
/// </note>
/// </devdoc>
[
ValidationProperty("Value")
]
public class HtmlInputFile : HtmlInputControl, IPostBackDataHandler {
/*
* Creates an intrinsic Html INPUT type=file control.
*/
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.Web.UI.HtmlControls.HtmlInputFile'/> class.</para>
/// </devdoc>
public HtmlInputFile() : base("file") {
}
/*
* Accept type property.
*/
/// <devdoc>
/// <para>
/// Gets
/// or sets a comma-separated list of MIME encodings that
/// can be used to constrain the file types that the browser lets the user
/// select. For example, to restrict the
/// selection to images, the accept value image/* should be specified.
/// </para>
/// </devdoc>
[
WebCategory("Behavior"),
DefaultValue(""),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public string Accept {
get {
string s = Attributes["accept"];
return((s != null) ? s : String.Empty);
}
set {
Attributes["accept"] = MapStringAttributeToString(value);
}
}
/*
* The property for the maximum characters allowed.
*/
/// <devdoc>
/// <para>
/// Gets or sets the
/// maximum length of the file path of the file to upload
/// from the client machine.
/// </para>
/// </devdoc>
[
WebCategory("Behavior"),
DefaultValue(""),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public int MaxLength {
get {
string s = Attributes["maxlength"];
return((s != null) ? Int32.Parse(s, CultureInfo.InvariantCulture) : -1);
}
set {
Attributes["maxlength"] = MapIntegerAttributeToString(value);
}
}
/*
* PostedFile property.
*/
/// <devdoc>
/// <para>Gets access to the uploaded file specified by a client.</para>
/// </devdoc>
[
WebCategory("Default"),
DefaultValue(""),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public HttpPostedFile PostedFile {
get { return Context.Request.Files[RenderedNameAttribute];}
}
/*
* The property for the width in characters.
*/
/// <devdoc>
/// <para>Gets or sets the width of the file-path text box that the
/// browser displays when the <see cref='System.Web.UI.HtmlControls.HtmlInputFile'/>
/// control is used on a page.</para>
/// </devdoc>
[
WebCategory("Appearance"),
DefaultValue(-1),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public int Size {
get {
string s = Attributes["size"];
return((s != null) ? Int32.Parse(s, CultureInfo.InvariantCulture) : -1);
}
set {
Attributes["size"] = MapIntegerAttributeToString(value);
}
}
// ASURT 122262 : The value property isn't submitted back to us when the a page
// containing this control postsback, so required field validators are broken
// (value would contain the empty string). To fix this, we return the filename.
[
Browsable(false)
]
public override string Value {
get {
HttpPostedFile postedFile = PostedFile;
if (postedFile != null) {
return postedFile.FileName;
}
return String.Empty;
}
set {
// Throw here because setting the value on this tag has no effect on the
// rendering behavior and since we're always returning the posted file's
// filename, we don't want to get into a situation where the user
// sets a value and does not get back that value.
throw new NotSupportedException(SR.GetString(SR.Value_Set_Not_Supported, this.GetType().Name));
}
}
/*
* Method of IPostBackDataHandler interface to process posted data.
*/
/// <internalonly/>
bool IPostBackDataHandler.LoadPostData(string postDataKey, NameValueCollection postCollection) {
return LoadPostData(postDataKey, postCollection);
}
protected virtual bool LoadPostData(string postDataKey, NameValueCollection postCollection) {
return false;
}
/*
* Method of IPostBackDataHandler interface which is invoked whenever
* posted data for a control has changed. RadioButton fires an
* OnServerChange event.
*/
/// <internalonly/>
void IPostBackDataHandler.RaisePostDataChangedEvent() {
RaisePostDataChangedEvent();
}
protected virtual void RaisePostDataChangedEvent() {
}
/// <devdoc>
/// <para>Raises the <see langword='PreRender'/> event. This method uses event arguments
/// to pass the event data to the control.</para>
/// </devdoc>
protected internal override void OnPreRender(EventArgs e) {
base.OnPreRender(e);
// ASURT 35328: use multipart encoding if no encoding is currently specified
HtmlForm form = Page.Form;
if (form != null && form.Enctype.Length == 0) {
form.Enctype = "multipart/form-data";
}
}
}
}
| |
using System;
using System.IO;
using System.Collections;
namespace LumiSoft.Net.Mime
{
/// <summary>
/// Class for creating,parsing,modifing rfc 2822 mime messages.
/// </summary>
/// <remarks>
/// <code>
///
/// Message examples:
///
/// <B>Simple message:</B>
///
/// //--- Beginning of message
/// From: sender@domain.com
/// To: recipient@domain.com
/// Subject: Message subject.
/// Content-Type: text/plain
///
/// Message body text. Bla blaa
/// blaa,blaa.
/// //--- End of message
///
///
/// In simple message MainEntity is whole message.
///
/// <B>Message with attachments:</B>
///
/// //--- Beginning of message
/// From: sender@domain.com
/// To: recipient@domain.com
/// Subject: Message subject.
/// Content-Type: multipart/mixed; boundary="multipart_mixed"
///
/// --multipart_mixed /* text entity */
/// Content-Type: text/plain
///
/// Message body text. Bla blaa
/// blaa,blaa.
/// --multipart_mixed /* attachment entity */
/// Content-Type: application/octet-stream
///
/// attachment_data
/// --multipart_mixed--
/// //--- End of message
///
/// MainEntity is multipart_mixed entity and text and attachment entities are child entities of MainEntity.
/// </code>
/// </remarks>
/// <example>
/// <code>
/// // Parsing example:
/// Mime m = Mime.Parse("message.eml");
/// // Do your stuff with mime
/// </code>
/// <code>
/// // Creating a new simple message
/// Mime m = new Mime();
/// MimeEntity mainEntity = m.MainEntity;
/// // Force to create From: header field
/// mainEntity.From = new AddressList();
/// mainEntity.From.Add(new MailboxAddress("dispaly name","user@domain.com"));
/// // Force to create To: header field
/// mainEntity.To = new AddressList();
/// mainEntity.To.Add(new MailboxAddress("dispaly name","user@domain.com"));
/// mainEntity.Subject = "subject";
/// mainEntity.ContentType = MediaType_enum.Text_plain;
/// mainEntity.ContentTransferEncoding = ContentTransferEncoding_enum.QuotedPrintable;
/// mainEntity.DataText = "Message body text.";
///
/// m.ToFile("message.eml");
/// </code>
/// <code>
/// // Creating message with text and attachments
/// Mime m = new Mime();
/// MimeEntity mainEntity = m.MainEntity;
/// // Force to create From: header field
/// mainEntity.From = new AddressList();
/// mainEntity.From.Add(new MailboxAddress("dispaly name","user@domain.com"));
/// // Force to create To: header field
/// mainEntity.To = new AddressList();
/// mainEntity.To.Add(new MailboxAddress("dispaly name","user@domain.com"));
/// mainEntity.Subject = "subject";
/// mainEntity.ContentType = MediaType_enum.Multipart_mixed;
///
/// MimeEntity textEntity = mainEntity.ChildEntities.Add();
/// textEntity.ContentType = MediaType_enum.Text_plain;
/// textEntity.ContentTransferEncoding = ContentTransferEncoding_enum.QuotedPrintable;
/// textEntity.DataText = "Message body text.";
///
/// MimeEntity attachmentEntity = mainEntity.ChildEntities.Add();
/// attachmentEntity.ContentType = MediaType_enum.Application_octet_stream;
/// attachmentEntity.ContentDisposition = ContentDisposition_enum.Attachment;
/// attachmentEntity.ContentTransferEncoding = ContentTransferEncoding_enum.Base64;
/// attachmentEntity.ContentDisposition_FileName = "yourfile.xxx";
/// attachmentEntity.DataFromFile("yourfile.xxx");
/// // or
/// attachmentEntity.Data = your_attachment_data;
/// </code>
/// </example>
public class Mime
{
private MimeEntity m_pMainEntity = null;
/// <summary>
/// Default constructor.
/// </summary>
public Mime()
{
m_pMainEntity = new MimeEntity();
// Add default header fields
m_pMainEntity.MessageID = MimeUtils.CreateMessageID();
m_pMainEntity.Date = DateTime.Now;
m_pMainEntity.MimeVersion = "1.0";
}
#region static method Parse
/// <summary>
/// Parses mime message from byte[] data.
/// </summary>
/// <param name="data">Mime message data.</param>
/// <returns></returns>
public static Mime Parse(byte[] data)
{
using(MemoryStream ms = new MemoryStream(data)){
return Parse(ms);
}
}
/// <summary>
/// Parses mime message from file.
/// </summary>
/// <param name="fileName">Mime message file.</param>
/// <returns></returns>
public static Mime Parse(string fileName)
{
using(FileStream fs = File.OpenRead(fileName)){
return Parse(fs);
}
}
/// <summary>
/// Parses mime message from stream.
/// </summary>
/// <param name="stream">Mime message stream.</param>
/// <returns></returns>
public static Mime Parse(Stream stream)
{
Mime mime = new Mime();
mime.MainEntity.Parse(stream,null);
return mime;
}
#endregion
#region method ToStringData
/// <summary>
/// Stores mime message to string.
/// </summary>
/// <returns></returns>
public string ToStringData()
{
return System.Text.Encoding.Default.GetString(this.ToByteData());
}
#endregion
#region method ToByteData
/// <summary>
/// Stores mime message to byte[].
/// </summary>
/// <returns></returns>
public byte[] ToByteData()
{
using(MemoryStream ms = new MemoryStream()){
ToStream(ms);
return ms.ToArray();
}
}
#endregion
#region method ToFile
/// <summary>
/// Stores mime message to specified file.
/// </summary>
/// <param name="fileName">File name.</param>
public void ToFile(string fileName)
{
using(FileStream fs = File.Create(fileName)){
ToStream(fs);
}
}
#endregion
#region method ToStream
/// <summary>
/// Stores mime message to specified stream. Stream position stays where mime writing ends.
/// </summary>
/// <param name="storeStream">Stream where to store mime message.</param>
public void ToStream(Stream storeStream)
{
m_pMainEntity.ToStream(storeStream);
}
#endregion
#region function GetEntities
/// <summary>
/// Gets mime entities, including nested entries.
/// </summary>
/// <param name="entities"></param>
/// <param name="allEntries"></param>
private void GetEntities(MimeEntityCollection entities,ArrayList allEntries)
{
if(entities != null){
foreach(MimeEntity ent in entities){
allEntries.Add(ent);
// Add child entities, if any
if(ent.ChildEntities.Count > 0){
GetEntities(ent.ChildEntities,allEntries);
}
}
}
}
#endregion
#region Properties Implementaion
/// <summary>
/// Message main(top-level) entity.
/// </summary>
public MimeEntity MainEntity
{
get{ return m_pMainEntity; }
}
/// <summary>
/// Gets all mime entities contained in message, including child entities.
/// </summary>
public MimeEntity[] MimeEntities
{
get{
ArrayList allEntities = new ArrayList();
allEntities.Add(m_pMainEntity);
GetEntities(m_pMainEntity.ChildEntities,allEntities);
return (MimeEntity[])allEntities.ToArray(typeof(MimeEntity));
}
}
/// <summary>
/// Gets mime entities which Content-Disposition: is Attachment or Inline.
/// </summary>
public MimeEntity[] Attachments
{
get{
ArrayList attachments = new ArrayList();
MimeEntity[] entities = this.MimeEntities;
foreach(MimeEntity entity in entities){
if(entity.ContentDisposition == ContentDisposition_enum.Attachment || entity.ContentDisposition == ContentDisposition_enum.Inline){
attachments.Add(entity);
}
}
return (MimeEntity[])attachments.ToArray(typeof(MimeEntity));
}
}
/// <summary>
/// Gets message body text. Returns null if no body text specified.
/// </summary>
public string BodyText
{
get{
MimeEntity[] entities = this.MimeEntities;
foreach(MimeEntity entity in entities){
if(entity.ContentType == MediaType_enum.Text_plain){
return entity.DataText;
}
}
return null;
}
}
/// <summary>
/// Gets message body html. Returns null if no body html text specified.
/// </summary>
public string BodyHtml
{
get{
MimeEntity[] entities = this.MimeEntities;
foreach(MimeEntity entity in entities){
if(entity.ContentType == MediaType_enum.Text_html){
return entity.DataText;
}
}
return null;
}
}
#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.Xml;
using System.Diagnostics;
using System.Globalization;
namespace System.Transactions.Diagnostics
{
internal enum EnlistmentType
{
Volatile = 0,
Durable = 1,
PromotableSinglePhase = 2
}
internal enum NotificationCall
{
// IEnlistmentNotification
Prepare = 0,
Commit = 1,
Rollback = 2,
InDoubt = 3,
// ISinglePhaseNotification
SinglePhaseCommit = 4,
// IPromotableSinglePhaseNotification
Promote = 5
}
internal enum EnlistmentCallback
{
Done = 0,
Prepared = 1,
ForceRollback = 2,
Committed = 3,
Aborted = 4,
InDoubt = 5
}
internal enum TransactionScopeResult
{
CreatedTransaction = 0,
UsingExistingCurrent = 1,
TransactionPassed = 2,
DependentTransactionPassed = 3,
NoTransaction = 4
}
/// <summary>
/// TraceHelper is an internal class that is used by TraceRecord classes to write
/// TransactionTraceIdentifiers and EnlistmentTraceIdentifiers to XmlWriters.
/// </summary>
internal static class TraceHelper
{
internal static void WriteTxId(XmlWriter writer, TransactionTraceIdentifier txTraceId)
{
writer.WriteStartElement("TransactionTraceIdentifier");
if (null != txTraceId.TransactionIdentifier)
{
writer.WriteElementString("TransactionIdentifier", txTraceId.TransactionIdentifier);
}
else
{
writer.WriteElementString("TransactionIdentifier", "");
}
// Don't write out CloneIdentifiers of 0 it's confusing.
int cloneId = txTraceId.CloneIdentifier;
if (cloneId != 0)
{
writer.WriteElementString("CloneIdentifier", cloneId.ToString(CultureInfo.CurrentCulture));
}
writer.WriteEndElement();
}
internal static void WriteEnId(XmlWriter writer, EnlistmentTraceIdentifier enId)
{
writer.WriteStartElement("EnlistmentTraceIdentifier");
writer.WriteElementString("ResourceManagerId", enId.ResourceManagerIdentifier.ToString());
TraceHelper.WriteTxId(writer, enId.TransactionTraceId);
writer.WriteElementString("EnlistmentIdentifier", enId.EnlistmentIdentifier.ToString(CultureInfo.CurrentCulture));
writer.WriteEndElement();
}
internal static void WriteTraceSource(XmlWriter writer, string traceSource)
{
writer.WriteElementString("TraceSource", traceSource);
}
}
#region one
/// <summary>
/// Trace record for the TransactionCreated trace code.
/// </summary>
internal class TransactionCreatedTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "TransactionCreatedTraceRecord"; } }
private static TransactionCreatedTraceRecord s_record = new TransactionCreatedTraceRecord();
private TransactionTraceIdentifier _txTraceId;
private string _traceSource;
internal static void Trace(string traceSource, TransactionTraceIdentifier txTraceId)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._txTraceId = txTraceId;
DiagnosticTrace.TraceEvent(TraceEventType.Information,
TransactionsTraceCode.TransactionCreated,
SR.TraceTransactionCreated,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
TraceHelper.WriteTxId(xml, _txTraceId);
}
}
/// <summary>
/// Trace record for the TransactionPromoted trace code.
/// </summary>
internal class TransactionPromotedTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "TransactionPromotedTraceRecord"; } }
private static TransactionPromotedTraceRecord s_record = new TransactionPromotedTraceRecord();
private TransactionTraceIdentifier _localTxTraceId;
private TransactionTraceIdentifier _distTxTraceId;
private string _traceSource;
internal static void Trace(string traceSource, TransactionTraceIdentifier localTxTraceId, TransactionTraceIdentifier distTxTraceId)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._localTxTraceId = localTxTraceId;
s_record._distTxTraceId = distTxTraceId;
DiagnosticTrace.TraceEvent(TraceEventType.Information,
TransactionsTraceCode.TransactionPromoted,
SR.TraceTransactionPromoted,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
xml.WriteStartElement("LightweightTransaction");
TraceHelper.WriteTxId(xml, _localTxTraceId);
xml.WriteEndElement();
xml.WriteStartElement("PromotedTransaction");
TraceHelper.WriteTxId(xml, _distTxTraceId);
xml.WriteEndElement();
}
}
/// <summary>
/// Trace record for the Enlistment trace code.
/// </summary>
internal class EnlistmentTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "EnlistmentTraceRecord"; } }
private static EnlistmentTraceRecord s_record = new EnlistmentTraceRecord();
private EnlistmentTraceIdentifier _enTraceId;
private EnlistmentType _enType;
private EnlistmentOptions _enOptions;
private string _traceSource;
internal static void Trace(string traceSource, EnlistmentTraceIdentifier enTraceId, EnlistmentType enType,
EnlistmentOptions enOptions)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._enTraceId = enTraceId;
s_record._enType = enType;
s_record._enOptions = enOptions;
DiagnosticTrace.TraceEvent(TraceEventType.Information,
TransactionsTraceCode.Enlistment,
SR.TraceEnlistment,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
TraceHelper.WriteEnId(xml, _enTraceId);
xml.WriteElementString("EnlistmentType", _enType.ToString());
xml.WriteElementString("EnlistmentOptions", _enOptions.ToString());
}
}
/// <summary>
/// Trace record for the EnlistmentNotificationCall trace code.
/// </summary>
internal class EnlistmentNotificationCallTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "EnlistmentNotificationCallTraceRecord"; } }
private static EnlistmentNotificationCallTraceRecord s_record = new EnlistmentNotificationCallTraceRecord();
private EnlistmentTraceIdentifier _enTraceId;
private NotificationCall _notCall;
private string _traceSource;
internal static void Trace(string traceSource, EnlistmentTraceIdentifier enTraceId, NotificationCall notCall)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._enTraceId = enTraceId;
s_record._notCall = notCall;
DiagnosticTrace.TraceEvent(TraceEventType.Verbose,
TransactionsTraceCode.EnlistmentNotificationCall,
SR.TraceEnlistmentNotificationCall,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
TraceHelper.WriteEnId(xml, _enTraceId);
xml.WriteElementString("NotificationCall", _notCall.ToString());
}
}
/// <summary>
/// Trace record for the EnlistmentCallbackPositive trace code.
/// </summary>
internal class EnlistmentCallbackPositiveTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "EnlistmentCallbackPositiveTraceRecord"; } }
private static EnlistmentCallbackPositiveTraceRecord s_record = new EnlistmentCallbackPositiveTraceRecord();
private EnlistmentTraceIdentifier _enTraceId;
private EnlistmentCallback _callback;
private string _traceSource;
internal static void Trace(string traceSource, EnlistmentTraceIdentifier enTraceId, EnlistmentCallback callback)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._enTraceId = enTraceId;
s_record._callback = callback;
DiagnosticTrace.TraceEvent(TraceEventType.Verbose,
TransactionsTraceCode.EnlistmentCallbackPositive,
SR.TraceEnlistmentCallbackPositive,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
TraceHelper.WriteEnId(xml, _enTraceId);
xml.WriteElementString("EnlistmentCallback", _callback.ToString());
}
}
/// <summary>
/// Trace record for the EnlistmentCallbackNegative trace code.
/// </summary>
internal class EnlistmentCallbackNegativeTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "EnlistmentCallbackNegativeTraceRecord"; } }
private static EnlistmentCallbackNegativeTraceRecord s_record = new EnlistmentCallbackNegativeTraceRecord();
private EnlistmentTraceIdentifier _enTraceId;
private EnlistmentCallback _callback;
private string _traceSource;
internal static void Trace(string traceSource, EnlistmentTraceIdentifier enTraceId, EnlistmentCallback callback)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._enTraceId = enTraceId;
s_record._callback = callback;
DiagnosticTrace.TraceEvent(TraceEventType.Warning,
TransactionsTraceCode.EnlistmentCallbackNegative,
SR.TraceEnlistmentCallbackNegative,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
TraceHelper.WriteEnId(xml, _enTraceId);
xml.WriteElementString("EnlistmentCallback", _callback.ToString());
}
}
#endregion
#region two
/// <summary>
/// Trace record for the TransactionCommitCalled trace code.
/// </summary>
internal class TransactionCommitCalledTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "TransactionCommitCalledTraceRecord"; } }
private static TransactionCommitCalledTraceRecord s_record = new TransactionCommitCalledTraceRecord();
private TransactionTraceIdentifier _txTraceId;
private string _traceSource;
internal static void Trace(string traceSource, TransactionTraceIdentifier txTraceId)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._txTraceId = txTraceId;
DiagnosticTrace.TraceEvent(TraceEventType.Verbose,
TransactionsTraceCode.TransactionCommitCalled,
SR.TraceTransactionCommitCalled,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
TraceHelper.WriteTxId(xml, _txTraceId);
}
}
/// <summary>
/// Trace record for the TransactionRollbackCalled trace code.
/// </summary>
internal class TransactionRollbackCalledTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "TransactionRollbackCalledTraceRecord"; } }
private static TransactionRollbackCalledTraceRecord s_record = new TransactionRollbackCalledTraceRecord();
private TransactionTraceIdentifier _txTraceId;
private string _traceSource;
internal static void Trace(string traceSource, TransactionTraceIdentifier txTraceId)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._txTraceId = txTraceId;
DiagnosticTrace.TraceEvent(TraceEventType.Warning,
TransactionsTraceCode.TransactionRollbackCalled,
SR.TraceTransactionRollbackCalled,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
TraceHelper.WriteTxId(xml, _txTraceId);
}
}
/// <summary>
/// Trace record for the TransactionCommitted trace code.
/// </summary>
internal class TransactionCommittedTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "TransactionCommittedTraceRecord"; } }
private static TransactionCommittedTraceRecord s_record = new TransactionCommittedTraceRecord();
private TransactionTraceIdentifier _txTraceId;
private string _traceSource;
internal static void Trace(string traceSource, TransactionTraceIdentifier txTraceId)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._txTraceId = txTraceId;
DiagnosticTrace.TraceEvent(TraceEventType.Verbose,
TransactionsTraceCode.TransactionCommitted,
SR.TraceTransactionCommitted,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
TraceHelper.WriteTxId(xml, _txTraceId);
}
}
/// <summary>
/// Trace record for the TransactionAborted trace code.
/// </summary>
internal class TransactionAbortedTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "TransactionAbortedTraceRecord"; } }
private static TransactionAbortedTraceRecord s_record = new TransactionAbortedTraceRecord();
private TransactionTraceIdentifier _txTraceId;
private string _traceSource;
internal static void Trace(string traceSource, TransactionTraceIdentifier txTraceId)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._txTraceId = txTraceId;
DiagnosticTrace.TraceEvent(TraceEventType.Warning,
TransactionsTraceCode.TransactionAborted,
SR.TraceTransactionAborted,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
TraceHelper.WriteTxId(xml, _txTraceId);
}
}
/// <summary>
/// Trace record for the TransactionInDoubt trace code.
/// </summary>
internal class TransactionInDoubtTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "TransactionInDoubtTraceRecord"; } }
private static TransactionInDoubtTraceRecord s_record = new TransactionInDoubtTraceRecord();
private TransactionTraceIdentifier _txTraceId;
private string _traceSource;
internal static void Trace(string traceSource, TransactionTraceIdentifier txTraceId)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._txTraceId = txTraceId;
DiagnosticTrace.TraceEvent(TraceEventType.Warning,
TransactionsTraceCode.TransactionInDoubt,
SR.TraceTransactionInDoubt,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
TraceHelper.WriteTxId(xml, _txTraceId);
}
}
/// <summary>
/// Trace record for the TransactionScopeCreated trace code.
/// </summary>
internal class TransactionScopeCreatedTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "TransactionScopeCreatedTraceRecord"; } }
private static TransactionScopeCreatedTraceRecord s_record = new TransactionScopeCreatedTraceRecord();
private TransactionTraceIdentifier _txTraceId;
private TransactionScopeResult _txScopeResult;
private string _traceSource;
internal static void Trace(string traceSource, TransactionTraceIdentifier txTraceId, TransactionScopeResult txScopeResult)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._txTraceId = txTraceId;
s_record._txScopeResult = txScopeResult;
DiagnosticTrace.TraceEvent(TraceEventType.Information,
TransactionsTraceCode.TransactionScopeCreated,
SR.TraceTransactionScopeCreated,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
TraceHelper.WriteTxId(xml, _txTraceId);
xml.WriteElementString("TransactionScopeResult", _txScopeResult.ToString());
}
}
/// <summary>
/// Trace record for the TransactionScopeDisposed trace code.
/// </summary>
internal class TransactionScopeDisposedTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "TransactionScopeDisposedTraceRecord"; } }
private static TransactionScopeDisposedTraceRecord s_record = new TransactionScopeDisposedTraceRecord();
private TransactionTraceIdentifier _txTraceId;
private string _traceSource;
internal static void Trace(string traceSource, TransactionTraceIdentifier txTraceId)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._txTraceId = txTraceId;
DiagnosticTrace.TraceEvent(TraceEventType.Information,
TransactionsTraceCode.TransactionScopeDisposed,
SR.TraceTransactionScopeDisposed,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
TraceHelper.WriteTxId(xml, _txTraceId);
}
}
/// <summary>
/// Trace record for the TransactionScopeIncomplete trace code.
/// </summary>
internal class TransactionScopeIncompleteTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "TransactionScopeIncompleteTraceRecord"; } }
private static TransactionScopeIncompleteTraceRecord s_record = new TransactionScopeIncompleteTraceRecord();
private TransactionTraceIdentifier _txTraceId;
private string _traceSource;
internal static void Trace(string traceSource, TransactionTraceIdentifier txTraceId)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._txTraceId = txTraceId;
DiagnosticTrace.TraceEvent(TraceEventType.Warning,
TransactionsTraceCode.TransactionScopeIncomplete,
SR.TraceTransactionScopeIncomplete,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
TraceHelper.WriteTxId(xml, _txTraceId);
}
}
/// <summary>
/// Trace record for the TransactionScopeNestedIncorrectly trace code.
/// </summary>
internal class TransactionScopeNestedIncorrectlyTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "TransactionScopeNestedIncorrectlyTraceRecord"; } }
private static TransactionScopeNestedIncorrectlyTraceRecord s_record = new TransactionScopeNestedIncorrectlyTraceRecord();
private TransactionTraceIdentifier _txTraceId;
private string _traceSource;
internal static void Trace(string traceSource, TransactionTraceIdentifier txTraceId)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._txTraceId = txTraceId;
DiagnosticTrace.TraceEvent(TraceEventType.Warning,
TransactionsTraceCode.TransactionScopeNestedIncorrectly,
SR.TraceTransactionScopeNestedIncorrectly,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
TraceHelper.WriteTxId(xml, _txTraceId);
}
}
/// <summary>
/// Trace record for the TransactionScopeCurrentChanged trace code.
/// </summary>
internal class TransactionScopeCurrentChangedTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "TransactionScopeCurrentChangedTraceRecord"; } }
private static TransactionScopeCurrentChangedTraceRecord s_record = new TransactionScopeCurrentChangedTraceRecord();
private TransactionTraceIdentifier _scopeTxTraceId;
private TransactionTraceIdentifier _currentTxTraceId;
private string _traceSource;
internal static void Trace(string traceSource, TransactionTraceIdentifier scopeTxTraceId, TransactionTraceIdentifier currentTxTraceId)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._scopeTxTraceId = scopeTxTraceId;
s_record._currentTxTraceId = currentTxTraceId;
DiagnosticTrace.TraceEvent(TraceEventType.Warning,
TransactionsTraceCode.TransactionScopeCurrentTransactionChanged,
SR.TraceTransactionScopeCurrentTransactionChanged,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
TraceHelper.WriteTxId(xml, _scopeTxTraceId);
TraceHelper.WriteTxId(xml, _currentTxTraceId);
}
}
/// <summary>
/// Trace record for the TransactionScopeTimeoutTraceRecord trace code.
/// </summary>
internal class TransactionScopeTimeoutTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "TransactionScopeTimeoutTraceRecord"; } }
private static TransactionScopeTimeoutTraceRecord s_record = new TransactionScopeTimeoutTraceRecord();
private TransactionTraceIdentifier _txTraceId;
private string _traceSource;
internal static void Trace(string traceSource, TransactionTraceIdentifier txTraceId)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._txTraceId = txTraceId;
DiagnosticTrace.TraceEvent(TraceEventType.Warning,
TransactionsTraceCode.TransactionScopeTimeout,
SR.TraceTransactionScopeTimeout,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
TraceHelper.WriteTxId(xml, _txTraceId);
}
}
/// <summary>
/// Trace record for the TransactionTimeoutTraceRecord trace code.
/// </summary>
internal class TransactionTimeoutTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "TransactionTimeoutTraceRecord"; } }
private static TransactionTimeoutTraceRecord s_record = new TransactionTimeoutTraceRecord();
private TransactionTraceIdentifier _txTraceId;
private string _traceSource;
internal static void Trace(string traceSource, TransactionTraceIdentifier txTraceId)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._txTraceId = txTraceId;
DiagnosticTrace.TraceEvent(TraceEventType.Warning,
TransactionsTraceCode.TransactionTimeout,
SR.TraceTransactionTimeout,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
TraceHelper.WriteTxId(xml, _txTraceId);
}
}
/// <summary>
/// Trace record for the DependentCloneCreatedTraceRecord trace code.
/// </summary>
internal class DependentCloneCreatedTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "DependentCloneCreatedTraceRecord"; } }
private static DependentCloneCreatedTraceRecord s_record = new DependentCloneCreatedTraceRecord();
private TransactionTraceIdentifier _txTraceId;
private DependentCloneOption _option;
private string _traceSource;
internal static void Trace(string traceSource, TransactionTraceIdentifier txTraceId, DependentCloneOption option)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._txTraceId = txTraceId;
s_record._option = option;
DiagnosticTrace.TraceEvent(TraceEventType.Information,
TransactionsTraceCode.DependentCloneCreated,
SR.TraceDependentCloneCreated,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
TraceHelper.WriteTxId(xml, _txTraceId);
xml.WriteElementString("DependentCloneOption", _option.ToString());
}
}
/// <summary>
/// Trace record for the DependentCloneComplete trace code.
/// </summary>
internal class DependentCloneCompleteTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "DependentCloneCompleteTraceRecord"; } }
private static DependentCloneCompleteTraceRecord s_record = new DependentCloneCompleteTraceRecord();
private TransactionTraceIdentifier _txTraceId;
private string _traceSource;
internal static void Trace(string traceSource, TransactionTraceIdentifier txTraceId)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._txTraceId = txTraceId;
DiagnosticTrace.TraceEvent(TraceEventType.Information,
TransactionsTraceCode.DependentCloneComplete,
SR.TraceDependentCloneComplete,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
TraceHelper.WriteTxId(xml, _txTraceId);
}
}
/// <summary>
/// Trace record for the CloneCreated trace code.
/// </summary>
internal class CloneCreatedTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "CloneCreatedTraceRecord"; } }
private static CloneCreatedTraceRecord s_record = new CloneCreatedTraceRecord();
private TransactionTraceIdentifier _txTraceId;
private string _traceSource;
internal static void Trace(string traceSource, TransactionTraceIdentifier txTraceId)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._txTraceId = txTraceId;
DiagnosticTrace.TraceEvent(TraceEventType.Verbose,
TransactionsTraceCode.CloneCreated,
SR.TraceCloneCreated,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
TraceHelper.WriteTxId(xml, _txTraceId);
}
}
#endregion
#region three
/// <summary>
/// Trace record for the RecoveryComplete trace code.
/// </summary>
internal class RecoveryCompleteTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "RecoveryCompleteTraceRecord"; } }
private static RecoveryCompleteTraceRecord s_record = new RecoveryCompleteTraceRecord();
private Guid _rmId;
private string _traceSource;
internal static void Trace(string traceSource, Guid rmId)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._rmId = rmId;
DiagnosticTrace.TraceEvent(TraceEventType.Information,
TransactionsTraceCode.RecoveryComplete,
SR.TraceRecoveryComplete,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
xml.WriteElementString("ResourceManagerId", _rmId.ToString());
}
}
/// <summary>
/// Trace record for the Reenlist trace code.
/// </summary>
internal class ReenlistTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "ReenlistTraceRecord"; } }
private static ReenlistTraceRecord s_record = new ReenlistTraceRecord();
private Guid _rmId;
private string _traceSource;
internal static void Trace(string traceSource, Guid rmId)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._rmId = rmId;
DiagnosticTrace.TraceEvent(TraceEventType.Information,
TransactionsTraceCode.Reenlist,
SR.TraceReenlist,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
xml.WriteElementString("ResourceManagerId", _rmId.ToString());
}
}
/// <summary>
/// </summary>
internal class DistributedTransactionManagerCreatedTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "TransactionManagerCreatedTraceRecord"; } }
private static DistributedTransactionManagerCreatedTraceRecord s_record = new DistributedTransactionManagerCreatedTraceRecord();
private Type _tmType;
private string _nodeName;
private string _traceSource;
internal static void Trace(string traceSource, Type tmType, string nodeName)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._tmType = tmType;
s_record._nodeName = nodeName;
DiagnosticTrace.TraceEvent(TraceEventType.Verbose,
TransactionsTraceCode.TransactionManagerCreated,
SR.TraceTransactionManagerCreated,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
xml.WriteElementString("TransactionManagerType", _tmType.ToString());
xml.WriteStartElement("TransactionManagerProperties");
xml.WriteElementString("DistributedTransactionManagerName", _nodeName);
xml.WriteEndElement();
}
}
#endregion
#region four
/// <summary>
/// Trace record for the TransactionSerialized trace code.
/// </summary>
internal class TransactionSerializedTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "TransactionSerializedTraceRecord"; } }
private static TransactionSerializedTraceRecord s_record = new TransactionSerializedTraceRecord();
private TransactionTraceIdentifier _txTraceId;
private string _traceSource;
internal static void Trace(string traceSource, TransactionTraceIdentifier txTraceId)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._txTraceId = txTraceId;
DiagnosticTrace.TraceEvent(TraceEventType.Information,
TransactionsTraceCode.TransactionSerialized,
SR.TraceTransactionSerialized,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
TraceHelper.WriteTxId(xml, _txTraceId);
}
}
/// <summary>
/// Trace record for the TransactionDeserialized trace code.
/// </summary>
internal class TransactionDeserializedTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "TransactionDeserializedTraceRecord"; } }
private static TransactionDeserializedTraceRecord s_record = new TransactionDeserializedTraceRecord();
private TransactionTraceIdentifier _txTraceId;
private string _traceSource;
internal static void Trace(string traceSource, TransactionTraceIdentifier txTraceId)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._txTraceId = txTraceId;
DiagnosticTrace.TraceEvent(TraceEventType.Verbose,
TransactionsTraceCode.TransactionDeserialized,
SR.TraceTransactionDeserialized,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
TraceHelper.WriteTxId(xml, _txTraceId);
}
}
/// <summary>
/// Trace record for the TransactionException trace code.
/// </summary>
internal class TransactionExceptionTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "TransactionExceptionTraceRecord"; } }
private static TransactionExceptionTraceRecord s_record = new TransactionExceptionTraceRecord();
private string _exceptionMessage;
private string _traceSource;
internal static void Trace(string traceSource, string exceptionMessage)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._exceptionMessage = exceptionMessage;
DiagnosticTrace.TraceEvent(TraceEventType.Error,
TransactionsTraceCode.TransactionException,
SR.TraceTransactionException,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
xml.WriteElementString("ExceptionMessage", _exceptionMessage);
}
}
internal class DictionaryTraceRecord : TraceRecord
{
private System.Collections.IDictionary _dictionary;
internal DictionaryTraceRecord(System.Collections.IDictionary dictionary)
{
_dictionary = dictionary;
}
internal override string EventId { get { return TraceRecord.EventIdBase + "Dictionary" + TraceRecord.NamespaceSuffix; } }
internal override void WriteTo(XmlWriter xml)
{
if (_dictionary != null)
{
foreach (object key in _dictionary.Keys)
{
xml.WriteElementString(key.ToString(), _dictionary[key].ToString());
}
}
}
public override string ToString()
{
string retval = null;
if (_dictionary != null)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (object key in _dictionary.Keys)
{
sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "{0}: {1}", key, _dictionary[key].ToString()));
}
}
return retval;
}
}
/// <summary>
/// Trace record for the ExceptionConsumed trace code.
/// </summary>
internal class ExceptionConsumedTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "ExceptionConsumedTraceRecord"; } }
private static ExceptionConsumedTraceRecord s_record = new ExceptionConsumedTraceRecord();
private Exception _exception;
private string _traceSource;
internal static void Trace(string traceSource, Exception exception)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._exception = exception;
DiagnosticTrace.TraceEvent(TraceEventType.Verbose,
TransactionsTraceCode.ExceptionConsumed,
SR.TraceExceptionConsumed,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
xml.WriteElementString("ExceptionMessage", _exception.Message);
xml.WriteElementString("ExceptionStack", _exception.StackTrace);
}
}
/// <summary>
/// Trace record for the InvalidOperationException trace code.
/// </summary>
internal class InvalidOperationExceptionTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "InvalidOperationExceptionTraceRecord"; } }
private static InvalidOperationExceptionTraceRecord s_record = new InvalidOperationExceptionTraceRecord();
private string _exceptionMessage;
private string _traceSource;
internal static void Trace(string traceSource, string exceptionMessage)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._exceptionMessage = exceptionMessage;
DiagnosticTrace.TraceEvent(TraceEventType.Error,
TransactionsTraceCode.InvalidOperationException,
SR.TraceInvalidOperationException,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
xml.WriteElementString("ExceptionMessage", _exceptionMessage);
}
}
/// <summary>
/// Trace record for the InternalError trace code.
/// </summary>
internal class InternalErrorTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "InternalErrorTraceRecord"; } }
private static InternalErrorTraceRecord s_record = new InternalErrorTraceRecord();
private string _exceptionMessage;
private string _traceSource;
internal static void Trace(string traceSource, string exceptionMessage)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._exceptionMessage = exceptionMessage;
DiagnosticTrace.TraceEvent(TraceEventType.Critical,
TransactionsTraceCode.InternalError,
SR.TraceInternalError,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
xml.WriteElementString("ExceptionMessage", _exceptionMessage);
}
}
/// <summary>
/// Trace record for the MethodEntered trace code.
/// </summary>
internal class MethodEnteredTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "MethodEnteredTraceRecord"; } }
private static MethodEnteredTraceRecord s_record = new MethodEnteredTraceRecord();
private string _methodName;
private string _traceSource;
internal static void Trace(string traceSource, string methodName)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._methodName = methodName;
DiagnosticTrace.TraceEvent(TraceEventType.Verbose,
TransactionsTraceCode.MethodEntered,
SR.TraceMethodEntered,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
xml.WriteElementString("MethodName", _methodName);
}
}
/// <summary>
/// Trace record for the MethodExited trace code.
/// </summary>
internal class MethodExitedTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "MethodExitedTraceRecord"; } }
private static MethodExitedTraceRecord s_record = new MethodExitedTraceRecord();
private string _methodName;
private string _traceSource;
internal static void Trace(string traceSource, string methodName)
{
lock (s_record)
{
s_record._traceSource = traceSource;
s_record._methodName = methodName;
DiagnosticTrace.TraceEvent(TraceEventType.Verbose,
TransactionsTraceCode.MethodExited,
SR.TraceMethodExited,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
xml.WriteElementString("MethodName", _methodName);
}
}
/// <summary>
/// Trace record for the MethodEntered trace code.
/// </summary>
internal class ConfiguredDefaultTimeoutAdjustedTraceRecord : TraceRecord
{
/// <summary>
/// Defines object layout.
/// </summary>
internal override string EventId { get { return EventIdBase + "ConfiguredDefaultTimeoutAdjustedTraceRecord"; } }
private static ConfiguredDefaultTimeoutAdjustedTraceRecord s_record = new ConfiguredDefaultTimeoutAdjustedTraceRecord();
private string _traceSource;
internal static void Trace(string traceSource)
{
lock (s_record)
{
s_record._traceSource = traceSource;
DiagnosticTrace.TraceEvent(TraceEventType.Warning,
TransactionsTraceCode.ConfiguredDefaultTimeoutAdjusted,
SR.TraceConfiguredDefaultTimeoutAdjusted,
s_record);
}
}
internal override void WriteTo(XmlWriter xml)
{
TraceHelper.WriteTraceSource(xml, _traceSource);
}
}
#endregion
}
| |
// Copyright (c) 2021 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
using Alachisoft.NCache.Runtime.Serialization;
using Alachisoft.NCache.Runtime.Serialization.IO;
using System.Diagnostics;
namespace Alachisoft.NCache.Common.Stats
{
/// <summary>
/// Class that is useful in capturing statistics. It uses High performnace counters for
/// the measurement of the time.
/// </summary>
public class HPTimeStats :ICompactSerializable
{
/// <summary> Total number of samples collected for the statistics. </summary>
private long _runCount;
/// <summary> Timestamp for the begining of a sample. </summary>
private long _lastStart;
/// <summary> Timestamp for the end of a sample. </summary>
private long _lastStop;
/// <summary> Total time spent in sampling, i.e., acrued sample time. </summary>
private double _totalTime;
/// <summary> Best time interval mesaured during sampling. </summary>
private double _bestTime;
/// <summary> Worst time interval mesaured during sampling. </summary>
private double _worstTime;
/// <summary> Avg. time interval mesaured during sampling. </summary>
private double _avgTime;
/// <summary> Total number of samples collected for the statistics. </summary>
private long _totalRunCount;
private float _avgCummulativeOperations;
private double _worstThreshHole = double.MaxValue;
private long _worstOccurance;
private static double _frequency;
static HPTimeStats()
{
long freq = 0;
freq = Stopwatch.Frequency;
_frequency = (double)freq / (double)1000;
}
/// <summary>
/// Constructor
/// </summary>
public HPTimeStats()
{
Reset();
}
/// <summary>
/// Constructor
/// </summary>
public HPTimeStats(double worstThreshHoleValue)
{
Reset();
_worstThreshHole = worstThreshHoleValue;
}
/// <summary>
/// Returns the total numbre of runs in the statistics capture.
/// </summary>
public long Runs
{
get { lock (this) { return _runCount; } }
set { lock (this) _runCount = value; }
}
/// <summary>
/// Gets or sets the threshhold value for worst case occurance count.
/// </summary>
public double WorstThreshHoldValue
{
get { return _worstThreshHole; }
set { _worstThreshHole = value; }
}
/// <summary>
/// Gets the number of total worst cases occurred.
/// </summary>
public long TotalWorstCases
{
get { return _worstOccurance; }
}
/// <summary>
/// Returns the total time iterval spent in sampling
/// </summary>
public double Total
{
get { lock (this) { return _totalTime; } }
}
/// <summary>
/// Returns the time interval for the last sample
/// </summary>
public double Current
{
get { lock (this) { return (double)(_lastStop - _lastStart)/(double)_frequency; } }
}
/// <summary>
/// Returns the best time interval mesaured during sampling
/// </summary>
public double Best
{
get { lock (this) { return _bestTime; } }
}
/// <summary>
/// Returns the avg. time interval mesaured during sampling
/// </summary>
public double Avg
{
get { lock (this) { return _avgTime; } }
}
public float AvgOperations
{
get { lock (this) { return _avgCummulativeOperations; } }
}
/// <summary>
/// Returns the worst time interval mesaured during sampling
/// </summary>
public double Worst
{
get { lock (this) { return _worstTime; } }
}
/// <summary>
/// Resets the statistics collected so far.
/// </summary>
public void Reset()
{
_runCount = 0;
_totalTime = _bestTime = _worstTime = _worstOccurance = 0;
_avgTime = 0;
_avgCummulativeOperations = 0;
}
/// <summary>
/// Timestamps the start of a sampling interval.
/// </summary>
public void BeginSample()
{
_lastStart = Stopwatch.GetTimestamp(); // POTeam DateTime.UtcNow.Ticks;
}
/// <summary>
/// Timestamps the end of interval and calculates the sample time
/// </summary>
public void EndSample()
{
lock (this)
{
_lastStop = Stopwatch.GetTimestamp(); // POTeam DateTime.UtcNow.Ticks;
AddSampleTime(Current);
}
}
/// <summary>
/// Timestamps the end of interval and calculates the sample time
/// </summary>
public void EndSample(int runcount)
{
lock (this)
{
_lastStop = Stopwatch.GetTimestamp();
AddSampleTime(Current, runcount);
}
}
/// <summary>
/// Adds a specified sample time to the statistics and updates the run count
/// </summary>
/// <param name="time">sample time in milliseconds.</param>
public void AddSampleTime(double time)
{
lock (this)
{
_runCount++;
_totalRunCount++;
if (_runCount == 1)
{
_avgTime = _totalTime = _bestTime = _worstTime = time;
}
else
{
_totalTime += time;
if (time < _bestTime) _bestTime = time;
if (time > _worstTime) _worstTime = time;
if (time > _worstThreshHole) _worstOccurance += 1;
_avgTime = (double)_totalTime / (double)_runCount;
}
if (_totalTime < 1000)
_avgCummulativeOperations = _runCount;
else
_avgCummulativeOperations = (float)_runCount * 1000 / (float)_totalTime;
}
}
/// <summary>
/// Adds a specified sample time to the statistics and updates the run count
/// </summary>
/// <param name="time">sample time in milliseconds.</param>
public void AddSampleTime(double time, int runcount)
{
lock (this)
{
_runCount += runcount;
_totalRunCount += runcount;
if (_runCount == 1)
{
_avgTime = _totalTime = _bestTime = _worstTime = time;
}
else
{
_totalTime += time;
if (time < _bestTime) _bestTime = time;
if (time > _worstTime) _worstTime = time;
if (time > _worstThreshHole) _worstOccurance += 1;
_avgTime = (float)_totalTime / (float)_runCount;
}
if (_totalTime < 1000)
_avgCummulativeOperations = _runCount;
else
_avgCummulativeOperations = (float)_runCount * 1000 / (float)_totalTime;
}
}
/// <summary>
/// Gets the total run count for the samples
/// </summary>
public long TotalRunCount
{
get { return _totalRunCount; }
}
/// <summary>
/// Override converts to string equivalent.
/// </summary>
/// <returns></returns>
public override string ToString()
{
lock (this)
{
string retval = "[Runs: " + _runCount + ", ";
retval += "Best(ms): " + _bestTime + ", ";
retval += "Avg.(ms): " + _avgTime + ", ";
retval += "Worst(ms): " + _worstTime + ", ";
retval += "WorstThreshHole(ms): " + _worstThreshHole + ", ";
retval += "Worst cases: " + _worstOccurance + "]";
return retval;
}
}
#region ICompactSerializable Members
public void Deserialize(CompactReader reader)
{
_runCount = reader.ReadInt64();
_avgTime = reader.ReadDouble();
_bestTime = reader.ReadDouble();
_lastStart = reader.ReadInt64();
_lastStop = reader.ReadInt64();
_worstThreshHole = reader.ReadDouble();
_worstTime = reader.ReadDouble();
_totalRunCount = reader.ReadInt64();
_totalTime = reader.ReadDouble();
_worstOccurance = reader.ReadInt64();
_avgCummulativeOperations = reader.ReadSingle();
}
public void Serialize(CompactWriter writer)
{
writer.Write(_runCount);
writer.Write(_avgTime);
writer.Write(_bestTime);
writer.Write(_lastStart);
writer.Write(_lastStop);
writer.Write(_worstThreshHole);
writer.Write(_worstTime);
writer.Write(_totalRunCount);
writer.Write(_totalTime);
writer.Write(_worstOccurance);
writer.Write(_avgCummulativeOperations);
}
#endregion
}
}
| |
using ClosedXML.Extensions;
using System;
using System.Diagnostics;
namespace ClosedXML.Excel
{
internal struct XLAddress : IXLAddress, IEquatable<XLAddress>
{
#region Static
/// <summary>
/// Create address without worksheet. For calculation only!
/// </summary>
/// <param name="cellAddressString"></param>
/// <returns></returns>
public static XLAddress Create(string cellAddressString)
{
return Create(null, cellAddressString);
}
public static XLAddress Create(XLWorksheet worksheet, string cellAddressString)
{
var fixedColumn = cellAddressString[0] == '$';
Int32 startPos;
if (fixedColumn)
{
startPos = 1;
}
else
{
startPos = 0;
}
int rowPos = startPos;
while (cellAddressString[rowPos] > '9')
{
rowPos++;
}
var fixedRow = cellAddressString[rowPos] == '$';
string columnLetter;
int rowNumber;
if (fixedRow)
{
if (fixedColumn)
{
columnLetter = cellAddressString.Substring(startPos, rowPos - 1);
}
else
{
columnLetter = cellAddressString.Substring(startPos, rowPos);
}
rowNumber = int.Parse(cellAddressString.Substring(rowPos + 1), XLHelper.NumberStyle, XLHelper.ParseCulture);
}
else
{
if (fixedColumn)
{
columnLetter = cellAddressString.Substring(startPos, rowPos - 1);
}
else
{
columnLetter = cellAddressString.Substring(startPos, rowPos);
}
rowNumber = Int32.Parse(cellAddressString.Substring(rowPos), XLHelper.NumberStyle, XLHelper.ParseCulture);
}
return new XLAddress(worksheet, rowNumber, columnLetter, fixedRow, fixedColumn);
}
#endregion Static
#region Private fields
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private bool _fixedRow;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private bool _fixedColumn;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly int _rowNumber;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly int _columnNumber;
private string _trimmedAddress;
#endregion Private fields
#region Constructors
/// <summary>
/// Initializes a new <see cref = "XLAddress" /> struct using a mixed notation. Attention: without worksheet for calculation only!
/// </summary>
/// <param name = "rowNumber">The row number of the cell address.</param>
/// <param name = "columnLetter">The column letter of the cell address.</param>
/// <param name = "fixedRow"></param>
/// <param name = "fixedColumn"></param>
public XLAddress(int rowNumber, string columnLetter, bool fixedRow, bool fixedColumn)
: this(null, rowNumber, columnLetter, fixedRow, fixedColumn)
{
}
/// <summary>
/// Initializes a new <see cref = "XLAddress" /> struct using a mixed notation.
/// </summary>
/// <param name = "worksheet"></param>
/// <param name = "rowNumber">The row number of the cell address.</param>
/// <param name = "columnLetter">The column letter of the cell address.</param>
/// <param name = "fixedRow"></param>
/// <param name = "fixedColumn"></param>
public XLAddress(XLWorksheet worksheet, int rowNumber, string columnLetter, bool fixedRow, bool fixedColumn)
: this(worksheet, rowNumber, XLHelper.GetColumnNumberFromLetter(columnLetter), fixedRow, fixedColumn)
{
}
/// <summary>
/// Initializes a new <see cref = "XLAddress" /> struct using R1C1 notation. Attention: without worksheet for calculation only!
/// </summary>
/// <param name = "rowNumber">The row number of the cell address.</param>
/// <param name = "columnNumber">The column number of the cell address.</param>
/// <param name = "fixedRow"></param>
/// <param name = "fixedColumn"></param>
public XLAddress(int rowNumber, int columnNumber, bool fixedRow, bool fixedColumn)
: this(null, rowNumber, columnNumber, fixedRow, fixedColumn)
{
}
/// <summary>
/// Initializes a new <see cref = "XLAddress" /> struct using R1C1 notation.
/// </summary>
/// <param name = "worksheet"></param>
/// <param name = "rowNumber">The row number of the cell address.</param>
/// <param name = "columnNumber">The column number of the cell address.</param>
/// <param name = "fixedRow"></param>
/// <param name = "fixedColumn"></param>
public XLAddress(XLWorksheet worksheet, int rowNumber, int columnNumber, bool fixedRow, bool fixedColumn) : this()
{
Worksheet = worksheet;
_rowNumber = rowNumber;
_columnNumber = columnNumber;
_fixedColumn = fixedColumn;
_fixedRow = fixedRow;
}
#endregion Constructors
#region Properties
public XLWorksheet Worksheet { get; internal set; }
IXLWorksheet IXLAddress.Worksheet
{
[DebuggerStepThrough]
get { return Worksheet; }
}
public bool HasWorksheet
{
[DebuggerStepThrough]
get { return Worksheet != null; }
}
public bool FixedRow
{
get { return _fixedRow; }
}
public bool FixedColumn
{
get { return _fixedColumn; }
}
/// <summary>
/// Gets the row number of this address.
/// </summary>
public Int32 RowNumber
{
get { return _rowNumber; }
}
/// <summary>
/// Gets the column number of this address.
/// </summary>
public Int32 ColumnNumber
{
get { return _columnNumber; }
}
/// <summary>
/// Gets the column letter(s) of this address.
/// </summary>
public String ColumnLetter
{
get { return XLHelper.GetColumnLetterFromNumber(_columnNumber); }
}
#endregion Properties
#region Overrides
public override string ToString()
{
String retVal = ColumnLetter;
if (_fixedColumn)
{
retVal = "$" + retVal;
}
if (_fixedRow)
{
retVal += "$";
}
retVal += _rowNumber.ToInvariantString();
return retVal;
}
public string ToString(XLReferenceStyle referenceStyle)
{
return ToString(referenceStyle, false);
}
public string ToString(XLReferenceStyle referenceStyle, bool includeSheet)
{
string address;
if (referenceStyle == XLReferenceStyle.A1)
address = GetTrimmedAddress();
else if (referenceStyle == XLReferenceStyle.R1C1
|| HasWorksheet && Worksheet.Workbook.ReferenceStyle == XLReferenceStyle.R1C1)
address = "R" + _rowNumber.ToInvariantString() + "C" + ColumnNumber.ToInvariantString();
else
address = GetTrimmedAddress();
if (includeSheet)
return String.Concat(
Worksheet.Name.EscapeSheetName(),
'!',
address);
return address;
}
#endregion Overrides
#region Methods
public string GetTrimmedAddress()
{
return _trimmedAddress ?? (_trimmedAddress = ColumnLetter + _rowNumber.ToInvariantString());
}
#endregion Methods
#region Operator Overloads
public static XLAddress operator +(XLAddress left, XLAddress right)
{
return new XLAddress(left.Worksheet,
left.RowNumber + right.RowNumber,
left.ColumnNumber + right.ColumnNumber,
left._fixedRow,
left._fixedColumn);
}
public static XLAddress operator -(XLAddress left, XLAddress right)
{
return new XLAddress(left.Worksheet,
left.RowNumber - right.RowNumber,
left.ColumnNumber - right.ColumnNumber,
left._fixedRow,
left._fixedColumn);
}
public static XLAddress operator +(XLAddress left, Int32 right)
{
return new XLAddress(left.Worksheet,
left.RowNumber + right,
left.ColumnNumber + right,
left._fixedRow,
left._fixedColumn);
}
public static XLAddress operator -(XLAddress left, Int32 right)
{
return new XLAddress(left.Worksheet,
left.RowNumber - right,
left.ColumnNumber - right,
left._fixedRow,
left._fixedColumn);
}
public static Boolean operator ==(XLAddress left, XLAddress right)
{
if (ReferenceEquals(left, right))
{
return true;
}
return !ReferenceEquals(left, null) && left.Equals(right);
}
public static Boolean operator !=(XLAddress left, XLAddress right)
{
return !(left == right);
}
#endregion Operator Overloads
#region Interface Requirements
#region IEqualityComparer<XLCellAddress> Members
public Boolean Equals(IXLAddress x, IXLAddress y)
{
return x == y;
}
public new Boolean Equals(object x, object y)
{
return x == y;
}
#endregion IEqualityComparer<XLCellAddress> Members
#region IEquatable<XLCellAddress> Members
public bool Equals(IXLAddress other)
{
if (other == null)
return false;
return _rowNumber == other.RowNumber &&
_columnNumber == other.ColumnNumber &&
_fixedRow == other.FixedRow &&
_fixedColumn == other.FixedColumn;
}
public bool Equals(XLAddress other)
{
return _rowNumber == other._rowNumber &&
_columnNumber == other._columnNumber &&
_fixedRow == other._fixedRow &&
_fixedColumn == other._fixedColumn;
}
public override Boolean Equals(Object other)
{
return Equals(other as IXLAddress);
}
public override int GetHashCode()
{
var hashCode = 2122234362;
hashCode = hashCode * -1521134295 + _fixedRow.GetHashCode();
hashCode = hashCode * -1521134295 + _fixedColumn.GetHashCode();
hashCode = hashCode * -1521134295 + _rowNumber.GetHashCode();
hashCode = hashCode * -1521134295 + _columnNumber.GetHashCode();
return hashCode;
}
public int GetHashCode(IXLAddress obj)
{
return ((XLAddress)obj).GetHashCode();
}
#endregion IEquatable<XLCellAddress> Members
#endregion Interface Requirements
public String ToStringRelative()
{
return ToStringRelative(false);
}
public String ToStringFixed()
{
return ToStringFixed(XLReferenceStyle.Default);
}
public String ToStringRelative(Boolean includeSheet)
{
if (includeSheet)
return String.Concat(
Worksheet.Name.EscapeSheetName(),
'!',
GetTrimmedAddress()
);
return GetTrimmedAddress();
}
internal XLAddress WithoutWorksheet()
{
return new XLAddress(RowNumber, ColumnNumber, FixedRow, FixedColumn);
}
public String ToStringFixed(XLReferenceStyle referenceStyle)
{
return ToStringFixed(referenceStyle, false);
}
public String ToStringFixed(XLReferenceStyle referenceStyle, Boolean includeSheet)
{
String address;
if (referenceStyle == XLReferenceStyle.Default && HasWorksheet)
referenceStyle = Worksheet.Workbook.ReferenceStyle;
if (referenceStyle == XLReferenceStyle.Default)
referenceStyle = XLReferenceStyle.A1;
Debug.Assert(referenceStyle != XLReferenceStyle.Default);
switch (referenceStyle)
{
case XLReferenceStyle.A1:
address = String.Concat('$', ColumnLetter, '$', _rowNumber.ToInvariantString());
break;
case XLReferenceStyle.R1C1:
address = String.Concat('R', _rowNumber.ToInvariantString(), 'C', ColumnNumber);
break;
default:
throw new NotImplementedException();
}
if (includeSheet)
return String.Concat(
Worksheet.Name.EscapeSheetName(),
'!',
address);
return address;
}
public String UniqueId { get { return RowNumber.ToString("0000000") + ColumnNumber.ToString("00000"); } }
public bool IsValid
{
get
{
return 0 < RowNumber && RowNumber <= XLHelper.MaxRowNumber &&
0 < ColumnNumber && ColumnNumber <= XLHelper.MaxColumnNumber;
}
}
}
}
| |
using XPT.Games.Generic.Constants;
using XPT.Games.Generic.Maps;
using XPT.Games.Twinion.Entities;
namespace XPT.Games.Twinion.Maps {
class TwMap14 : TwMap {
public override int MapIndex => 14;
public override int MapID => 0x0601;
protected override int RandomEncounterChance => 10;
protected override int RandomEncounterExtraCount => 2;
private const int DETECTED_DOOR = 1;
private const int KEEPPIT = 2;
private const int TROUGH = 3;
protected override void FnEvent01(TwPlayerServer player, MapEventType type, bool doMsgs) {
ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
protected override void FnEvent02(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "A voice from the shadows whispers, 'Ah, another adventurer seeking to be the Queen's Champion, no doubt.");
ShowText(player, type, doMsgs, "One tip, youngling, there's a magical force that returns most Quest items back to where they came should you accidentally drop them.'");
}
protected override void FnEvent03(TwPlayerServer player, MapEventType type, bool doMsgs) {
TeleportParty(player, type, doMsgs, 6, 1, 40, Direction.West);
}
protected override void FnEvent04(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You step into the hot lava.");
DamXit(player, type, doMsgs);
}
protected override void FnEvent05(TwPlayerServer player, MapEventType type, bool doMsgs) {
FntnPic(player, type, doMsgs);
ShowText(player, type, doMsgs, "The sweet waters of the Fountain of Nectar restore your mana.");
ModifyMana(player, type, doMsgs, 10000);
}
protected override void FnEvent06(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "Pass through this portal to Tipekans.");
TeleportParty(player, type, doMsgs, 7, 1, 32, Direction.East);
}
protected override void FnEvent07(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeTile, KEEPPIT) == 0) {
ShowText(player, type, doMsgs, "The pit isn't as deep as you feared, but you injure your ankle.");
DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs) / 10);
SetFlag(player, type, doMsgs, FlagTypeTile, KEEPPIT, 1);
}
}
protected override void FnEvent08(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, DWARFWIZARD);
ShowText(player, type, doMsgs, "You see a dwarf shaking her head. She turns to you and says, 'The graveyard is very dark. You must rely upon your wits and skills to get you through.");
ShowText(player, type, doMsgs, "Having something that sheds a little light for you wouldn't hurt, either.'");
}
protected override void FnEvent09(TwPlayerServer player, MapEventType type, bool doMsgs) {
if ((HasUsedSkill(player, type, ref doMsgs, DETECT_SKILL) >= 6 || HasUsedSpell(player, type, ref doMsgs, TRUE_SEEING_SPELL) >= 1 || UsedItem(player, type, ref doMsgs, HELMOFWISDOM, HELMOFWISDOM) || UsedItem(player, type, ref doMsgs, VALKYRIESHELM, VALKYRIESHELM) || UsedItem(player, type, ref doMsgs, RINGOFTHIEVES, RINGOFTHIEVES) || UsedItem(player, type, ref doMsgs, CRYSTALBALL, CRYSTALBALL)) || (IsFlagOn(player, type, doMsgs, FlagTypeTile, DETECTED_DOOR))) {
SetFlag(player, type, doMsgs, FlagTypeTile, DETECTED_DOOR, 1);
if (UsedItem(player, type, ref doMsgs, BLUELOCKPICK, BLUELOCKPICK) || UsedItem(player, type, ref doMsgs, HELMOFGUILE, HELMOFGUILE) || HasUsedSkill(player, type, ref doMsgs, LOCKPICK_SKILL) >= 6) {
DoorHere(player, type, doMsgs);
WallClear(player, type, doMsgs);
ShowText(player, type, doMsgs, "You successfully pick the lock.");
}
else {
WallBlock(player, type, doMsgs);
DoorHere(player, type, doMsgs);
ShowText(player, type, doMsgs, "A locked door appears in the wall.");
}
}
else {
WallBlock(player, type, doMsgs);
}
}
protected override void FnEvent0A(TwPlayerServer player, MapEventType type, bool doMsgs) {
TeleportParty(player, type, doMsgs, 6, 1, 13, Direction.East);
}
protected override void FnEvent0B(TwPlayerServer player, MapEventType type, bool doMsgs) {
TeleportParty(player, type, doMsgs, 6, 1, 210, Direction.South);
}
protected override void FnEvent0C(TwPlayerServer player, MapEventType type, bool doMsgs) {
TeleportParty(player, type, doMsgs, 5, 1, 70, Direction.East);
}
protected override void FnEvent0D(TwPlayerServer player, MapEventType type, bool doMsgs) {
TeleportParty(player, type, doMsgs, 6, 1, 72, Direction.North);
}
protected override void FnEvent0E(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetGuild(player, type, doMsgs) == BARBARIAN) {
if (HasItem(player, type, doMsgs, SKELETONKEY)) {
ShowText(player, type, doMsgs, "The room is empty.");
}
else if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.ARMORY_ITEM) == 1) {
GiveItem(player, type, doMsgs, SKELETONKEY);
ShowText(player, type, doMsgs, "You find a key which may open seemingly impassable doors in your race to finish Queen Aeowyn's Map Quest.");
ShowText(player, type, doMsgs, "The key is made of bone and features a skull and crossed arm bones.");
}
else {
GiveItem(player, type, doMsgs, SKELETONKEY);
ShowText(player, type, doMsgs, "Your Guildmaster left you a special key that will give you access to magical armor.");
ShowText(player, type, doMsgs, "The key is made of bone. The grasp is shaped like a skull and the shaft like two crossed, bony arms.");
}
}
else {
ShowText(player, type, doMsgs, "The room is bare.");
}
}
protected override void FnEvent0F(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You walk into a lair.");
if (HasItem(player, type, doMsgs, SCROLLOFDEATH)) {
SetTreasure(player, type, doMsgs, BLUELOCKPICK, SCROLLOFTHESUN, 0, 0, 0, 1000);
}
else {
SetTreasure(player, type, doMsgs, BLUELOCKPICK, SCROLLOFDEATH, CURATIVEELIXIR, 0, 0, 3000);
}
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 1);
AddEncounter(player, type, doMsgs, 02, 25);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 2);
AddEncounter(player, type, doMsgs, 02, 3);
AddEncounter(player, type, doMsgs, 06, 1);
}
else {
AddEncounter(player, type, doMsgs, 01, 2);
AddEncounter(player, type, doMsgs, 02, 2);
AddEncounter(player, type, doMsgs, 03, 3);
AddEncounter(player, type, doMsgs, 04, 4);
AddEncounter(player, type, doMsgs, 05, 27);
}
}
protected override void FnEvent10(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, HALFLINGCLERIC);
ShowText(player, type, doMsgs, "A cleric pulls you aside and whispers, 'It is rumored that there are areas in the dungeon that can be accessed only by certain races or guilds.'");
}
protected override void FnEvent11(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetGuild(player, type, doMsgs) == BARBARIAN) {
ShowText(player, type, doMsgs, "A sign on the door says, 'BARBARIANS ONLY.'");
DoorHere(player, type, doMsgs);
WallClear(player, type, doMsgs);
}
else {
WallBlock(player, type, doMsgs);
}
}
protected override void FnEvent12(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "A sign reads 'This path leads to Lake Despair.'");
TeleportParty(player, type, doMsgs, 5, 1, 16, Direction.North);
}
protected override void FnEvent13(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "The opening of the ground may have affected the stability of the walls.");
WallClear(player, type, doMsgs);
}
protected override void FnEvent14(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "While admiring the plaques you are attacked.");
if (HasItem(player, type, doMsgs, MANARESTORE)) {
SetTreasure(player, type, doMsgs, MANAELIXIR, SHAMANSCROLL, 0, 0, 0, 1500);
}
else {
SetTreasure(player, type, doMsgs, MANARESTORE, SCROLLOFTHESUN, 0, 0, 0, 3000);
}
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 8);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 5);
AddEncounter(player, type, doMsgs, 02, 7);
}
else {
AddEncounter(player, type, doMsgs, 01, 5);
AddEncounter(player, type, doMsgs, 02, 6);
AddEncounter(player, type, doMsgs, 04, 7);
AddEncounter(player, type, doMsgs, 05, 9);
AddEncounter(player, type, doMsgs, 06, 9);
}
}
protected override void FnEvent15(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You see a plaque on the wall. 'Welcome to the Gallery. Our ancient plaques are informative as well as decorative.'");
}
protected override void FnEvent16(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You fall into the Snake Pit and to your death.");
DamXit(player, type, doMsgs);
}
protected override void FnEvent17(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You have entered the Cloister. Enjoy your respite on your way to the Gallery.");
}
protected override void FnEvent18(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You are attacked by raptors!");
if (HasItem(player, type, doMsgs, HEALALLPOTION)) {
SetTreasure(player, type, doMsgs, ELIXIROFHEALTH, SCROLLOFPROTECTION, RINGOFTHIEVES, 0, 0, 1500);
}
else {
SetTreasure(player, type, doMsgs, HEALALLPOTION, CURSEDSCROLL, HALOSCROLL, RINGOFTHIEVES, 0, 3000);
}
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 15);
AddEncounter(player, type, doMsgs, 05, 32);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 15);
AddEncounter(player, type, doMsgs, 02, 17);
AddEncounter(player, type, doMsgs, 06, 32);
}
else {
AddEncounter(player, type, doMsgs, 01, 16);
AddEncounter(player, type, doMsgs, 02, 16);
AddEncounter(player, type, doMsgs, 03, 17);
AddEncounter(player, type, doMsgs, 04, 17);
AddEncounter(player, type, doMsgs, 06, 32);
}
}
protected override void FnEvent19(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "Dark Alley awaits the unwary traveler. Step cautiously as you wander through the darkness.");
TeleportParty(player, type, doMsgs, 5, 1, 182, Direction.South);
}
protected override void FnEvent1B(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "To the Vineyard.");
TeleportParty(player, type, doMsgs, 4, 1, 57, Direction.South);
}
protected override void FnEvent1C(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You find a scrap of paper on the floor with a lost and found message: 'Reward offered for the return of a jeweled lockpick to Tipekans.'");
}
protected override void FnEvent1D(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "To the Statuary");
TeleportParty(player, type, doMsgs, 5, 1, 199, Direction.East);
}
protected override void FnEvent1F(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasUsedSkill(player, type, ref doMsgs, DETECT_SKILL) >= 6 || HasUsedSpell(player, type, ref doMsgs, TRUE_SEEING_SPELL) >= 1 || UsedItem(player, type, ref doMsgs, HELMOFWISDOM, HELMOFWISDOM) || UsedItem(player, type, ref doMsgs, VALKYRIESHELM, VALKYRIESHELM) || UsedItem(player, type, ref doMsgs, RINGOFTHIEVES, RINGOFTHIEVES) || UsedItem(player, type, ref doMsgs, CRYSTALBALL, CRYSTALBALL)) {
ShowText(player, type, doMsgs, "A door appears in the wall.");
DoorHere(player, type, doMsgs);
WallClear(player, type, doMsgs);
}
else {
WallBlock(player, type, doMsgs);
}
}
protected override void FnEvent20(TwPlayerServer player, MapEventType type, bool doMsgs) {
TeleportParty(player, type, doMsgs, 5, 1, 8, Direction.South);
ShowText(player, type, doMsgs, "To the Vault");
}
protected override void FnEvent21(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "Some of the walls appear to have been reconstructed.");
}
protected override void FnEvent22(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetRace(player, type, doMsgs) == HUMAN) {
ShowText(player, type, doMsgs, "The message on the plaque says, 'Use Tyndil's payment first.'");
}
else {
ShowText(player, type, doMsgs, "The plaque is worn and unreadable.");
}
}
protected override void FnEvent23(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetRace(player, type, doMsgs) == DWARF) {
ShowText(player, type, doMsgs, "The message on the plaque says, 'Save your Coral for last.'");
}
else {
ShowText(player, type, doMsgs, "The plaque is cracked down the center.");
}
}
protected override void FnEvent24(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetRace(player, type, doMsgs) == HALFLING) {
ShowText(player, type, doMsgs, "The message on the plaque says, 'Use your Ebony before your Opal.'");
}
else {
ShowText(player, type, doMsgs, "You cannot read the plaque.");
}
}
protected override void FnEvent25(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "The eerie sounds coming from the Graveyard make you wonder if you should step through this teleport.");
TeleportParty(player, type, doMsgs, 5, 3, 15, Direction.West);
}
protected override void FnEvent26(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "Through this teleport you will find the Breezeway.");
TeleportParty(player, type, doMsgs, 4, 1, 128, Direction.North);
}
protected override void FnEvent27(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasItem(player, type, doMsgs, RUBYLOCKPICK)) {
if (GetPartyCount(player, type, doMsgs) == 1) {
ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
else {
SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
ShowText(player, type, doMsgs, "'Alone I said! It took me a long time to tunnel through this wall and it's only large enough for one!'");
}
}
else {
SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
ShowText(player, type, doMsgs, "Smirk grabs you by the collar before you can sneak through the door. 'Have you no sense? Return when you have the item I desire!'");
}
}
protected override void FnEvent28(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetRace(player, type, doMsgs) == TROLL) {
ShowText(player, type, doMsgs, "The message on the plaque says, 'Don't give up your Pearl until last.'");
}
else {
ShowText(player, type, doMsgs, "This plaque appears chipped.");
}
}
protected override void FnEvent29(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetGuild(player, type, doMsgs) == RANGER) {
if (HasItem(player, type, doMsgs, SKELETONKEY)) {
ShowText(player, type, doMsgs, "The room is empty.");
}
else if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.ARMORY_ITEM) == 1) {
GiveItem(player, type, doMsgs, SKELETONKEY);
ShowText(player, type, doMsgs, "You find a key which may open seemingly impassable doors in your race to finish Queen Aeowyn's Map Quest.");
ShowText(player, type, doMsgs, "The key is made of bone and features a skull and crossed arm bones.");
}
else {
GiveItem(player, type, doMsgs, SKELETONKEY);
ShowText(player, type, doMsgs, "Your Guildmaster left you a special key that will give you access to magical armor.");
ShowText(player, type, doMsgs, "The key is made of bone. The grasp is shaped like a skull and the shaft like two crossed, bony arms.");
}
}
else {
ShowText(player, type, doMsgs, "The room is bare.");
}
}
protected override void FnEvent2A(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetGuild(player, type, doMsgs) == RANGER) {
ShowText(player, type, doMsgs, "A sign on the door says, 'RANGERS ONLY.'");
DoorHere(player, type, doMsgs);
WallClear(player, type, doMsgs);
}
else {
WallBlock(player, type, doMsgs);
}
}
protected override void FnEvent2B(TwPlayerServer player, MapEventType type, bool doMsgs) {
FntnPic(player, type, doMsgs);
if (GetGuild(player, type, doMsgs) == WIZARD) {
if (GetSkill(player, type, doMsgs, ARCHERY_SKILL) == 0) {
SetSkill(player, type, doMsgs, ARCHERY_SKILL, 1);
ShowText(player, type, doMsgs, "Journey's End Fountain endows you with the Archery skill.");
}
else {
Jtxt(player, type, doMsgs);
}
}
else if (GetGuild(player, type, doMsgs) == KNIGHT || GetGuild(player, type, doMsgs) == THIEF || GetGuild(player, type, doMsgs) == RANGER) {
if (GetSkill(player, type, doMsgs, ATHLETICS_SKILL) == 0) {
SetSkill(player, type, doMsgs, ATHLETICS_SKILL, 1);
ShowText(player, type, doMsgs, "Journey's End Fountain endows you with the Athletics skill.");
}
else {
Jtxt(player, type, doMsgs);
}
}
else if (GetGuild(player, type, doMsgs) == CLERIC) {
if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.BLESSCLERIC) == 0)) {
GiveSpell(player, type, doMsgs, BLESS_SPELL, 1);
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.BLESSCLERIC, 1);
ShowText(player, type, doMsgs, "Journey's End Fountain endows you with the Bless spell.");
}
else {
Jtxt(player, type, doMsgs);
}
}
else {
ShowText(player, type, doMsgs, "Journey's End Fountain is dry.");
}
}
protected override void FnEvent2C(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, TROLLKNIGHT);
ShowText(player, type, doMsgs, "You meet a Cavalier who says, 'I've heard tell of a special lantern that has proven very helpful in opening a certain door.");
ShowText(player, type, doMsgs, "The door is somewhere in the dark, or so I'm told.'");
}
protected override void FnEvent2D(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (UsedItem(player, type, ref doMsgs, RUBYLOCKPICK, RUBYLOCKPICK)) {
WallClear(player, type, doMsgs);
DoorHere(player, type, doMsgs);
ShowText(player, type, doMsgs, "Smirk waves you inside.");
}
else {
WallBlock(player, type, doMsgs);
ShowText(player, type, doMsgs, "The entrance to Smirk's Emporium is locked.");
}
}
protected override void FnEvent2E(TwPlayerServer player, MapEventType type, bool doMsgs) {
TeleportParty(player, type, doMsgs, 7, 1, 218, Direction.North);
}
protected override void FnEvent2F(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetRace(player, type, doMsgs) == GNOME) {
ShowText(player, type, doMsgs, "The message on the plaque says, 'Use Syrene's payment as your last choice.'");
}
else {
ShowText(player, type, doMsgs, "The plaque is worn and unreadable.");
}
}
protected override void FnEvent30(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeTile, TROUGH) == 0) {
FntnPic(player, type, doMsgs);
ShowText(player, type, doMsgs, "The stagnant waters of the Trough are poisonous!");
SetDebuff(player, type, doMsgs, POISON, 10, GetHealthMax(player, type, doMsgs) / 10);
SetFlag(player, type, doMsgs, FlagTypeTile, TROUGH, 1);
}
}
protected override void FnEvent31(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, HALFLINGCLERIC);
ShowText(player, type, doMsgs, "A monk breaks his silence and whispers, 'Search well, for there are places in the dungeon where your attributes can be enhanced.'");
}
protected override void FnEvent32(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasItem(player, type, doMsgs, LUMINOUSLANTERN)) {
RemoveItem(player, type, doMsgs, LUMINOUSLANTERN);
GiveItem(player, type, doMsgs, SNAKECHARM);
ShowText(player, type, doMsgs, "The Luminous Lantern fades and disappears as you catch a glimpse of a magical talisman.");
}
else {
ShowText(player, type, doMsgs, "The room is too dark for you to see. A portable light would prove most useful here,");
}
}
protected override void FnEvent33(TwPlayerServer player, MapEventType type, bool doMsgs) {
DisablePartyJoining(player, type, doMsgs);
ShowPortrait(player, type, doMsgs, HALFLINGTHIEF);
if (HasItem(player, type, doMsgs, RUBYLOCKPICK)) {
ShowText(player, type, doMsgs, "I see you have brought the lockpick. Continue through the door to the east alone and you will find your promised reward.");
}
else {
ShowText(player, type, doMsgs, "Smirk cautions you not to go beyond this point without the lockpick.");
}
}
protected override void FnEvent34(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetRace(player, type, doMsgs) == ORC) {
ShowText(player, type, doMsgs, "The message on the plaque says, 'If given a choice, use the Opal second.'");
}
else {
ShowText(player, type, doMsgs, "The plaque is cracked down the center.");
}
}
protected override void FnEvent35(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetRace(player, type, doMsgs) == ELF) {
ShowText(player, type, doMsgs, "The message on the plaque says, 'Use your Opal before your Coral.'");
}
else {
ShowText(player, type, doMsgs, "The etchings on the plaque are unintelligible.");
}
}
protected override void FnEvent36(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetRace(player, type, doMsgs) == GREMLIN) {
ShowText(player, type, doMsgs, "The message on the plaque says, 'Use Tyndil's payment third.'");
}
else {
ShowText(player, type, doMsgs, "You see nothing of interest on the plaque.");
}
}
protected override void FnEvent37(TwPlayerServer player, MapEventType type, bool doMsgs) {
TeleportParty(player, type, doMsgs, 6, 1, 161, Direction.West);
}
protected override void FnEvent38(TwPlayerServer player, MapEventType type, bool doMsgs) {
FntnPic(player, type, doMsgs);
ShowText(player, type, doMsgs, "Equestrian Fountain rejuvenates your health and mana.");
HealFtn(player, type, doMsgs);
}
protected override void FnEvent39(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, TROLLKNIGHT);
ShowText(player, type, doMsgs, "'Once you have the four map pieces the Queen seeks, make sure you know the order of the jewels before you seek your reward.");
ShowText(player, type, doMsgs, "Three clues are available for each race. I have found two and am now after the third. You must read all three clues, or you will not be rewarded.'");
}
protected override void FnEvent3A(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (UsedItem(player, type, ref doMsgs, RUBYLOCKPICK, RUBYLOCKPICK)) {
ShowText(player, type, doMsgs, "You are killed by Smirk who mistakes you for a robber.");
DamXit(player, type, doMsgs);
}
else {
ShowText(player, type, doMsgs, "Back door to Smirk's Emporium.");
WallBlock(player, type, doMsgs);
}
}
protected override void FnEvent3B(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, HALFLINGKNIGHT);
ShowText(player, type, doMsgs, "'I was told that in this area there are hidden rooms. A few rooms are available only to specific guilds.");
ShowText(player, type, doMsgs, "Beyond one hidden door is a second secretive door. That door leads to... Well, I think you should discover where that door leads.'");
}
protected override void FnEvent3C(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasItem(player, type, doMsgs, LIFEJACKET)) {
SetTreasure(player, type, doMsgs, BERSERKERTALISMAN, CHAINMAIL, 0, 0, 0, 1000);
}
else {
SetTreasure(player, type, doMsgs, LIFEJACKET, 0, 0, 0, 0, 3000);
ShowText(player, type, doMsgs, "You see a group of monsters tearing at a life jacket.");
}
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 2);
AddEncounter(player, type, doMsgs, 02, 7);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 1);
AddEncounter(player, type, doMsgs, 02, 3);
AddEncounter(player, type, doMsgs, 05, 7);
AddEncounter(player, type, doMsgs, 06, 8);
}
else {
AddEncounter(player, type, doMsgs, 01, 3);
AddEncounter(player, type, doMsgs, 02, 3);
AddEncounter(player, type, doMsgs, 03, 1);
AddEncounter(player, type, doMsgs, 04, 1);
AddEncounter(player, type, doMsgs, 05, 8);
AddEncounter(player, type, doMsgs, 06, 9);
}
}
protected override void FnEvent3D(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You can see it's a long, hard climb up to Cliffhanger.");
TeleportParty(player, type, doMsgs, 4, 1, 127, Direction.West);
}
protected override void FnEvent40(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "The Wine Cellar is dark and damp.");
}
protected override void FnEvent41(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 20);
AddEncounter(player, type, doMsgs, 02, 26);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 26);
AddEncounter(player, type, doMsgs, 02, 26);
AddEncounter(player, type, doMsgs, 03, 39);
AddEncounter(player, type, doMsgs, 04, 40);
}
else {
AddEncounter(player, type, doMsgs, 01, 21);
AddEncounter(player, type, doMsgs, 02, 38);
AddEncounter(player, type, doMsgs, 04, 38);
AddEncounter(player, type, doMsgs, 05, 39);
AddEncounter(player, type, doMsgs, 06, 40);
}
}
protected override void FnEvent42(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 15);
AddEncounter(player, type, doMsgs, 02, 32);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 16);
AddEncounter(player, type, doMsgs, 02, 17);
AddEncounter(player, type, doMsgs, 06, 11);
}
else {
AddEncounter(player, type, doMsgs, 01, 16);
AddEncounter(player, type, doMsgs, 02, 16);
AddEncounter(player, type, doMsgs, 03, 17);
AddEncounter(player, type, doMsgs, 05, 14);
AddEncounter(player, type, doMsgs, 06, 10);
}
}
protected override void FnEvent43(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 14);
AddEncounter(player, type, doMsgs, 02, 28);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 13);
AddEncounter(player, type, doMsgs, 02, 14);
AddEncounter(player, type, doMsgs, 04, 31);
}
else {
AddEncounter(player, type, doMsgs, 01, 13);
AddEncounter(player, type, doMsgs, 02, 13);
AddEncounter(player, type, doMsgs, 03, 14);
AddEncounter(player, type, doMsgs, 04, 14);
AddEncounter(player, type, doMsgs, 06, 33);
}
}
protected override void FnEvent44(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 29);
AddEncounter(player, type, doMsgs, 02, 29);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 1, 6);
AddEncounter(player, type, doMsgs, 2, 7);
AddEncounter(player, type, doMsgs, 6, 36);
}
else if (GetPartyCount(player, type, doMsgs) == 3) {
AddEncounter(player, type, doMsgs, 1, 5);
AddEncounter(player, type, doMsgs, 2, 6);
AddEncounter(player, type, doMsgs, 3, 21);
AddEncounter(player, type, doMsgs, 4, 19);
AddEncounter(player, type, doMsgs, 5, 20);
}
else {
AddEncounter(player, type, doMsgs, 1, 5);
AddEncounter(player, type, doMsgs, 2, 6);
AddEncounter(player, type, doMsgs, 3, 37);
AddEncounter(player, type, doMsgs, 4, 38);
AddEncounter(player, type, doMsgs, 5, 40);
AddEncounter(player, type, doMsgs, 6, 40);
}
}
protected override void FnEvent45(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 1);
AddEncounter(player, type, doMsgs, 02, 1);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 2);
AddEncounter(player, type, doMsgs, 02, 2);
AddEncounter(player, type, doMsgs, 06, 15);
}
else {
AddEncounter(player, type, doMsgs, 01, 2);
AddEncounter(player, type, doMsgs, 02, 3);
AddEncounter(player, type, doMsgs, 03, 16);
AddEncounter(player, type, doMsgs, 04, 17);
}
}
protected override void FnEvent46(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 1, 20);
AddEncounter(player, type, doMsgs, 2, 40);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 1, 21);
AddEncounter(player, type, doMsgs, 2, 21);
AddEncounter(player, type, doMsgs, 3, 23);
AddEncounter(player, type, doMsgs, 6, 40);
}
else if (GetPartyCount(player, type, doMsgs) == 3) {
AddEncounter(player, type, doMsgs, 1, 35);
AddEncounter(player, type, doMsgs, 2, 38);
AddEncounter(player, type, doMsgs, 3, 37);
AddEncounter(player, type, doMsgs, 5, 22);
AddEncounter(player, type, doMsgs, 6, 24);
}
else {
AddEncounter(player, type, doMsgs, 1, 23);
AddEncounter(player, type, doMsgs, 2, 39);
AddEncounter(player, type, doMsgs, 3, 36);
AddEncounter(player, type, doMsgs, 4, 36);
AddEncounter(player, type, doMsgs, 5, 34);
AddEncounter(player, type, doMsgs, 6, 34);
}
}
private void Jtxt(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "The waters of Journey's End Fountain are refreshing.");
}
private void WallClear(TwPlayerServer player, MapEventType type, bool doMsgs) {
ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
private void FntnPic(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, FOUNTAIN);
}
private void DamXit(TwPlayerServer player, MapEventType type, bool doMsgs) {
DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs));
// EXIT_DUNGEON(player, type, doMsgs);
}
private void WallBlock(TwPlayerServer player, MapEventType type, bool doMsgs) {
SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
private void DoorHere(TwPlayerServer player, MapEventType type, bool doMsgs) {
SetWallItem(player, type, doMsgs, DOOR, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
private void HealFtn(TwPlayerServer player, MapEventType type, bool doMsgs) {
ModifyHealth(player, type, doMsgs, GetHealthMax(player, type, doMsgs));
ModifyMana(player, type, doMsgs, 10000);
}
}
}
| |
using System;
using Pencil.Gaming;
using Pencil.Gaming.Graphics;
using System.Threading;
using System.Runtime.InteropServices;
namespace ExampleShader
{
public class ExampleShader : ShaderCrateLib.ShaderProgram
{
public ExampleShader ()
{
}
public static volatile int state = 0;
public static volatile string vertex = "";
public static volatile string fragment = "";
public override void OneTimeSetup ()
{
Thread x = new Thread (() => {
if (!Glfw.Init ()) {
Console.Error.WriteLine ("ERROR: Could not initialize GlFW, shutting down.");
Environment.Exit (1);
}
Glfw.SetErrorCallback ((code, des) => {
Console.Error.WriteLine ("ERROR ({0}): {1}", code, des);
});
Glfw.WindowHint (WindowHint.ContextVersionMajor, 4);
Glfw.WindowHint (WindowHint.ContextVersionMinor, 0);
Glfw.WindowHint (WindowHint.OpenGLForwardCompat, 1);
//should have one more line
GlfwWindowPtr window = Glfw.CreateWindow (800, 600, "GlFW 3 Window", GlfwMonitorPtr.Null, GlfwWindowPtr.Null);
if (window.Equals (GlfwWindowPtr.Null)) { // Does this line actually work???
Console.Error.WriteLine ("ERROR: Failed to create GlFW window, shutting down");
Environment.Exit (1);
}
Glfw.MakeContextCurrent (window);
Console.WriteLine ("render:" + GL.GetString (StringName.Renderer));
Console.WriteLine ("version:" + GL.GetString (StringName.Version));
GL.Enable (EnableCap.DepthTest);
GL.DepthFunc (DepthFunction.Less);
float[] points = {
-1.0f, 1.0f, -0.1f,
-1.0f, -1.0f, -0.1f,
1.0f, -1.0f, -0.1f ,
1.0f, 1.0f, -0.1f,
-1.0f, 1.0f, -0.1f,
1.0f, -1.0f, -0.1f
};
var vbo = GL.GenBuffer ();
GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
GL.BufferData(BufferTarget.ArrayBuffer, new IntPtr(Marshal.SizeOf(typeof(float))
*points.Length), points, BufferUsageHint.StaticDraw);
var vao = GL.GenVertexArray();
GL.BindVertexArray(vao);
GL.EnableVertexAttribArray(0);
GL.BindBuffer (BufferTarget.ArrayBuffer, vbo);
GL.VertexAttribPointer (0, 3, VertexAttribPointerType.Float, false, 0, IntPtr.Zero);
string vertex_shader = "#version 400\nin vec3 vp;\n" +
"uniform float iGlobalTime;\n"+
"uniform vec2 iResolution;\n"+
"void main () {"+
//" gl_Position = vec4 (vp, 1.0);"+
"gl_Position = vec4 (vp, 1.0);"+
"};";
string fragment_shader = "#version 400\nout vec4 frag_colour;\n"+
"uniform float iGlobalTime;\n"+
"uniform vec2 iResolution;\n"+
"void main () {"+
" frag_colour = vec4 (0.5, 0.0, 0.5, 1.0);"+
"}";;
var vs = GL.CreateShader (ShaderType.VertexShader);
GL.ShaderSource (vs, vertex_shader);
GL.CompileShader (vs);
Console.WriteLine(GL.GetShaderInfoLog (vs));
var fs = GL.CreateShader (ShaderType.FragmentShader);
GL.ShaderSource (fs, fragment_shader);
GL.CompileShader (fs);
Console.WriteLine (GL.GetShaderInfoLog (fs));
var combinedPrograms = GL.CreateProgram ();
GL.AttachShader (combinedPrograms,fs);
GL.AttachShader (combinedPrograms, vs);
GL.LinkProgram (combinedPrograms);
GL.ValidateProgram (combinedPrograms);
var IGlobalTime = GL.GetUniformLocation(combinedPrograms, "iGlobalTime");
GL.Uniform1(IGlobalTime, (float)DateTime.Now.Millisecond);
var iResolustion = GL.GetUniformLocation(combinedPrograms, "iResolution");
GL.Uniform2(iResolustion,new Pencil.Gaming.MathUtils.Vector2(800, 600));
GL.UseProgram (combinedPrograms);
while(!Glfw.WindowShouldClose(window))
{
switch(state)
{
case 0:
break;
case 1:
GL.Clear (ClearBufferMask.DepthBufferBit | ClearBufferMask.ColorBufferBit);
GL.ClearColor (1.0f, 0.0f, 0.0f, 1.0f);
//GL.UseProgram (combinedPrograms);
//GL.BindVertexArray (vao);
//GL.DrawArrays (BeginMode.Triangles, 0, verticesF.Length/3);
GL.UseProgram (combinedPrograms);
IGlobalTime = GL.GetUniformLocation(combinedPrograms, "iGlobalTime");
GL.Uniform1(IGlobalTime, (float)DateTime.Now.Millisecond);
GL.BindVertexArray (vao);
GL.DrawArrays (BeginMode.Triangles, 0, points.Length/3);
Glfw.SwapBuffers (window);
Glfw.PollEvents();
break;
case 2:
GL.Clear (ClearBufferMask.DepthBufferBit | ClearBufferMask.ColorBufferBit);
GL.ClearColor (1.0f, 0.0f, 0.0f, 1.0f);
//GL.UseProgram (combinedPrograms);
//GL.BindVertexArray (vao);
//GL.DrawArrays (BeginMode.Triangles, 0, verticesF.Length/3);
GL.UseProgram (combinedPrograms);
GL.BindVertexArray (vao);
GL.DrawArrays (BeginMode.Triangles, 0, points.Length/3);
Glfw.SwapBuffers (window);
Glfw.PollEvents();
break;
case 3:
var vs1 = GL.CreateShader (ShaderType.VertexShader);
GL.ShaderSource (vs1, vertex);
GL.CompileShader (vs1);
Console.WriteLine(GL.GetShaderInfoLog (vs1));
var fs1 = GL.CreateShader (ShaderType.FragmentShader);
GL.ShaderSource (fs1, fragment);
GL.CompileShader (fs1);
Console.WriteLine (GL.GetShaderInfoLog (fs1));
var combinedPrograms1 = GL.CreateProgram ();
GL.AttachShader (combinedPrograms1,fs1);
GL.AttachShader (combinedPrograms1, vs1);
GL.LinkProgram (combinedPrograms1);
GL.ValidateProgram (combinedPrograms1);
IGlobalTime = GL.GetUniformLocation(combinedPrograms1, "iGlobalTime");
GL.Uniform1(IGlobalTime, (float)DateTime.Now.Millisecond);
iResolustion = GL.GetUniformLocation(combinedPrograms, "iResolution");
GL.Uniform2(iResolustion, new Pencil.Gaming.MathUtils.Vector2(800, 600));
GL.DeleteProgram(combinedPrograms);
combinedPrograms = combinedPrograms1;
state = 1;
break;
}
}
});
x.IsBackground = true;
x.Start ();
}
public override void Pause ()
{
state = 2;
base.Pause ();
}
public override void Start ()
{
state = 1;
}
public override void Stop ()
{
state = 0;
base.Stop ();
}
public override string StartingVertexShader ()
{
return "#version 400\nin vec3 vp;\n" +
"uniform float iGlobalTime;\n"+
"uniform vec2 iResolution;\n"+
"void main () {"+
//" gl_Position = vec4 (vp, 1.0);"+
"gl_Position = vec4 (vp, 1.0);"+
"};";
}
public override string StartingFragmentShader ()
{
return "#version 400\nout vec4 frag_colour;\n" +
"uniform float iGlobalTime;\n"+
"uniform vec2 iResolution;\n"+
"void main () {" +
" frag_colour = vec4 (0.5, 0.0, 0.5, 1.0);" +
"}";
}
public override void setShaders (string vertex, string fragment)
{
if(ShaderReady)
{
ExampleShader.vertex = vertex;
ExampleShader.fragment = fragment;
state = 3;
}
}
public override string getVertexShader ()
{
return vertex;
}
public override string getFragmentShader ()
{
return fragment;
}
public override void setVertexShader (string vert)
{
vertex = vert;
}
public override void setFragmentShader (string frag)
{
fragment = frag;
}
}
}
| |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Dite.CoreApi.Models;
namespace Dite.CoreApi.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20160306162543_targetDetails")]
partial class targetDetails
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0-rc1-16348")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Dite.CoreApi.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasAnnotation("Relational:Name", "EmailIndex");
b.HasIndex("NormalizedUserName")
.HasAnnotation("Relational:Name", "UserNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetUsers");
});
modelBuilder.Entity("Dite.Model.TimerCounter", b =>
{
b.Property<Guid>("TimerCounterId")
.ValueGeneratedOnAdd();
b.Property<bool>("IsRunning");
b.Property<double>("Seconds");
b.Property<DateTime>("TimerEnd");
b.Property<Guid>("TimerHandlerId");
b.Property<DateTime>("TimerStart");
b.HasKey("TimerCounterId");
});
modelBuilder.Entity("Dite.Model.TimerHandler", b =>
{
b.Property<Guid>("TimerHandlerId")
.ValueGeneratedOnAdd();
b.Property<bool>("IsRunning");
b.Property<string>("Name");
b.HasKey("TimerHandlerId");
});
modelBuilder.Entity("Dite.Model.TimerResult", b =>
{
b.Property<Guid>("TimerResultId")
.ValueGeneratedOnAdd();
b.Property<int>("DayOfMonth");
b.Property<string>("DayOfWeek");
b.Property<int>("DayOfYear");
b.Property<int>("HourOfDay");
b.Property<int>("MinuteOfHour");
b.Property<int>("MonthOfYear");
b.Property<string>("Name");
b.Property<double>("Seconds");
b.Property<Guid>("TimerCounterId");
b.Property<Guid>("TimerHandlerId");
b.Property<int>("WeekOfMonth");
b.Property<int>("WeekOfYear");
b.Property<int>("Year");
b.HasKey("TimerResultId");
});
modelBuilder.Entity("Dite.Model.TimerTarget", b =>
{
b.Property<Guid>("TimerTargetId")
.ValueGeneratedOnAdd();
b.Property<int>("DayTargetHours");
b.Property<int>("DayTargetMinutes");
b.Property<int>("MonthTargetHours");
b.Property<int>("MonthTargetMinutes");
b.Property<string>("Name");
b.Property<double>("Seconds");
b.Property<int>("SecondsPerDay");
b.Property<int>("SecondsPerMonth");
b.Property<int>("SecondsPerWeek");
b.Property<int>("SecondsPerYear");
b.Property<int>("SecondsTotal");
b.Property<Guid>("TimerHandlerId");
b.Property<int>("TotalTargetHours");
b.Property<int>("TotalTargetMinutes");
b.Property<int>("WeekTargetHours");
b.Property<int>("WeekTargetMinutes");
b.Property<int>("YearTargetHours");
b.Property<int>("YearTargetMinutes");
b.HasKey("TimerTargetId");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasAnnotation("Relational:Name", "RoleNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasAnnotation("Relational:TableName", "AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasAnnotation("Relational:TableName", "AspNetUserRoles");
});
modelBuilder.Entity("Dite.Model.TimerCounter", b =>
{
b.HasOne("Dite.Model.TimerHandler")
.WithMany()
.HasForeignKey("TimerHandlerId");
});
modelBuilder.Entity("Dite.Model.TimerResult", b =>
{
b.HasOne("Dite.Model.TimerCounter")
.WithMany()
.HasForeignKey("TimerCounterId");
});
modelBuilder.Entity("Dite.Model.TimerTarget", b =>
{
b.HasOne("Dite.Model.TimerHandler")
.WithMany()
.HasForeignKey("TimerHandlerId");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.HasOne("Dite.CoreApi.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.HasOne("Dite.CoreApi.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
b.HasOne("Dite.CoreApi.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
}
}
}
| |
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using JetBrains.Annotations;
// ReSharper disable CheckNamespace
namespace System
// ReSharper restore CheckNamespace
{
public static class StringExtensions
{
public static string[] LinesX(this string source, bool removeEmptyLines = false)
{
return source.Split(new[] { "\r\r\n", Environment.NewLine, "\n" }, removeEmptyLines ? StringSplitOptions.RemoveEmptyEntries : StringSplitOptions.None);
}
public static string FirstLine(this string source)
{
var index = source.IndexOf(Environment.NewLine, StringComparison.OrdinalIgnoreCase);
return (index == -1) ? source : source.Substring(0, index + 1);
}
public static bool ContainsIgnoreCaseX(this IEnumerable<string> source, string target)
{
return source != null && source.Contains(target, StringComparer.OrdinalIgnoreCase);
}
public static bool EqualsIgnoreCaseX(this string source, string target)
{
return source != null && source.Equals(target, StringComparison.OrdinalIgnoreCase);
}
public static int FirstIndexOfX(this string source, params string[] matches)
{
return matches.Select(x => source.IndexOf(x, StringComparison.Ordinal)).Max();
}
public static int ParseToIntX(this string source)
{
return int.Parse(source);
}
public static int? TryParseToIntX(this string source)
{
int res;
return int.TryParse(source, out res) ? res : (int?)null;
}
public static long? TryParseToLongX(this string source)
{
long res;
return long.TryParse(source, out res) ? res : (long?)null;
}
public static byte ParseToByteX(this string source)
{
return byte.Parse(source);
}
public static byte? TryParseToByteX(this string source)
{
byte res;
return byte.TryParse(source, out res) ? res : (byte?)null;
}
public static bool ParseToBoolX(this string source)
{
return bool.Parse(source);
}
public static bool? TryParseToBoolX(this string source)
{
bool res;
return bool.TryParse(source, out res) ? res : (bool?)null;
}
public static DateTime ParseToUtcDateTimeX(this string source)
{
return DateTime.Parse(source, null);
}
public static DateTime ParseExactToUtcDateTimeX(this string source, string format)
{
return DateTime.ParseExact(source, format, null);
}
public static DateTime? TryParseToUtcDateTimeX(this string source, string format)
{
DateTime res;
return DateTime.TryParseExact(source, format, null, DateTimeStyles.AdjustToUniversal, out res) ? res : (DateTime?)null;
}
public static TimeSpan ParseToTimeSpanX(this string source)
{
return TimeSpan.Parse(source, null);
}
public static TimeSpan ParseExactToTimeSpanX(this string source, string format)
{
return TimeSpan.ParseExact(source, format, null);
}
public static TimeSpan? TryParseToTimeSpanX(this string source, string format)
{
TimeSpan res;
return TimeSpan.TryParseExact(source, format, null, out res) ? res : (TimeSpan?)null;
}
public static double ParseToDoubleX(this string source)
{
return double.Parse(source);
}
public static double? TryParseToDoubleX(this string source)
{
double res;
return double.TryParse(source, out res) ? res : (double?)null;
}
public static float ParseToSingleX(this string source)
{
return float.Parse(source);
}
public static float? TryParseToSingleX(this string source)
{
float res;
return float.TryParse(source, out res) ? res : (float?)null;
}
public static bool ContainsX(this string source, string contained, StringComparison options)
{
return source.IndexOf(contained, options) != -1;
}
public static bool ContainsX(this string source, string contained, int count, StringComparison options)
{
return (source.IndexOf(contained, 0, Math.Min(count, source.Length), options) >= 0);
}
public static bool ContainsTheFollowingStringsInTheSameOrderX(this string source, params string[] stringParts)
{
var current = source;
foreach (var stringPart in stringParts)
{
if (!current.Contains(stringPart))
{
return false;
}
current = current.Substring(current.IndexOf(stringPart));
}
return true;
}
public static string ReverseStringX(this string source)
{
char[] arr = source.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
[AssertionMethod]
[DebuggerNonUserCode]
public static bool IsNullOrWhiteSpaceX([CanBeNull][AssertionCondition(AssertionConditionType.IS_NOT_NULL)]this string source)
{
return string.IsNullOrWhiteSpace(source);
}
[AssertionMethod]
[DebuggerNonUserCode]
public static bool IsNullOrEmptyX([CanBeNull][AssertionCondition(AssertionConditionType.IS_NOT_NULL)]this string source)
{
return string.IsNullOrEmpty(source);
}
[AssertionMethod]
[DebuggerNonUserCode]
public static bool NotNullOrEmptyX([CanBeNull][AssertionCondition(AssertionConditionType.IS_NULL)]this string source)
{
return string.IsNullOrEmpty(source)==false;
}
public static string CapitalizeFirstLetterX(this string source)
{
if(source.IsNullOrEmptyX())
{
return source;
}
return Char.ToUpper(source[0]) + source.Substring(1);
}
public static string SubstringByIndexesX(this string source, int startIndex, int endIndex)
{
return source.Substring(startIndex, endIndex - startIndex);
}
public static string SeparatePascalCase(this string pascalCasedWord)
{
if (pascalCasedWord == null)
{
throw new ArgumentNullException("pascalCasedWord");
}
var sb = new StringBuilder(pascalCasedWord);
for (var i = pascalCasedWord.Length - 1; i > 0; i--)
{
if (char.IsUpper(pascalCasedWord[i]) && char.IsUpper(pascalCasedWord[i - 1])==false)
{
sb.Insert(i, " ");
}
else if(i+1<pascalCasedWord.Length
&& char.IsUpper(pascalCasedWord[i])
&& char.IsUpper(pascalCasedWord[i - 1])
&& char.IsUpper(pascalCasedWord[i + 1])==false)
{
sb.Insert(i, " ");
}
}
return sb.ToString();
}
public static string RemoveAllX(this string source, params char[] chars)
{
var sb = new StringBuilder();
foreach (char c in source)
{
if (chars.Any(x => x == c) == false)
{
sb.Append(c);
}
}
return sb.ToString();
}
public static string ReplaceCharactersAndCapitalizeX(this string input, char[] replaceCharacters, string replaceString = null)
{
var inputParts = input.Split(replaceCharacters, StringSplitOptions.RemoveEmptyEntries);
if (inputParts.Length == 0) return input;
return inputParts.Aggregate(new StringBuilder(),
(first, next) => first.Append(next.CapitalizeFirstLetterX() + (replaceString ?? string.Empty)),
x => x.ToString());
}
public static string Pluralize(this string input)
{
return input.EndsWith("s", StringComparison.OrdinalIgnoreCase)
? input
: input.EndsWith("y", StringComparison.OrdinalIgnoreCase)
? input.TrimEnd('y') + "ies"
: input + 's';
}
public static string ConcatX(this IEnumerable<string> source)
{
return string.Concat(source);
}
public static string JoinX(this IEnumerable<string> source, string seperator = "")
{
return string.Join(seperator, source);
}
[DebuggerNonUserCode]
[StringFormatMethod("source"), NotNull]
public static string FormatX(this string source, params object[] args)
{
return string.Format(source, args);
}
public static string ToOrdinalX(this int num)
{
switch (num % 100)
{
case 11:
case 12:
case 13:
return num + "th";
}
switch (num % 10)
{
case 1:
return num + "st";
case 2:
return num + "nd";
case 3:
return num + "rd";
default:
return num + "th";
}
}
}
}
| |
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using NUnit.Framework;
using Umbraco.Cms.Core.Cache;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.PublishedContent;
using Umbraco.Cms.Core.PropertyEditors;
using Umbraco.Cms.Core.PublishedCache;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Strings;
using Umbraco.Cms.Infrastructure.Serialization;
using Umbraco.Extensions;
namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Core.Published
{
[TestFixture]
public class PropertyCacheLevelTests
{
[TestCase(PropertyCacheLevel.None, 2)]
[TestCase(PropertyCacheLevel.Element, 1)]
[TestCase(PropertyCacheLevel.Elements, 1)]
[TestCase(PropertyCacheLevel.Snapshot, 1)]
public void CacheLevelTest(PropertyCacheLevel cacheLevel, int interConverts)
{
var converter = new CacheConverter1(cacheLevel);
var converters = new PropertyValueConverterCollection(() => new IPropertyValueConverter[]
{
converter,
});
var configurationEditorJsonSerializer = new ConfigurationEditorJsonSerializer();
var dataTypeServiceMock = new Mock<IDataTypeService>();
var dataType = new DataType(
new VoidEditor(
Mock.Of<IDataValueEditorFactory>()), configurationEditorJsonSerializer)
{ Id = 1 };
dataTypeServiceMock.Setup(x => x.GetAll()).Returns(dataType.Yield);
var publishedContentTypeFactory = new PublishedContentTypeFactory(Mock.Of<IPublishedModelFactory>(), converters, dataTypeServiceMock.Object);
IEnumerable<IPublishedPropertyType> CreatePropertyTypes(IPublishedContentType contentType)
{
yield return publishedContentTypeFactory.CreatePropertyType(contentType, "prop1", dataType.Id);
}
IPublishedContentType setType1 = publishedContentTypeFactory.CreateContentType(Guid.NewGuid(), 1000, "set1", CreatePropertyTypes);
// PublishedElementPropertyBase.GetCacheLevels:
//
// if property level is > reference level, or both are None
// use None for property & new reference
// else
// use Content for property, & keep reference
//
// PublishedElement creates properties with reference being None
// if converter specifies None, keep using None
// anything else is not > None, use Content
//
// for standalone elements, it's only None or Content
var set1 = new PublishedElement(setType1, Guid.NewGuid(), new Dictionary<string, object> { { "prop1", "1234" } }, false);
Assert.AreEqual(1234, set1.Value(Mock.Of<IPublishedValueFallback>(), "prop1"));
Assert.AreEqual(1, converter.SourceConverts);
Assert.AreEqual(1, converter.InterConverts);
// source is always converted once and cached per content
// inter conversion depends on the specified cache level
Assert.AreEqual(1234, set1.Value(Mock.Of<IPublishedValueFallback>(), "prop1"));
Assert.AreEqual(1, converter.SourceConverts);
Assert.AreEqual(interConverts, converter.InterConverts);
}
// property is not cached, converted cached at Content, exept
// /None = not cached at all
[TestCase(PropertyCacheLevel.None, PropertyCacheLevel.None, 2, 0, 0, 0, 0)]
[TestCase(PropertyCacheLevel.None, PropertyCacheLevel.Element, 1, 0, 0, 0, 0)]
[TestCase(PropertyCacheLevel.None, PropertyCacheLevel.Elements, 1, 0, 0, 0, 0)]
[TestCase(PropertyCacheLevel.None, PropertyCacheLevel.Snapshot, 1, 0, 0, 0, 0)]
// property is cached at element level, converted cached at
// /None = not at all
// /Element = in element
// /Snapshot = in snapshot
// /Elements = in elements
[TestCase(PropertyCacheLevel.Element, PropertyCacheLevel.None, 2, 0, 0, 0, 0)]
[TestCase(PropertyCacheLevel.Element, PropertyCacheLevel.Element, 1, 0, 0, 0, 0)]
[TestCase(PropertyCacheLevel.Element, PropertyCacheLevel.Elements, 1, 1, 0, 1, 0)]
[TestCase(PropertyCacheLevel.Element, PropertyCacheLevel.Snapshot, 1, 0, 1, 0, 1)]
// property is cached at elements level, converted cached at Element, exept
// /None = not cached at all
// /Snapshot = cached in snapshot
[TestCase(PropertyCacheLevel.Elements, PropertyCacheLevel.None, 2, 0, 0, 0, 0)]
[TestCase(PropertyCacheLevel.Elements, PropertyCacheLevel.Element, 1, 0, 0, 0, 0)]
[TestCase(PropertyCacheLevel.Elements, PropertyCacheLevel.Elements, 1, 0, 0, 0, 0)]
[TestCase(PropertyCacheLevel.Elements, PropertyCacheLevel.Snapshot, 1, 0, 1, 0, 1)]
// property is cached at snapshot level, converted cached at Element, exept
// /None = not cached at all
[TestCase(PropertyCacheLevel.Snapshot, PropertyCacheLevel.None, 2, 0, 0, 0, 0)]
[TestCase(PropertyCacheLevel.Snapshot, PropertyCacheLevel.Element, 1, 0, 0, 0, 0)]
[TestCase(PropertyCacheLevel.Snapshot, PropertyCacheLevel.Elements, 1, 0, 0, 0, 0)]
[TestCase(PropertyCacheLevel.Snapshot, PropertyCacheLevel.Snapshot, 1, 0, 0, 0, 0)]
public void CachePublishedSnapshotTest(
PropertyCacheLevel referenceCacheLevel,
PropertyCacheLevel converterCacheLevel,
int interConverts,
int elementsCount1,
int snapshotCount1,
int elementsCount2,
int snapshotCount2)
{
var converter = new CacheConverter1(converterCacheLevel);
var converters = new PropertyValueConverterCollection(() => new IPropertyValueConverter[]
{
converter,
});
var dataTypeServiceMock = new Mock<IDataTypeService>();
var dataType = new DataType(
new VoidEditor(
Mock.Of<IDataValueEditorFactory>()), new ConfigurationEditorJsonSerializer())
{ Id = 1 };
dataTypeServiceMock.Setup(x => x.GetAll()).Returns(dataType.Yield);
var publishedContentTypeFactory = new PublishedContentTypeFactory(Mock.Of<IPublishedModelFactory>(), converters, dataTypeServiceMock.Object);
IEnumerable<IPublishedPropertyType> CreatePropertyTypes(IPublishedContentType contentType)
{
yield return publishedContentTypeFactory.CreatePropertyType(contentType, "prop1", 1);
}
IPublishedContentType setType1 = publishedContentTypeFactory.CreateContentType(Guid.NewGuid(), 1000, "set1", CreatePropertyTypes);
var elementsCache = new FastDictionaryAppCache();
var snapshotCache = new FastDictionaryAppCache();
var publishedSnapshot = new Mock<IPublishedSnapshot>();
publishedSnapshot.Setup(x => x.SnapshotCache).Returns(snapshotCache);
publishedSnapshot.Setup(x => x.ElementsCache).Returns(elementsCache);
var publishedSnapshotAccessor = new Mock<IPublishedSnapshotAccessor>();
var localPublishedSnapshot = publishedSnapshot.Object;
publishedSnapshotAccessor.Setup(x => x.TryGetPublishedSnapshot(out localPublishedSnapshot)).Returns(true);
// pretend we're creating this set as a value for a property
// referenceCacheLevel is the cache level for this fictious property
// converterCacheLevel is the cache level specified by the converter
var set1 = new PublishedElement(setType1, Guid.NewGuid(), new Dictionary<string, object> { { "prop1", "1234" } }, false, referenceCacheLevel, publishedSnapshotAccessor.Object);
Assert.AreEqual(1234, set1.Value(Mock.Of<IPublishedValueFallback>(), "prop1"));
Assert.AreEqual(1, converter.SourceConverts);
Assert.AreEqual(1, converter.InterConverts);
Assert.AreEqual(elementsCount1, elementsCache.Count);
Assert.AreEqual(snapshotCount1, snapshotCache.Count);
Assert.AreEqual(1234, set1.Value(Mock.Of<IPublishedValueFallback>(), "prop1"));
Assert.AreEqual(1, converter.SourceConverts);
Assert.AreEqual(interConverts, converter.InterConverts);
Assert.AreEqual(elementsCount2, elementsCache.Count);
Assert.AreEqual(snapshotCount2, snapshotCache.Count);
FastDictionaryAppCache oldSnapshotCache = snapshotCache;
snapshotCache.Clear();
Assert.AreEqual(1234, set1.Value(Mock.Of<IPublishedValueFallback>(), "prop1"));
Assert.AreEqual(1, converter.SourceConverts);
Assert.AreEqual(elementsCount2, elementsCache.Count);
Assert.AreEqual(snapshotCount2, snapshotCache.Count);
Assert.AreEqual(snapshotCount2, oldSnapshotCache.Count);
Assert.AreEqual((interConverts == 1 ? 1 : 3) + snapshotCache.Count, converter.InterConverts);
FastDictionaryAppCache oldElementsCache = elementsCache;
elementsCache.Clear();
Assert.AreEqual(1234, set1.Value(Mock.Of<IPublishedValueFallback>(), "prop1"));
Assert.AreEqual(1, converter.SourceConverts);
Assert.AreEqual(elementsCount2, elementsCache.Count);
Assert.AreEqual(elementsCount2, oldElementsCache.Count);
Assert.AreEqual(snapshotCount2, snapshotCache.Count);
Assert.AreEqual((interConverts == 1 ? 1 : 4) + snapshotCache.Count + elementsCache.Count, converter.InterConverts);
}
[Test]
public void CacheUnknownTest()
{
var converter = new CacheConverter1(PropertyCacheLevel.Unknown);
var converters = new PropertyValueConverterCollection(() => new IPropertyValueConverter[]
{
converter,
});
var dataTypeServiceMock = new Mock<IDataTypeService>();
var dataType = new DataType(
new VoidEditor(
Mock.Of<IDataValueEditorFactory>()), new ConfigurationEditorJsonSerializer())
{ Id = 1 };
dataTypeServiceMock.Setup(x => x.GetAll()).Returns(dataType.Yield);
var publishedContentTypeFactory = new PublishedContentTypeFactory(Mock.Of<IPublishedModelFactory>(), converters, dataTypeServiceMock.Object);
IEnumerable<IPublishedPropertyType> CreatePropertyTypes(IPublishedContentType contentType)
{
yield return publishedContentTypeFactory.CreatePropertyType(contentType, "prop1", 1);
}
IPublishedContentType setType1 = publishedContentTypeFactory.CreateContentType(Guid.NewGuid(), 1000, "set1", CreatePropertyTypes);
Assert.Throws<Exception>(() =>
{
var unused = new PublishedElement(setType1, Guid.NewGuid(), new Dictionary<string, object> { { "prop1", "1234" } }, false);
});
}
private class CacheConverter1 : IPropertyValueConverter
{
private readonly PropertyCacheLevel _cacheLevel;
public CacheConverter1(PropertyCacheLevel cacheLevel) => _cacheLevel = cacheLevel;
public int SourceConverts { get; private set; }
public int InterConverts { get; private set; }
public bool? IsValue(object value, PropertyValueLevel level)
=> value != null && (!(value is string) || string.IsNullOrWhiteSpace((string)value) == false);
public bool IsConverter(IPublishedPropertyType propertyType)
=> propertyType.EditorAlias.InvariantEquals("Umbraco.Void");
public Type GetPropertyValueType(IPublishedPropertyType propertyType)
=> typeof(int);
public PropertyCacheLevel GetPropertyCacheLevel(IPublishedPropertyType propertyType)
=> _cacheLevel;
public object ConvertSourceToIntermediate(IPublishedElement owner, IPublishedPropertyType propertyType, object source, bool preview)
{
SourceConverts++;
return int.TryParse(source as string, out int i) ? i : 0;
}
public object ConvertIntermediateToObject(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview)
{
InterConverts++;
return (int)inter;
}
public object ConvertIntermediateToXPath(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview)
=> ((int)inter).ToString();
}
}
}
| |
namespace PokerTell.PokerHand.Tests.Services.PokerRoundsConverterTests
{
using System;
using Fakes;
using Infrastructure.Enumerations.PokerHand;
using Infrastructure.Interfaces.PokerHand;
using Infrastructure.Services;
using Interfaces;
using Microsoft.Practices.Unity;
using Moq;
using NUnit.Framework;
using PokerTell.PokerHand.Analyzation;
using PokerTell.PokerHand.Aquisition;
using PokerTell.PokerHand.Services;
using UnitTests;
public class Postflop_ThreePlayers : TestWithLog
{
#region Constants and Fields
IUnityContainer _container;
Constructor<IConvertedPokerPlayer> _convertedPlayerMake;
MockPokerRoundsConverter _converter;
StubBuilder _stub;
#endregion
#region Public Methods
[SetUp]
public void _Init()
{
_stub = new StubBuilder();
_convertedPlayerMake = new Constructor<IConvertedPokerPlayer>(() => new ConvertedPokerPlayer());
_container = new UnityContainer();
_container
.RegisterConstructor<IConvertedPokerAction, ConvertedPokerAction>()
.RegisterConstructor<IConvertedPokerActionWithId, ConvertedPokerActionWithId>()
.RegisterConstructor<IConvertedPokerRound, ConvertedPokerRound>()
.RegisterType<IPokerActionConverter, PokerActionConverter>()
.RegisterType<IPokerRoundsConverter, MockPokerRoundsConverter>();
_converter = (MockPokerRoundsConverter)_container.Resolve<IPokerRoundsConverter>();
_converter
.InitializeWith(
_stub.Setup<IAquiredPokerHand>()
.Get(hand => hand.TotalPot).Returns(_stub.Valid(For.TotalPot, 1.0)).Out,
_stub.Out<IConvertedPokerHand>(),
_stub.Valid(For.Pot, 1.0),
_stub.Out<double>(For.ToCall));
}
[Test]
public void ConvertFlop_Player1IsSmallBlind__SetsSequencesCorrectly()
{
RelativeRatioResult result = ConvertPreflopThreePlayersHand();
IConvertedPokerHand convHand = result.ConvertedHand;
IConvertedPokerPlayer smallBlindPlayer = convHand[0];
IConvertedPokerPlayer bigBlindPlayer = convHand[1];
IConvertedPokerPlayer buttonPlayer = convHand[2];
var action1 = new ConvertedPokerActionWithId(
smallBlindPlayer[Streets.Flop][0], smallBlindPlayer.Position);
var action2 = new ConvertedPokerActionWithId(bigBlindPlayer[Streets.Flop][0], bigBlindPlayer.Position);
var action3 = new ConvertedPokerActionWithId(buttonPlayer[Streets.Flop][0], buttonPlayer.Position);
var action4 = new ConvertedPokerActionWithId(
smallBlindPlayer[Streets.Flop][1], smallBlindPlayer.Position);
var action5 = new ConvertedPokerActionWithId(bigBlindPlayer[Streets.Flop][1], bigBlindPlayer.Position);
var action6 = new ConvertedPokerActionWithId(buttonPlayer[Streets.Flop][1], buttonPlayer.Position);
IConvertedPokerRound expectedPreflopSequence = new ConvertedPokerRound()
.Add(action1)
.Add(action2)
.Add(action3)
.Add(action4)
.Add(action5)
.Add(action6);
Assert.That(expectedPreflopSequence, Is.EqualTo(convHand.Sequences[(int)Streets.Flop]));
}
[Test]
public void ConvertFlop_Player1IsSmallBlind_CalculatesBigBlindsRatio1Correctly()
{
RelativeRatioResult result = ConvertPreflopThreePlayersHand();
Assert.That(result.Player2FlopRound[0].Ratio, Is.EqualTo(result.RelativeRatio2));
}
[Test]
public void ConvertFlop_Player1IsSmallBlind_CalculatesBigBlindsRatio2Correctly()
{
RelativeRatioResult result = ConvertPreflopThreePlayersHand();
Assert.That(result.Player2FlopRound[1].Ratio, Is.EqualTo(result.RelativeRatio5));
}
[Test]
public void ConvertFlop_Player1IsSmallBlind_CalculatesButtonsRatio1Correctly()
{
RelativeRatioResult result = ConvertPreflopThreePlayersHand();
Assert.That(result.Player3FlopRound[0].Ratio, Is.EqualTo(result.RelativeRatio3));
}
[Test]
public void ConvertFlop_Player1IsSmallBlind_CalculatesSmallBlindsRatio1Correctly()
{
RelativeRatioResult result = ConvertPreflopThreePlayersHand();
Assert.That(result.Player1FlopRound[0].Ratio, Is.EqualTo(result.RelativeRatio1));
}
[Test]
public void ConvertFlop_Player1IsSmallBlind_CalculatesSmallBlindsRatio2Correctly()
{
RelativeRatioResult result = ConvertPreflopThreePlayersHand();
Assert.That(result.Player1FlopRound[1].Ratio, Is.EqualTo(result.RelativeRatio4));
}
[Test]
public void ConvertFlop_Player1IsSmallBlind_SetsButtonsSecondActionToFold()
{
RelativeRatioResult result = ConvertPreflopThreePlayersHand();
Assert.That(result.Player3FlopRound[1].What, Is.EqualTo(ActionTypes.F));
}
[Test]
public void ConvertFlop_Player1IsSmallBlind_SetsSmallBlindsPreflopSequence()
{
// small blind bet 0.7
const string expectedSequence = "7";
var result = ConvertPreflopThreePlayersHand();
var smallBlindPreflopSequence = result.ConvertedHand[0].SequenceStrings[(int)Streets.Flop];
Assert.That(smallBlindPreflopSequence, Is.EqualTo(expectedSequence));
}
[Test]
public void ConvertFlop_Player1IsSmallBlind_SetsBigBlindsPreflopSequence()
{
// small blind bet 0.7 - big blind called
const string expectedSequence = "7C";
var result = ConvertPreflopThreePlayersHand();
var bigBlindPreflopSequence = result.ConvertedHand[1].SequenceStrings[(int)Streets.Flop];
Assert.That(bigBlindPreflopSequence, Is.EqualTo(expectedSequence));
}
[Test]
public void ConvertFlop_Player1IsSmallBlind_SetsButtonsPreflopSequence()
{
// small blind bet 0.7 - big blind called (ignored - not special) -> Button raised
const string expectedSequence = "7R";
var result = ConvertPreflopThreePlayersHand();
var buttonPreflopSequence = result.ConvertedHand[2].SequenceStrings[(int)Streets.Flop];
Assert.That(buttonPreflopSequence, Is.EqualTo(expectedSequence));
}
#endregion
#region Methods
RelativeRatioResult ConvertPreflopThreePlayersHand()
{
_stub
.Value(For.HoleCards).Is(string.Empty);
const double smallBlind = 1.0;
const double bigBlind = 2.0;
const double pot = smallBlind + bigBlind;
const int totalPlayers = 3;
const int smallBlindPosition = 0;
const int bigBlindPosition = 1;
const int buttonPosition = 2;
var action1 = new AquiredPokerAction(ActionTypes.B, bigBlind);
const double relativeRatio1 = bigBlind / pot;
const double pot1 = pot + bigBlind;
var action2 = new AquiredPokerAction(ActionTypes.C, bigBlind);
const double relativeRatio2 = bigBlind / pot1;
const double pot2 = pot1 + bigBlind;
var action3 = new AquiredPokerAction(ActionTypes.R, bigBlind * 3);
const double relativeRatio3 = 3;
const double pot3 = pot2 + (bigBlind * 3);
var action4 = new AquiredPokerAction(ActionTypes.R, bigBlind * 3 * 2);
const double relativeRatio4 = 2;
const double pot4 = pot3 + (bigBlind * 3 * 2);
var action5 = new AquiredPokerAction(ActionTypes.C, bigBlind * 3 * 2);
const double relativeRatio5 = (bigBlind * 2 * 3) / pot4;
var action6 = new AquiredPokerAction(ActionTypes.F, 1.0);
// Small Blind
IAquiredPokerPlayer player1 = new AquiredPokerPlayer(
_stub.Some<long>(), smallBlindPosition, _stub.Out<string>(For.HoleCards))
// Preflop
.AddRound(
new AquiredPokerRound()
.Add(new AquiredPokerAction(ActionTypes.C, 0.5)))
// Flop
.AddRound(
new AquiredPokerRound()
.Add(action1)
.Add(action4));
player1.Name = "player1";
player1.Position = smallBlindPosition;
// Big Blind
IAquiredPokerPlayer player2 = new AquiredPokerPlayer(
_stub.Some<long>(), bigBlindPosition, _stub.Out<string>(For.HoleCards))
// Preflop
.AddRound(
new AquiredPokerRound()
.Add(new AquiredPokerAction(ActionTypes.X, 1.0)))
// Flop
.AddRound(
new AquiredPokerRound()
.Add(action2)
.Add(action5));
player2.Name = "player2";
player2.Position = bigBlindPosition;
// Button
IAquiredPokerPlayer player3 = new AquiredPokerPlayer(
_stub.Some<long>(), buttonPosition, _stub.Out<string>(For.HoleCards))
// Preflop
.AddRound(
new AquiredPokerRound()
.Add(new AquiredPokerAction(ActionTypes.C, 1.0)))
// Flop
.AddRound(
new AquiredPokerRound()
.Add(action3)
.Add(action6));
player3.Name = "player3";
player3.Position = buttonPosition;
IAquiredPokerHand aquiredHand =
new AquiredPokerHand(
_stub.Valid(For.Site, "site"),
_stub.Out<ulong>(For.GameId),
_stub.Out<DateTime>(For.TimeStamp),
smallBlind,
bigBlind,
totalPlayers)
.AddPlayer(player1)
.AddPlayer(player2)
.AddPlayer(player3);
IConvertedPokerHand convertedHand =
new ConvertedPokerHand(aquiredHand)
.AddPlayersFrom(aquiredHand, pot, _convertedPlayerMake);
_converter
.InitializeWith(aquiredHand, convertedHand, pot, bigBlind)
.ConvertPreflop();
// Reset Values
_converter.PotProp = pot;
_converter.ToCallProp = bigBlind;
_converter.ConvertFlopTurnAndRiver();
IConvertedPokerRound player1FlopRound = convertedHand[smallBlindPosition][Streets.Flop];
IConvertedPokerRound player2FlopRound = convertedHand[bigBlindPosition][Streets.Flop];
IConvertedPokerRound player3FlopRound = convertedHand[buttonPosition][Streets.Flop];
return new RelativeRatioResult(
convertedHand,
player1FlopRound,
player2FlopRound,
player3FlopRound,
relativeRatio1,
relativeRatio2,
relativeRatio3,
relativeRatio4,
relativeRatio5);
}
#endregion
class RelativeRatioResult
{
#region Constants and Fields
public readonly IConvertedPokerHand ConvertedHand;
public readonly IConvertedPokerRound Player1FlopRound;
public readonly IConvertedPokerRound Player2FlopRound;
public readonly IConvertedPokerRound Player3FlopRound;
public readonly double RelativeRatio1;
public readonly double RelativeRatio2;
public readonly double RelativeRatio3;
public readonly double RelativeRatio4;
public readonly double RelativeRatio5;
#endregion
#region Constructors and Destructors
public RelativeRatioResult(
IConvertedPokerHand convertedHand,
IConvertedPokerRound player1FlopRound,
IConvertedPokerRound player2FlopRound,
IConvertedPokerRound player3FlopRound,
double relativeRatio1,
double relativeRatio2,
double relativeRatio3,
double relativeRatio4,
double relativeRatio5)
{
ConvertedHand = convertedHand;
Player1FlopRound = player1FlopRound;
Player2FlopRound = player2FlopRound;
Player3FlopRound = player3FlopRound;
RelativeRatio5 = relativeRatio5;
RelativeRatio4 = relativeRatio4;
RelativeRatio3 = relativeRatio3;
RelativeRatio2 = relativeRatio2;
RelativeRatio1 = relativeRatio1;
}
#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 Xunit;
using Xunit.Abstractions;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
namespace System.Xml.Tests
{
//[TestCase(Name = "XsltSettings-Retail", Desc = "This testcase tests the different settings on XsltSettings and the corresponding behavior in retail mode", Param = "Retail")]
//[TestCase(Name = "XsltSettings-Debug", Desc = "This testcase tests the different settings on XsltSettings and the corresponding behavior in debug mode", Param = "Debug")]
public class CXsltSettings : XsltApiTestCaseBase2
{
private ITestOutputHelper _output;
public CXsltSettings(ITestOutputHelper output) : base(output)
{
_output = output;
}
private XslCompiledTransform _xsl = null;
private string _xmlFile = string.Empty;
private string _xslFile = string.Empty;
private bool _debug = false;
private void Init(string xmlFile, string xslFile)
{
//if (Param.ToString() == "Debug")
//{
// xsl = new XslCompiledTransform(true);
// _debug = true;
//}
//else
_xsl = new XslCompiledTransform();
_xmlFile = FullFilePath(xmlFile);
_xslFile = FullFilePath(xslFile);
}
private StringWriter Transform()
{
StringWriter sw = new StringWriter();
_xsl.Transform(_xmlFile, null, sw);
return sw;
}
private void VerifyResult(object actual, object expected, string message)
{
_output.WriteLine("Expected : {0}", expected);
_output.WriteLine("Actual : {0}", actual);
Assert.Equal(actual, expected);
}
[ActiveIssue(9873)]
//[Variation(id = 1, Desc = "Test the script block with EnableScript, should work", Pri = 0, Params = new object[] { "XsltSettings.xml", "XsltSettings1.xsl", false, true })]
[InlineData(1, "XsltSettings.xml", "XsltSettings1.xsl", false, true)]
//[Variation(id = 4, Desc = "Test the script block with TrustedXslt, should work", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings1.xsl", true, true })]
[InlineData(4, "XsltSettings.xml", "XsltSettings1.xsl", true, true)]
//[Variation(id = 9, Desc = "Test the combination of script and document function with TrustedXslt, should work", Pri = 0, Params = new object[] { "XsltSettings.xml", "XsltSettings3.xsl", true, true })]
[InlineData(9, "XsltSettings.xml", "XsltSettings3.xsl", true, true)]
//[Variation(id = 11, Desc = "Test the combination of script and document function with EnableScript, only script should work", Pri = 2, Params = new object[] { "XsltSettings.xml", "XsltSettings3.xsl", false, true })]
[InlineData(11, "XsltSettings.xml", "XsltSettings3.xsl", false, true)]
[Theory]
public void XsltSettings1__1ActiveIssue9873(object param0, object param1, object param2, object param3, object param4)
{
XsltSettings1_1(param0, param1, param2, param3, param4);
}
//[Variation(id = 15, Desc = "Test 1 with Default settings, should fail", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings1.xsl", false, true, false, false })]
[InlineData(15, "XsltSettings.xml", "XsltSettings1.xsl", false, true, false, false)]
//[Variation(id = 16, Desc = "Test 2 with EnableScript override, should work", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings1.xsl", false, false, false, true })]
[InlineData(16, "XsltSettings.xml", "XsltSettings1.xsl", false, false, false, true)]
//[Variation(id = 19, Desc = "Test 9 with Default settings override, should fail", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings3.xsl", true, true, false, false })]
[InlineData(19, "XsltSettings.xml", "XsltSettings3.xsl", true, true, false, false)]
//[Variation(id = 20, Desc = "Test 10 with TrustedXslt override, should work", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings3.xsl", false, false, true, true })]
[InlineData(20, "XsltSettings.xml", "XsltSettings3.xsl", false, false, true, true)]
public void XsltSettings1_2_ActiveIssue9873(object param0, object param1, object param2, object param3, object param4, object param5, object param6)
{
XsltSettings1_2(param0, param1, param2, param3, param4, param5, param6);
}
[ActiveIssue(9876)]
//[Variation(id = 5, Desc = "Test the document function with EnableDocumentFunction, should work", Pri = 0, Params = new object[] { "XsltSettings.xml", "XsltSettings2.xsl", true, false })]
[InlineData(5, "XsltSettings.xml", "XsltSettings2.xsl", true, false)]
//[Variation(id = 8, Desc = "Test the document function with TrustedXslt, should work", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings2.xsl", true, true })]
[InlineData(8, "XsltSettings.xml", "XsltSettings2.xsl", true, true)]
[Theory]
public void XsltSettings1_1_ActiveIssue9876(object param0, object param1, object param2, object param3, object param4)
{
XsltSettings1_1(param0, param1, param2, param3, param4);
}
[ActiveIssue(9876)]
//[Variation(id = 18, Desc = "Test 6 with EnableDocumentFunction override, should work", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings2.xsl", false, false, true, false })]
[InlineData(18, "XsltSettings.xml", "XsltSettings2.xsl", false, false, true, false)]
[Theory]
public void XsltSettings1_2_ActiveIssue9876(object param0, object param1, object param2, object param3, object param4, object param5, object param6)
{
XsltSettings1_2(param0, param1, param2, param3, param4, param5, param6);
}
//[Variation(id = 2, Desc = "Test the script block with Default Settings, should fail", Pri = 0, Params = new object[] { "XsltSettings.xml", "XsltSettings1.xsl", false, false })]
[InlineData(2, "XsltSettings.xml", "XsltSettings1.xsl", false, false)]
//[Variation(id = 3, Desc = "Test the script block with EnableDocumentFunction, should fail", Pri = 2, Params = new object[] { "XsltSettings.xml", "XsltSettings1.xsl", true, false })]
[InlineData(3, "XsltSettings.xml", "XsltSettings1.xsl", true, false)]
//[Variation(id = 6, Desc = "Test the document function with Default Settings, should fail", Pri = 0, Params = new object[] { "XsltSettings.xml", "XsltSettings2.xsl", false, false })]
[InlineData(6, "XsltSettings.xml", "XsltSettings2.xsl", false, false)]
//[Variation(id = 7, Desc = "Test the document function with EnableScript, should fail", Pri = 2, Params = new object[] { "XsltSettings.xml", "XsltSettings2.xsl", false, true })]
[InlineData(7, "XsltSettings.xml", "XsltSettings2.xsl", false, true)]
//[Variation(id = 10, Desc = "Test the combination of script and document function with Default Settings, should fail", Pri = 0, Params = new object[] { "XsltSettings.xml", "XsltSettings3.xsl", false, false })]
[InlineData(10, "XsltSettings.xml", "XsltSettings3.xsl", false, false)]
//[Variation(id = 12, Desc = "Test the combination of script and document function with EnableDocumentFunction, only document should work", Pri = 2, Params = new object[] { "XsltSettings.xml", "XsltSettings3.xsl", true, false })]
[InlineData(12, "XsltSettings.xml", "XsltSettings3.xsl", true, false)]
//[Variation(id = 13, Desc = "Test the stylesheet with no script and document function with Default Settings", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings4.xsl", false, false })]
[InlineData(13, "XsltSettings.xml", "XsltSettings4.xsl", false, false)]
//[Variation(id = 14, Desc = "Test the stylesheet with no script and document function with TrustedXslt", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings4.xsl", true, true })]
[InlineData(14, "XsltSettings.xml", "XsltSettings4.xsl", true, true)]
/*
* enable all disable scripting
* enable all disable document()
* enable all disable none
* enable all disable all
*/
[Theory]
public void XsltSettings1_1(object param0, object param1, object param2, object param3, object param4)
{
Init(param1.ToString(), param2.ToString());
// In Proc Skip
// XsltSettings - Debug (1-20)
// XsltSettings - Retail (1,4,9,11,15,16,19,20)
if (_isInProc)
{
if (_debug)
return; //TEST_SKIPPED;
else
{
switch ((int)param0)
{
case 1:
case 4:
case 9:
case 11:
return; //TEST_SKIPPED;
// default:
//just continue;
}
}
}
XsltSettings xs = new XsltSettings((bool)param3, (bool)param4);
_xsl.Load(_xslFile, xs, new XmlUrlResolver());
try
{
StringWriter sw = Transform();
switch ((int)param0)
{
case 1:
case 4:
VerifyResult(sw.ToString(), "30", "Unexpected result, expected 30");
return;
case 5:
case 8:
VerifyResult(sw.ToString(), "7", "Unexpected result, expected 7");
return;
case 9:
VerifyResult(sw.ToString(), "17", "Unexpected result, expected 17");
return;
case 13:
case 14:
VerifyResult(sw.ToString(), "PASS", "Unexpected result, expected PASS");
return;
default:
Assert.True(false);
return;
}
}
catch (XsltException ex)
{
switch ((int)param0)
{
case 2:
case 3:
case 6:
case 7:
case 10:
case 11:
case 12:
_output.WriteLine(ex.ToString());
_output.WriteLine(ex.Message);
return;
default:
Assert.True(false);
return;
}
}
}
//[Variation(id = 17, Desc = "Test 5 with Default settings override, should fail", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings2.xsl", true, false, false, false })]
[InlineData(17, "XsltSettings.xml", "XsltSettings2.xsl", true, false, false, false)]
/*
* enable all disable scripting
* enable all disable document()
* enable all disable none
* enable all disable all
*/
[Theory]
public void XsltSettings1_2(object param0, object param1, object param2, object param3, object param4, object param5, object param6)
{
Init(param1.ToString(), param2.ToString());
// In Proc Skip
// XsltSettings - Debug (1-20)
// XsltSettings - Retail (1,4,9,11,15,16,19,20)
if (_isInProc)
{
if (_debug)
return; //TEST_SKIPPED;
else
{
switch ((int)param0)
{
case 15:
case 16:
case 19:
case 20:
return; //TEST_SKIPPED;
// default:
//just continue;
}
}
}
XsltSettings xs = new XsltSettings((bool)param3, (bool)param4);
_xsl.Load(_xslFile, xs, new XmlUrlResolver());
xs.EnableDocumentFunction = (bool)param5;
xs.EnableScript = (bool)param6;
_xsl.Load(_xslFile, xs, new XmlUrlResolver());
try
{
StringWriter sw = Transform();
switch ((int)param0)
{
case 16:
VerifyResult(sw.ToString(), "30", "Unexpected result, expected 30");
return;
case 18:
VerifyResult(sw.ToString(), "7", "Unexpected result, expected 7");
return;
case 20:
VerifyResult(sw.ToString(), "17", "Unexpected result, expected 17");
return;
default:
Assert.True(false);
return;
}
}
catch (XsltException ex)
{
switch ((int)param0)
{
case 15:
case 17:
case 19:
_output.WriteLine(ex.ToString());
_output.WriteLine(ex.Message);
return;
default:
Assert.True(false);
return;
}
}
}
//[Variation(id = 21, Desc = "Disable Scripting and load a stylesheet which includes another sytlesheet with script block", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings5.xsl", false, false })]
[InlineData("XsltSettings.xml", "XsltSettings5.xsl", false, false)]
//[Variation(id = 22, Desc = "Disable Scripting and load a stylesheet which imports XSLT which includes another XSLT with script block", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings6.xsl", false, false })]
[InlineData("XsltSettings.xml", "XsltSettings6.xsl", false, false)]
//[Variation(id = 23, Desc = "Disable Scripting and load a stylesheet which has an entity expanding to a script block", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings7.xsl", false, false })]
[InlineData("XsltSettings.xml", "XsltSettings7.xsl", false, false)]
//[Variation(id = 24, Desc = "Disable Scripting and load a stylesheet with multiple script blocks with different languages", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings8.xsl", false, false })]
[InlineData("XsltSettings.xml", "XsltSettings8.xsl", false, false)]
[Theory]
public void XsltSettings2(object param0, object param1, object param2, object param3)
{
Init(param0.ToString(), param1.ToString());
if (_isInProc)
if (_debug)
return; //TEST_SKIPPED;
XsltSettings xs = new XsltSettings((bool)param2, (bool)param3);
XPathDocument doc = new XPathDocument(_xslFile);
_xsl.Load(doc, xs, new XmlUrlResolver());
try
{
StringWriter sw = Transform();
_output.WriteLine("Execution of the scripts was allowed even when XsltSettings.EnableScript is false");
Assert.True(false);
}
catch (XsltException ex)
{
_output.WriteLine(ex.ToString());
return;
}
}
//[Variation(id = 25, Desc = "Disable DocumentFunction and Malicious stylesheet has document(url) opening a URL to an external system", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings9.xsl", false, false })]
//[InlineData("XsltSettings.xml", "XsltSettings9.xsl", false, false)]
//[Variation(id = 26, Desc = "Disable DocumentFunction and Malicious stylesheet has document(nodeset) opens union of all URLs referenced", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings10.xsl", false, false })]
[InlineData("XsltSettings.xml", "XsltSettings10.xsl", false, false)]
//[Variation(id = 27, Desc = "Disable DocumentFunction and Malicious stylesheet has document(url, nodeset) nodeset is a base URL to 1st arg", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings11.xsl", false, false })]
//[InlineData("XsltSettings.xml", "XsltSettings11.xsl", false, false)]
//[Variation(id = 28, Desc = "Disable DocumentFunction and Malicious stylesheet has document(nodeset, nodeset) 2nd arg is a base URL to 1st arg", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings12.xsl", false, false })]
[InlineData("XsltSettings.xml", "XsltSettings12.xsl", false, false)]
//[Variation(id = 29, Desc = "Disable DocumentFunction and Malicious stylesheet has document(''), no threat but just to verify if its considered", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings13.xsl", false, false })]
[InlineData("XsltSettings.xml", "XsltSettings13.xsl", false, false)]
//[Variation(id = 30, Desc = "Disable DocumentFunction and Stylesheet includes another stylesheet with document() function", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings14.xsl", false, false })]
//[InlineData("XsltSettings.xml", "XsltSettings14.xsl", false, false)]
//[Variation(id = 31, Desc = "Disable DocumentFunction and Stylesheet has an entity reference to doc(), ENTITY s document('foo.xml')", Pri = 1, Params = new object[] { "XsltSettings.xml", "XsltSettings15.xsl", false, false })]
//[InlineData("XsltSettings.xml", "XsltSettings15.xsl", false, false)]
[Theory]
public void XsltSettings3(object param0, object param1, object param2, object param3)
{
Init(param0.ToString(), param1.ToString());
if (_isInProc)
if (_debug)
return; //TEST_SKIPPED;
XsltSettings xs = new XsltSettings((bool)param2, (bool)param3);
XPathDocument doc = new XPathDocument(_xslFile);
_xsl.Load(doc, xs, new XmlUrlResolver());
try
{
StringWriter sw = Transform();
_output.WriteLine("Execution of the document function was allowed even when XsltSettings.EnableDocumentFunction is false");
Assert.True(false);
}
catch (XsltException ex)
{
_output.WriteLine(ex.ToString());
return;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace CmdrCompanion.Core
{
/// <summary>
/// Describes the commercial availability of a <see cref="Commodity"/>
/// </summary>
/// <seealso cref="CmdrCompanion.Core.Station.CreateTrade"/>
public class Trade : CoreObject
{
internal Trade(AstronomicalObject station, Commodity commodity)
{
Station = station;
Commodity = commodity;
DataDate = DateTime.Now;
}
/// <summary>
/// Gets a value indicating whether the station has this commodity available for sale
/// </summary>
public bool CanSell
{
get
{
return SellingPrice > 0 && Stock > 0;
}
}
/// <summary>
/// Gets a value indicating whether the station can buy this commodity
/// </summary>
public bool CanBuy
{
get
{
return BuyingPrice > 0;
}
}
private float _sellingPrice;
/// <summary>
/// Gets of sets the price at which the station will sell this commodity to traders
/// </summary>
public float SellingPrice
{
get
{
return _sellingPrice;
}
set
{
if (value < 0)
value = 0;
if (value != _sellingPrice)
{
_sellingPrice = value;
OnPropertyChanged(new string[] { "SellingPrice", "CanSell" });
}
}
}
private float _buyingPrice;
/// <summary>
/// Gets of sets the price at which the station will buy this commodity from traders
/// </summary>
public float BuyingPrice
{
get
{
return _buyingPrice;
}
set
{
if (value < 0)
value = 0;
if(value != _buyingPrice)
{
_buyingPrice = value;
OnPropertyChanged(new string[] { "BuyingPrice", "CanBuy" });
}
}
}
private int _stock;
/// <summary>
/// Gets of sets the amount of units available for sale
/// </summary>
public int Stock
{
get
{
return _stock;
}
set
{
if (value < 0)
value = 0;
if(value != _stock)
{
_stock = value;
OnPropertyChanged(new string[] { "Stock", "CanSell" });
}
}
}
/// <summary>
/// Gets the station that conducts this trade.
/// </summary>
public AstronomicalObject Station { get; private set; }
/// <summary>
/// Gets the commodity that this trade instance is about
/// </summary>
public Commodity Commodity { get; private set; }
private DateTime _dataDate;
/// <summary>
/// Gets or sets the date at which the data in this instance was extracted from the game
/// </summary>
public DateTime DataDate
{
get
{
return _dataDate;
}
set
{
if(value != _dataDate)
{
_dataDate = value;
OnPropertyChanged("DataDate");
}
}
}
/// <summary>
/// Returns the string representation of this instance
/// </summary>
/// <returns>The string representation of this instance</returns>
public override string ToString()
{
return String.Format("Trade of {0} between at station {1}", Commodity.Name, Station.Name);
}
internal void Save(XmlWriter writer)
{
writer.WriteStartElement("trade");
writer.WriteAttributeString("commodity", Commodity.Name);
writer.WriteAttributeFloat("sellingPrice", SellingPrice);
writer.WriteAttributeFloat("buyingPrice", BuyingPrice);
writer.WriteAttributeInt("stock", Stock);
writer.WriteAttributeString("station", Station.Name);
writer.WriteEndElement();
}
internal static bool Load(XmlReader reader, EliteEnvironment container)
{
if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "trade")
return false;
Commodity commodity = null;
AstronomicalObject station = null;
float sellingPrice = 0;
float buyingPrice = 0;
int stock = 0;
while(reader.MoveToNextAttribute())
{
switch(reader.LocalName)
{
case "commodity":
commodity = container.FindCommodityByName(reader.Value);
if(commodity == null)
throw new EnvironmentLoadException(String.Format("Unknown commodity name '{0}'", reader.Value), reader);
break;
case "station":
station = container.Stations.Where(s => s.Name == reader.Value).FirstOrDefault();
if (station == null)
throw new EnvironmentLoadException(String.Format("Unknown station name '{0}'", reader.Value), reader);
break;
case "sellingPrice":
sellingPrice = reader.ReadFloat();
break;
case "buyingPrice":
buyingPrice = reader.ReadFloat();
break;
case "stock":
stock = reader.ReadInt();
break;
}
}
if (commodity == null)
throw new EnvironmentLoadException("Missing commodity for a trade entry", reader);
if (station == null)
throw new EnvironmentLoadException("Missing station for a trade entry", reader);
station.CreateTrade(commodity, sellingPrice, buyingPrice, stock);
reader.Read();
return true;
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.HSSF.Record.Aggregates
{
using System;
using System.Text;
using System.Collections;
using NPOI.HSSF.Record;
using NPOI.HSSF.Model;
using NPOI.SS.Formula;
using System.Collections.Generic;
using NPOI.SS.Util;
using NPOI.SS.Formula.PTG;
using NPOI.Util;
/// <summary>
///
/// </summary>
/// CFRecordsAggregate - aggregates Conditional Formatting records CFHeaderRecord
/// and number of up to three CFRuleRecord records toGether to simplify
/// access to them.
/// @author Dmitriy Kumshayev
public class CFRecordsAggregate : RecordAggregate
{
/** Excel allows up to 3 conditional formating rules */
private const int MAX_97_2003_CONDTIONAL_FORMAT_RULES = 3;
public const short sid = -2008; // not a real BIFF record
//private static POILogger log = POILogFactory.GetLogger(typeof(CFRecordsAggregate));
private CFHeaderBase header;
/** List of CFRuleRecord objects */
private List<CFRuleBase> rules;
private CFRecordsAggregate(CFHeaderBase pHeader, CFRuleBase[] pRules)
{
if (pHeader == null)
{
throw new ArgumentException("header must not be null");
}
if (pRules == null)
{
throw new ArgumentException("rules must not be null");
}
if (pRules.Length > MAX_97_2003_CONDTIONAL_FORMAT_RULES)
{
Console.WriteLine("Excel versions before 2007 require that "
+ "No more than " + MAX_97_2003_CONDTIONAL_FORMAT_RULES
+ " rules may be specified, " + pRules.Length + " were found,"
+ " this file will cause problems with old Excel versions");
}
if (pRules.Length != pHeader.NumberOfConditionalFormats)
{
throw new RecordFormatException("Mismatch number of rules");
}
header = pHeader;
rules = new List<CFRuleBase>(pRules.Length);
foreach (CFRuleBase pRule in pRules)
{
CheckRuleType(pRule);
rules.Add(pRule);
}
}
public CFRecordsAggregate(CellRangeAddress[] regions, CFRuleBase[] rules)
: this(CreateHeader(regions, rules), rules)
{
}
private static CFHeaderBase CreateHeader(CellRangeAddress[] regions, CFRuleBase[] rules)
{
CFHeaderBase header;
if (rules.Length == 0 || rules[0] is CFRuleRecord) {
header = new CFHeaderRecord(regions, rules.Length);
}
else
{
header = new CFHeader12Record(regions, rules.Length);
}
// set the "needs recalculate" by default to avoid Excel handling conditional formatting incorrectly
// see bug 52122 for details
header.NeedRecalculation = true;
return header;
}
/// <summary>
/// Create CFRecordsAggregate from a list of CF Records
/// </summary>
/// <param name="rs">list of Record objects</param>
public static CFRecordsAggregate CreateCFAggregate(RecordStream rs)
{
Record rec = rs.GetNext();
if (rec.Sid != CFHeaderRecord.sid &&
rec.Sid != CFHeader12Record.sid)
{
throw new InvalidOperationException("next record sid was " + rec.Sid
+ " instead of " + CFHeaderRecord.sid + " or "
+ CFHeader12Record.sid + " as expected");
}
CFHeaderBase header = (CFHeaderBase)rec;
int nRules = header.NumberOfConditionalFormats;
CFRuleBase[] rules = new CFRuleBase[nRules];
for (int i = 0; i < rules.Length; i++)
{
rules[i] = (CFRuleBase)rs.GetNext();
}
return new CFRecordsAggregate(header, rules);
}
/// <summary>
/// Create CFRecordsAggregate from a list of CF Records
/// </summary>
/// <param name="recs">list of Record objects</param>
/// <param name="pOffset">position of CFHeaderRecord object in the list of Record objects</param>
[Obsolete("Not found in poi(2015-07-14), maybe was removed")]
public static CFRecordsAggregate CreateCFAggregate(IList recs, int pOffset)
{
Record rec = (Record)recs[pOffset];
if (rec.Sid != CFHeaderRecord.sid)
{
throw new InvalidOperationException("next record sid was " + rec.Sid
+ " instead of " + CFHeaderRecord.sid + " as expected");
}
CFHeaderRecord header = (CFHeaderRecord)rec;
int nRules = header.NumberOfConditionalFormats;
CFRuleRecord[] rules = new CFRuleRecord[nRules];
int offset = pOffset;
int countFound = 0;
while (countFound < rules.Length)
{
offset++;
if (offset >= recs.Count)
{
break;
}
rec = (Record)recs[offset];
if (rec is CFRuleRecord)
{
rules[countFound] = (CFRuleRecord)rec;
countFound++;
}
else
{
break;
}
}
if (countFound < nRules)
{ // TODO -(MAR-2008) can this ever happen? Write junit
//if (log.Check(POILogger.DEBUG))
//{
// log.Log(POILogger.DEBUG, "Expected " + nRules + " Conditional Formats, "
// + "but found " + countFound + " rules");
//}
header.NumberOfConditionalFormats = (nRules);
CFRuleRecord[] lessRules = new CFRuleRecord[countFound];
Array.Copy(rules, 0, lessRules, 0, countFound);
rules = lessRules;
}
return new CFRecordsAggregate(header, rules);
}
public override void VisitContainedRecords(RecordVisitor rv)
{
rv.VisitRecord(header);
foreach (CFRuleBase rule in rules)
{
rv.VisitRecord(rule);
}
}
/// <summary>
/// Create a deep Clone of the record
/// </summary>
public CFRecordsAggregate CloneCFAggregate()
{
CFRuleBase[] newRecs = new CFRuleBase[rules.Count];
for (int i = 0; i < newRecs.Length; i++)
{
newRecs[i] = (CFRuleRecord)GetRule(i).Clone();
}
return new CFRecordsAggregate((CFHeaderBase)header.Clone(), newRecs);
}
public override short Sid
{
get { return sid; }
}
/// <summary>
/// called by the class that is responsible for writing this sucker.
/// Subclasses should implement this so that their data is passed back in a
/// byte array.
/// </summary>
/// <param name="offset">The offset to begin writing at</param>
/// <param name="data">The data byte array containing instance data</param>
/// <returns> number of bytes written</returns>
public override int Serialize(int offset, byte[] data)
{
int nRules = rules.Count;
header.NumberOfConditionalFormats = (nRules);
int pos = offset;
pos += header.Serialize(pos, data);
for (int i = 0; i < nRules; i++)
{
pos += GetRule(i).Serialize(pos, data);
}
return pos - offset;
}
public CFHeaderBase Header
{
get { return header; }
}
private void CheckRuleIndex(int idx)
{
if (idx < 0 || idx >= rules.Count)
{
throw new ArgumentException("Bad rule record index (" + idx
+ ") nRules=" + rules.Count);
}
}
private void CheckRuleType(CFRuleBase r)
{
if (header is CFHeaderRecord &&
r is CFRuleRecord) {
return;
}
if (header is CFHeader12Record &&
r is CFRule12Record) {
return;
}
throw new ArgumentException("Header and Rule must both be CF or both be CF12, can't mix");
}
public CFRuleBase GetRule(int idx)
{
CheckRuleIndex(idx);
return rules[idx];
}
public void SetRule(int idx, CFRuleBase r)
{
CheckRuleIndex(idx);
CheckRuleType(r);
rules[idx] = r;
}
/**
* @return <c>false</c> if this whole {@link CFHeaderRecord} / {@link CFRuleRecord}s should be deleted
*/
public bool UpdateFormulasAfterCellShift(FormulaShifter shifter, int currentExternSheetIx)
{
CellRangeAddress[] cellRanges = header.CellRanges;
bool changed = false;
List<CellRangeAddress> temp = new List<CellRangeAddress>();
foreach (CellRangeAddress craOld in cellRanges)
{
CellRangeAddress craNew = ShiftRange(shifter, craOld, currentExternSheetIx);
if (craNew == null)
{
changed = true;
continue;
}
temp.Add(craNew);
if (craNew != craOld)
{
changed = true;
}
}
if (changed)
{
int nRanges = temp.Count;
if (nRanges == 0)
{
return false;
}
CellRangeAddress[] newRanges = new CellRangeAddress[nRanges];
newRanges = temp.ToArray();
header.CellRanges = (newRanges);
}
foreach (CFRuleBase rule in rules)
{
Ptg[] ptgs;
ptgs = rule.ParsedExpression1;
if (ptgs != null && shifter.AdjustFormula(ptgs, currentExternSheetIx))
{
rule.ParsedExpression1 = (ptgs);
}
ptgs = rule.ParsedExpression2;
if (ptgs != null && shifter.AdjustFormula(ptgs, currentExternSheetIx))
{
rule.ParsedExpression2 = (ptgs);
}
if (rule is CFRule12Record)
{
CFRule12Record rule12 = (CFRule12Record)rule;
ptgs = rule12.ParsedExpressionScale;
if (ptgs != null && shifter.AdjustFormula(ptgs, currentExternSheetIx))
{
rule12.ParsedExpressionScale = (ptgs);
}
}
}
return true;
}
private static CellRangeAddress ShiftRange(FormulaShifter shifter, CellRangeAddress cra, int currentExternSheetIx)
{
// FormulaShifter works well in terms of Ptgs - so convert CellRangeAddress to AreaPtg (and back) here
AreaPtg aptg = new AreaPtg(cra.FirstRow, cra.LastRow, cra.FirstColumn, cra.LastColumn, false, false, false, false);
Ptg[] ptgs = { aptg, };
if (!shifter.AdjustFormula(ptgs, currentExternSheetIx))
{
return cra;
}
Ptg ptg0 = ptgs[0];
if (ptg0 is AreaPtg)
{
AreaPtg bptg = (AreaPtg)ptg0;
return new CellRangeAddress(bptg.FirstRow, bptg.LastRow, bptg.FirstColumn, bptg.LastColumn);
}
if (ptg0 is AreaErrPtg)
{
return null;
}
throw new InvalidCastException("Unexpected shifted ptg class (" + ptg0.GetType().Name + ")");
}
public void AddRule(CFRuleBase r)
{
if (rules.Count >= MAX_97_2003_CONDTIONAL_FORMAT_RULES)
{
Console.WriteLine("Excel versions before 2007 cannot cope with"
+ " any more than " + MAX_97_2003_CONDTIONAL_FORMAT_RULES
+ " - this file will cause problems with old Excel versions");
}
CheckRuleType(r);
rules.Add(r);
header.NumberOfConditionalFormats = (rules.Count);
}
public int NumberOfRules
{
get { return rules.Count; }
}
public override String ToString()
{
StringBuilder buffer = new StringBuilder();
String type = "CF";
if (header is CFHeader12Record) {
type = "CF12";
}
buffer.Append("[").Append(type).Append("]\n");
if (header != null)
{
buffer.Append(header.ToString());
}
foreach (CFRuleBase cfRule in rules)
{
if (cfRule != null)
{
buffer.Append(cfRule.ToString());
}
}
buffer.Append("[/CF]\n");
return buffer.ToString();
}
}
}
| |
#define debugging
/*-----------------------------------------------------------------------------------------
C#Prolog -- Copyright (C) 2007-2009 John Pool -- j.pool@ision.nl
Contributions 2009 by Lars Iwer -- lars.iwer@inf.tu-dresden.de
This library is free software; you can redistribute it and/or modify it under the terms of
the GNU General Public License as published by the Free Software Foundation; either version
2 of the License, or 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 General Public License for details, or enter 'license.' at the command prompt.
-------------------------------------------------------------------------------------------*/
using System;
using System.Text;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Text.RegularExpressions;
namespace Prolog
{
/*
----------------
PredicateStorage
----------------
*/
public class PredicateStorage
{
private Hashtable predTable;
private Hashtable predefineds;
private Hashtable moduleName;
private Hashtable definedInCurrFile;
private Hashtable isDiscontiguous;
private Hashtable actionWhenUndefined;
private string prevIndex = null;
private bool allDiscontiguous = false; // should normally not be used (used for messy code from others)
private const string SLASH = "/";
public PredicateStorage()
{
predTable = new Hashtable();
predefineds = new Hashtable();
moduleName = new Hashtable();
definedInCurrFile = new Hashtable();
isDiscontiguous = new Hashtable();
actionWhenUndefined = new Hashtable();
}
public void Reset()
{
predTable.Clear();
predefineds.Clear();
moduleName.Clear();
definedInCurrFile.Clear();
isDiscontiguous.Clear();
actionWhenUndefined.Clear();
prevIndex = null;
}
public PredicateDescr this[string key]
{
get { return (PredicateDescr)predTable[key]; }
set { predTable[key] = value; }
}
public bool IsPredefined(string key)
{
return predefineds.Contains(key);
}
public void SetFailWhenUndefined(string f, int a)
{
actionWhenUndefined[Term.Key(f, a)] = "true";
}
public UndefAction ActionWhenUndefined(string f, int a)
{
object o;
o = actionWhenUndefined[Term.Key(f, a)];
return (o == null) ? UndefAction.unknown : (UndefAction)o;
}
#if persistent
public bool IsPersistent (Term t)
{
PredicateDescr pd = (PredicateDescr)predTable [t.KbKey];
return (pd == null) ? false : pd is PersistentPredDescr;
}
public bool IsPersistent (string functor, int arity)
{
PredicateDescr pd = (PredicateDescr)predTable [Term.Key (functor, arity)];
return (pd == null) ? false : pd is PersistentPredDescr;
}
#endif
public bool IsPredicate(string functor, int arity)
{
return this.Contains(Term.Key(functor, arity));
}
#if debugging
public bool SetSpy(bool enabled, string functor, int arity, Term list)
{
SpyPort ports;
if (list == null)
ports = SpyPort.full;
else
{
ports = SpyPort.none;
string s;
while (list.Arity == 2)
{
s = list.Arg(0).Functor;
try
{
ports |= (SpyPort)Enum.Parse(typeof(SpyPort), s);
}
catch
{
PrologIO.Error("Illegal value '{0}'", s);
}
list = list.Arg(1);
}
}
PredicateDescr pd;
if (arity == -1)
{
bool found = false;
foreach (DictionaryEntry de in predTable)
if ((pd = (PredicateDescr)de.Value).Name == functor)
{
found = true;
pd.SetSpy(enabled, pd.Name, pd.Arity, ports, !enabled);
}
if (!found) PrologIO.Error("Predicate does not exist: {0}", functor);
return found;
}
else
{
if ((pd = (PredicateDescr)predTable[Term.Key(functor, arity)]) == null)
{
PrologIO.Error("Predicate does not exist: {0}/{1}", functor, arity);
return false;
}
pd.SetSpy(enabled, functor, arity, ports, !enabled);
}
return true;
}
public void SetNoSpyAll()
{
PredicateDescr pd;
foreach (DictionaryEntry de in predTable)
((pd = (PredicateDescr)de.Value)).SetSpy(false, pd.Name, pd.Arity, SpyPort.none, false);
}
public void ShowSpypoints()
{
foreach (DictionaryEntry de in predTable)
((PredicateDescr)de.Value).ShowSpypoint();
}
#endif
private PredicateDescr SetClauseList(PredEnum predType, string f, int a, ClauseNode c)
{
string key = Term.Key(f, a);
PredicateDescr pd = this[key];
if (pd == null)
{
switch (predType)
{
#if persistent
case PredEnum.table:
this [key] = pd = new TablePredDescr (Globals.ConsultModuleName, Globals.ConsultFileName, f, a, c);
break;
case PredEnum.selproc:
this [key] = pd = new ProcedurePredDescr (Globals.ConsultModuleName, Globals.ConsultFileName, f, a, c, true);
break;
case PredEnum.execproc:
this [key] = pd = new ProcedurePredDescr (Globals.ConsultModuleName, Globals.ConsultFileName, f, a, c, false);
break;
#endif
default:
if (f.Contains("::"))
{
String[] parts = Regex.Split(f, "::");
double prob = Double.Parse(parts[0], Globals.CI);
long timestamp = 0L;
string clauseText = "";
if (parts.Length == 3)
{
if ("T".Equals(parts[1]))
{
timestamp = DateTime.Now.Ticks;
}
else
{
timestamp = DateTime.Now.Ticks + long.Parse(parts[1]) *10000000;
}
clauseText = parts[2];
}
else
{
clauseText = parts[1];
}
Parser np = new Parser(null);
np.StreamIn = clauseText + ".";
Term goalTerm = np.QueryNode.Term;
key = Term.Key(goalTerm.Functor, goalTerm.Arity);
ClauseNode cn = new ClauseNode(goalTerm, null, prob, timestamp);
if (this[key] == null)
{
this[key] = pd = new PredicateDescr(Globals.ConsultModuleName, Globals.ConsultFileName, goalTerm.Functor, goalTerm.Arity, cn);
}
else
{
pd = this[key];
pd.AppendToClauseList(cn);
}
}
else
{
this[key] = pd = new PredicateDescr(Globals.ConsultModuleName, Globals.ConsultFileName, f, a, c);
}
break;
}
}
else
pd.SetClauseListHead(c);
pd.AdjustClauseListEnd();
return pd;
}
public bool Contains(string key)
{
return (this[key] != null);
}
public override string ToString()
{
return predTable.ToString();
}
public int Consult(string fName)
{
Parser saveCurrentParser = Globals.CurrentParser;
Parser parser = Globals.CurrentParser = new Parser(this);
allDiscontiguous = false;
try
{
prevIndex = null;
definedInCurrFile.Clear();
isDiscontiguous.Clear();
actionWhenUndefined.Clear();
Globals.ConsultFileName = fName.ToLower();
Globals.ConsultModuleName = null;
parser.Prefix = "&program";
PrologIO.Write("--- Consulting {0} ... ", fName);
parser.LoadFromFile(fName);
PrologIO.WriteLine("{0} lines read", parser.LineCount);
}
finally
{
Globals.ConsultFileName = null;
Globals.ConsultModuleName = null;
Globals.CurrentParser = saveCurrentParser;
}
return parser.LineCount;
}
public void AddPredefined(ClauseNode clause)
{
Term Term = clause.Term;
string key = Term.KbKey;
PredicateDescr pd = this[key];
if (pd == null)
{
predefineds[key] = "true"; // any value != null will do
SetClauseList(PredEnum.session, Term.Functor, Term.Arity, clause); // create a pd
}
else if (prevIndex != null && key != prevIndex)
PrologIO.Error("Definition for predefined predicate '{0}' must be contiguous", Term.Index);
else
pd.AppendToClauseList(clause);
prevIndex = key;
}
public void SetDiscontiguous(Term t)
{
if (t == null || t.Functor != SLASH || !t.Arg(0).IsAtom || !t.Arg(1).IsInteger)
PrologIO.Error("Illegal or missing argument '{0}' for discontiguous/1", t);
// The predicate descriptor does not yet exist (and may even not come at all!)
string key = Term.Key(t.Arg(0).Functor, t.Arg(1).Functor);
//Console.WriteLine ("--- Setting discontiguous for {0} in definingFile {1}", key, Globals.ConsultFileName);
isDiscontiguous[key] = "true";
}
public void SetDiscontiguous(bool mode)
{
allDiscontiguous = mode;
}
public enum UndefAction { fail, succeed, warning, error, unknown }
public bool SetUndefPredAction(Term t, bool err)
{
Term pred = null;
Term action = null;
ArrayList args = null;
string msg;
bool result = true;
t.IsPacked = false;
if (t != null) args = t.ArgumentsToArrayList(false);
bool OK =
t != null &&
(args.Count == 2) &&
(pred = (Term)args[0]).Arity == 2 &&
pred.Functor == SLASH &&
pred.Arg(0).IsAtom &&
pred.Arg(1).IsInteger;
if (!OK)
{
result = false;
msg = string.Format("Bad first argument '{0}' for undef_pred_action( <predicate>/<arity>, ...)", t.Arg(0));
if (err) PrologIO.Error(msg); else PrologIO.Warning(msg);
}
OK =
(action = (Term)args[1]) != null &&
(action.Functor == "fail" ||
// action.Functor == "succeed" ||
action.Functor == "error" ||
action.Functor == "warning");
if (!OK)
{
result = false;
msg = string.Format("Bad second argument '{0}' for undef_pred_action( ..., fail/succeed/warning)", action);
if (err) PrologIO.Error(msg); else PrologIO.Warning(msg);
}
if (result)
{
string key = Term.Key(pred.Arg(0).Functor, pred.Arg(1).Functor);
actionWhenUndefined[key] = (UndefAction)Enum.Parse(typeof(UndefAction), action.Functor, false);
}
return result;
}
private enum PredEnum { session, table, execproc, selproc } // table and view are treated identically
#if persistent
public void SetPersistent (Term t)
{
Term pred = null;
Term db_info = null; // table( <name>) or procedure( <name>, <executable/selectable>)
bool isTable = false;
bool isExec = false; // executable stored procedure (as opposed to selectable)
Term dbEntity = null;
DbLogin dbLogin = null;
ArrayList args = null;
PredEnum predType;
t.IsPacked = false;
if (t != null) args = t.ArgumentsToArrayList (false);
//for (int i = 0; i < args.Count; i++) Console.WriteLine ("args [{0}] = {1}", i, args [i]);
bool OK =
t != null &&
(args.Count == 2 || args.Count == 5) &&
(pred = (Term)args [0]).Arity == 2 &&
pred.Functor == SLASH &&
pred.Arg (0).IsAtom &&
pred.Arg (1).IsInteger;
if (!OK)
IO.Error ("Bad first argument '{0}' for persistent( <predicate>/<arity>, ...)", t.Arg (0));
OK =
(db_info = (Term)args [1]) != null &&
( (isTable = (db_info.Functor == "table" || db_info.Functor == "view")) ||
db_info.Functor == "procedure" ||
db_info.Functor == "proc") &&
db_info.Arity > 0 &&
( (dbEntity = db_info.Arg (0)).IsAtom || dbEntity.IsString );
if (!OK)
IO.Error ("Bad second argument '{0}' for persistent( ..., table/view/procedure(...))", db_info);
if (isTable)
{
if (db_info.Arity != 1)
IO.Error ("Bad second argument '{0}' for persistent( ..., table/view( <db_entity_name>))", db_info);
predType = PredEnum.table;
}
else
{
string invocation;
OK = (db_info.Arity == 2) && // procedure( <name>, <executable/selectable>)
( (isExec = ((invocation = db_info.Arg (1).Functor) == "executable" || invocation == "exec")) ||
invocation == "selectable" || invocation == "select" );
if (!OK)
IO.Error ("Bad second argument '{0}' for persistent( ..., procedure( <db_entity_name>, [selectable|executable]))", t.Arg (1));
predType = isExec ? PredEnum.execproc : PredEnum.selproc;
}
string functor = pred.Arg (0).Functor;
int arity = Convert.ToInt32 (pred.Arg (1).Functor);
string index = Term.Key (functor, arity);
if (predefineds [index] != null)
IO.Error ("Predefined predicate '{0}/{1}' cannot be declared as persistent", functor, arity);
if (args.Count == 5)
{
for (int i = 2; i <= 4; i++)
if (!(((Term)args [i]).IsAtom || ((Term)args [i]).IsString))
IO.Error ("Argument '{0}' not an atom or string", (Term)args [i]);
dbLogin = new DbLogin (((Term)args [2]).Functor, ((Term)args [3]).Functor, ((Term)args [4]).Functor);
}
PredicateDescr pd = this [index];
if (pd != null) // apparently already defined
{
string definingFile = (pd.DefiningFile == Globals.ConsultFileName) ? "this file" : pd.DefiningFile;
if (!(pd is PersistentPredDescr))
IO.Error ("Predicate '{0}/{1}' cannot be declared as persistent (predicate defined in {2})", functor, arity, definingFile);
}
pd = SetClauseList (predType, functor, arity, null);
((PersistentPredDescr)pd).DbEntity = dbEntity.Functor;
((PersistentPredDescr)pd).DbLogin = dbLogin;
}
public void SetUnpersistent (Term t)
{
Term s;
if ( t == null ||
t.Arity != 1 ||
(s = t.Arg (0)).Arity != 2 ||
s.Functor != SLASH ||
!s.Arg (0).IsAtom ||
!s.Arg (1).IsInteger )
IO.Error ("Bad argument(s) {0} for unpersistent( <predicate>/<arity>)", t);
string functor = t.Arg (0).Arg (0).Functor; // do not touch case
int arity = Convert.ToInt32 (t.Arg (0).Arg (1).Functor);
string key = Term.Key (functor, arity);
if (predefineds [key] != null)
IO.Error ("Predefined predicate '{0}/{1}' cannot be declared as unpersistent", functor, arity);
PredicateDescr pd = this [key];
if (pd == null || !(pd is PersistentPredDescr))
IO.Error ("Predicate '{0}/{1}' was not declared as persistent", functor, arity);
else
this [key] = null;
}
#else
public void SetPersistent(Term t)
{
PrologIO.Error("Persistent predicates are not available in this version");
}
public void SetUnpersistent(Term t)
{
PrologIO.Error("Persistent predicates are not available in this version");
}
#endif
#if persistent
public Term PersistentInfo (string functor, string arity)
{
string index = Term.Key (functor, arity);
PredicateDescr pd = this [index];
if (pd == null || !(pd is PersistentPredDescr))
{
IO.Error ("Predicate '{0}/{1}' was not declared as persistent", functor, arity);
return null;
}
return ((PersistentPredDescr)pd).PersistentInfo ();
}
#endif
public void SetModuleName(string n)
{
object o = moduleName[n];
string currFile = Globals.ConsultFileName;
if (o == null)
{
moduleName[n] = currFile;
Globals.ConsultModuleName = null;
}
else if ((string)o != currFile)
PrologIO.Error("Module name {0} already declared in definingFile {1}", n, (string)o);
// ACTUAL FUNCTIONALITY TO BE IMPLEMENTED
}
public void AddClause(ClauseNode clause)
{
Term Term = clause.Term;
string key = Term.KbKey;
string index = Term.Index;
if (predefineds.Contains(key))
PrologIO.Error("Modification of predefined predicate {0} not allowed", index);
if (prevIndex == key) // previous clause was for the same predicate
{
PredicateDescr pd = this[key];
pd.AppendToClauseList(clause);
}
else // first predicate or different predicate
{
PredicateDescr pd = this[key];
if (definedInCurrFile[key] == null) // very first clause of this predicate in this file -- reset at start of consult
{
// check whether it was defined as persistent
if (pd != null && pd.DefiningFile != Globals.ConsultFileName)
{
#if persistent
if (pd is PersistentPredDescr)
IO.Error ("No predicate definitions allowed for persistent predicate '{0}'", index);
else
#endif
PrologIO.Error("Predicate '{0}' is already defined in {1}", index, pd.DefiningFile);
}
definedInCurrFile[key] = true;
pd = SetClauseList(PredEnum.session, Term.Functor, Term.Arity, clause); // implicitly erases all previous definitions
pd.IsDiscontiguous = (isDiscontiguous[key] != null || allDiscontiguous);
// NOTE: SetClauseListHead does not reset all remaining fields in the possibly existing PredicateDescr -- look at this later
prevIndex = key;
}
else // not the first clause. First may be from another definingFile (which is an error). If from same, IsDiscontiguous must hold
{
if (pd.IsDiscontiguous)
{
if (pd.DefiningFile == Globals.ConsultFileName)
pd.AppendToClauseList(clause);
else // OK
PrologIO.Error("Discontiguous predicate {0} must be in one file (also found in {1})", index, pd.DefiningFile);
}
else if (pd.DefiningFile == Globals.ConsultFileName) // error
PrologIO.Error("Predicate '{0}' occurs discontiguously but is not declared as such", index);
else
PrologIO.Error("Predicate '{0}' is already defined in {1}", index, pd.DefiningFile);
}
}
}
public void Assert(Term assertion, bool asserta)
{
assertion = assertion.CleanCopy(); // make a fresh copy
Term head;
TermNode body = null;
if (assertion.Functor == Parser.IMPLIES)
{
head = assertion.Arg(0);
body = assertion.Arg(1).ToGoalList();
}
else
head = assertion;
if (head.IsVar) PrologIO.Error("Cannot assert a variable as predicate head");
string key = head.KbKey;
// A predefined predicate (which may also be defined as operator) may not be redefined.
// Operators ':-', ',', ';', '-->', '->' (precedence >= 1000) may also not be redefined.
if (predefineds.Contains(key) || (head.Precedence >= 1000))
PrologIO.Error("assert cannot be applied to predefined predicate or system operator {0}", assertion.Index);
PredicateDescr pd = (PredicateDescr)predTable[key];
#if persistent
if (pd != null && pd is PersistentPredDescr)
{
((PersistentPredDescr)pd).Assert (head);
return;
}
#endif
ClauseNode newC = new ClauseNode(head, body);
if (pd == null) // first head
{
SetClauseList(PredEnum.session, head.Functor, head.Arity, newC);
ResolveIndices();
}
else if (asserta) // at beginning
{
newC.NextClause = pd.ClauseNode; // pd.ClauseNode may be null
SetClauseList(PredEnum.session, head.Functor, head.Arity, newC);
#if arg1index
pd.CreateFirstArgIndex (); // re-create
#endif
}
else // at end
{
pd.AppendToClauseList(newC);
#if arg1index
pd.CreateFirstArgIndex (); // re-create
#endif
}
}
public bool Retract(Term t, VarStack varStack, Term where)
{
string key = t.KbKey;
if (predefineds.Contains(key))
PrologIO.Error("retract of predefined predicate {0} not allowed", key);
PredicateDescr pd = this[key];
if (pd == null) return false;
#if persistent
if (pd is PersistentPredDescr)
{
((PersistentPredDescr)pd).Retract (t, varStack, where);
return true;
}
#endif
ClauseNode c = pd.GetClauseList(null, null);
ClauseNode prevc = null;
Term cleanTerm;
int top;
while (c != null)
{
cleanTerm = c.Term.CleanCopy();
top = varStack.Count;
if (cleanTerm.Unify(t, varStack)) // match found -- remove this term from the chain
{
if (prevc == null) // remove first clause
{
if (c.NextClause == null) // we are about to remove the last remaining clause for this predicate
{
predTable.Remove(key); // ... so remove its PredicateDescr as well
#if arg1index
pd.CreateFirstArgIndex (); // re-create
#endif
ResolveIndices();
}
else
pd.SetClauseListHead(c.NextClause);
}
else // not the first
{
prevc.NextClause = c.NextClause;
prevc = c;
pd.AdjustClauseListEnd();
#if arg1index
pd.CreateFirstArgIndex (); // re-create
#endif
}
return true; // possible bindings must stay intact (e.g. if p(a) then retract(p(X)) yields X=a)
}
Term s;
for (int i = varStack.Count - top; i > 0; i--) // unbind all vars that got bound by the above Unification
{
s = (Term)varStack.Pop();
s.Unbind();
}
prevc = c;
c = c.NextClause;
}
ResolveIndices();
return false;
}
public bool RetractAll(Term t, VarStack varStack) // should *always* return true ?????
{
// remark: first-argument indexing is not affected by deleting clauses
string key = t.KbKey;
if (predefineds.Contains(key))
PrologIO.Error("retract of predefined predicate {0} not allowed", key);
PredicateDescr pd = this[key];
if (pd == null) return true;
#if persistent
if (pd is PersistentPredDescr)
{
((PersistentPredDescr)pd).Retract (t, varStack, null);
return true; /////////////JPO persistent retract always to succeed ????
}
#endif
ClauseNode c = pd.GetClauseList(null, null);
ClauseNode prevc = null;
bool match = false;
while (c != null)
{
Term cleanTerm = c.Term.CleanCopy();
if (cleanTerm.Unifiable(t, varStack)) // match found -- remove this term from the chain
{
match = true; // to indicate that at least one term was found
if (prevc == null) // remove first clause
{
if (c.NextClause == null) // we are about to remove the last remaining clause for this predicate
{
predTable.Remove(key); // ... so remove its PredicateDescr as well
break;
}
else
pd.SetClauseListHead(c.NextClause);
}
else // not the first
{
prevc.NextClause = c.NextClause;
prevc = c;
}
}
else
prevc = c;
c = c.NextClause;
}
if (match)
{
#if arg1index
pd.DestroyFirstArgIndex (); // rebuild by ResolveIndices()
#endif
pd.AdjustClauseListEnd();
ResolveIndices();
}
return true;
}
public bool Abolish(string functor, string arity)
{
string key = Term.Key(functor, arity);
if (predefineds.Contains(key))
PrologIO.Error("abolish of predefined predicate '{0}/{1}' not allowed", functor, arity);
PredicateDescr pd = this[key];
if (pd == null) return false;
#if persistent
if (pd is PersistentPredDescr)
IO.Error ("abolish of persistent predicate '{0}/{1}' not allowed", functor, arity);
#endif
predTable.Remove(key);
#if arg1index
pd.DestroyFirstArgIndex (); // rebuild by ResolveIndices()
#endif
ResolveIndices();
return true;
}
private bool ListClause(PredicateDescr pd, string functor, int arity, int seqno)
{
ClauseNode clause = null;
string details;
#if persistent
if (pd is PersistentPredDescr)
{
details = "persistent, details: " + pd.DefiningFile;
}
else
#endif
{
if ((clause = pd.GetClauseList(null, null)) == null) return false;
details = "source: " + pd.DefiningFile;
}
#if arg1index
if (pd.IsFirstArgIndexed) details += "; arg1-indexed (jump points marked with '.')";
#endif
Console.WriteLine("\n{0}/{1}: ({2}) {3}", functor, arity,
details,
((seqno == 1) ? "" : ("(" + seqno.ToString() + ")")));
while (clause != null)
{
TermNode next;
#if arg1index
// prefix a clause that is pointed to by first-argument indexing with '.'
Console.Write (" {0}{1}", (pd.IsFirstArgMarked (clause))?".":" ", clause.Term);
#else
Console.Write(" {0}", clause.Term);
#endif
if ((next = clause.NextNode) != null)
{
BI builtinId = next.BuiltinId;
Console.Write(" :-\n{0}", (builtinId == BI.none) ? next.ToString() : builtinId.ToString());
}
Console.WriteLine(".");
clause = clause.NextClause;
}
return true;
}
public bool ListAll(string functor, int arity, bool showPredefined, bool showUserDefined)
{
bool result = false; // no such predicate assumed
PredicateDescr pd;
SortedList sl = new SortedList(); // for sorting the predicates alphabetically
foreach (DictionaryEntry de in predTable)
{
pd = (PredicateDescr)de.Value;
if (functor == null || functor == pd.Name)
{
bool isPredefined = IsPredefined((string)de.Key);
if ((showPredefined && showUserDefined ||
showPredefined && isPredefined ||
showUserDefined && !isPredefined) &&
(arity == -1 || arity == pd.Arity))
sl.Add(pd.Name + pd.Arity.ToString(), pd);
}
}
int seqNo = 0;
foreach (DictionaryEntry de in sl)
result = ListClause(pd = (PredicateDescr)de.Value, pd.Name, pd.Arity, ++seqNo) || result;
return result;
}
/*
---------------------------------------------
ResolveIndices (functor/arity-key resolution)
---------------------------------------------
*/
public void ResolveIndices()
{
PredicateDescr pd;
foreach (DictionaryEntry de in predTable) // traverse all program predicates
{
ResolveIndex(pd = (PredicateDescr)de.Value);
#if arg1index
pd.CreateFirstArgIndex (); // check whether first-argument indexing is applicable, and build the index if so
#endif
}
}
private void ResolveIndex(PredicateDescr pd)
{
#if persistent
if (pd is PersistentPredDescr) return; // does not have a clauseTerm
#endif
ClauseNode clause = pd.GetClauseList(null, null);
while (clause != null) // iterate over all clauses of this predicate. ClauseNode.Term contains predicate clauseHead
{
Term clauseHead = clause.Term; // clause = clauseHead :- clauseTerm*
TermNode clauseTerm = clause.NextNode;
while (clauseTerm != null) // non-facts only. Iterate over all clauseTerm-terms t of this clause
{
if (clauseTerm.BuiltinId == BI.none) clauseTerm.PredDescr = this[clauseTerm.Term.KbKey];
// builtins (>=0) are handled differently (in Execute ())
clauseTerm = clauseTerm.NextNode;
}
clause = clause.NextClause;
}
return;
}
public void FindUndefineds()
{
SortedList sd = new SortedList();
foreach (DictionaryEntry de in predTable) FindUndefined(sd, (PredicateDescr)de.Value);
PrologIO.WriteLine("The following predicates are undefined:");
foreach (DictionaryEntry de in sd) Console.WriteLine(" {0}", de.Key);
}
private void FindUndefined(SortedList sd, PredicateDescr pd)
{
#if persistent
if (pd is PersistentPredDescr) return;
#endif
ClauseNode clause = pd.GetClauseList(null, null);
Term clauseHead;
TermNode clauseTerm;
while (clause != null) // iterate over all clauses of this predicate
{
clauseHead = clause.Term;
clauseTerm = clause.NextNode;
while (clauseTerm != null) // non-facts only. Iterate over all clauseTerm-terms t of this clause
{
if (clauseTerm.BuiltinId == BI.none && clauseTerm.PredDescr == null) sd[clauseTerm.Term.Index] = null;
clauseTerm = clauseTerm.NextNode;
}
clause = clause.NextClause;
}
return;
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CoinAPI.WebSocket.V1;
using CoinAPI.WebSocket.V1.DataModels;
using Newtonsoft.Json;
using NodaTime;
using QuantConnect.Configuration;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Interfaces;
using QuantConnect.Lean.Engine.DataFeeds;
using QuantConnect.Lean.Engine.HistoricalData;
using QuantConnect.Logging;
using QuantConnect.Packets;
using QuantConnect.ToolBox.CoinApi.Messages;
using QuantConnect.Util;
using RestSharp;
using HistoryRequest = QuantConnect.Data.HistoryRequest;
namespace QuantConnect.ToolBox.CoinApi
{
/// <summary>
/// An implementation of <see cref="IDataQueueHandler"/> for CoinAPI
/// </summary>
public class CoinApiDataQueueHandler : SynchronizingHistoryProvider, IDataQueueHandler
{
protected int HistoricalDataPerRequestLimit = 10000;
private static readonly Dictionary<Resolution, string> _ResolutionToCoinApiPeriodMappings = new Dictionary<Resolution, string>
{
{ Resolution.Second, "1SEC"},
{ Resolution.Minute, "1MIN" },
{ Resolution.Hour, "1HRS" },
{ Resolution.Daily, "1DAY" },
};
private readonly string _apiKey = Config.Get("coinapi-api-key");
private readonly string[] _streamingDataType;
private readonly CoinApiWsClient _client;
private readonly object _locker = new object();
private ConcurrentDictionary<string, Symbol> _symbolCache = new ConcurrentDictionary<string, Symbol>();
private readonly CoinApiSymbolMapper _symbolMapper = new CoinApiSymbolMapper();
private readonly IDataAggregator _dataAggregator;
private readonly EventBasedDataQueueHandlerSubscriptionManager _subscriptionManager;
private readonly TimeSpan _subscribeDelay = TimeSpan.FromMilliseconds(250);
private readonly object _lockerSubscriptions = new object();
private DateTime _lastSubscribeRequestUtcTime = DateTime.MinValue;
private bool _subscriptionsPending;
private readonly TimeSpan _minimumTimeBetweenHelloMessages = TimeSpan.FromSeconds(5);
private DateTime _nextHelloMessageUtcTime = DateTime.MinValue;
private readonly ConcurrentDictionary<string, Tick> _previousQuotes = new ConcurrentDictionary<string, Tick>();
/// <summary>
/// Initializes a new instance of the <see cref="CoinApiDataQueueHandler"/> class
/// </summary>
public CoinApiDataQueueHandler()
{
_dataAggregator = Composer.Instance.GetPart<IDataAggregator>();
if (_dataAggregator == null)
{
_dataAggregator =
Composer.Instance.GetExportedValueByTypeName<IDataAggregator>(Config.Get("data-aggregator", "QuantConnect.Lean.Engine.DataFeeds.AggregationManager"));
}
var product = Config.GetValue<CoinApiProduct>("coinapi-product");
_streamingDataType = product < CoinApiProduct.Streamer
? new[] { "trade" }
: new[] { "trade", "quote" };
Log.Trace($"CoinApiDataQueueHandler(): using plan '{product}'. Available data types: '{string.Join(",", _streamingDataType)}'");
_client = new CoinApiWsClient();
_client.TradeEvent += OnTrade;
_client.QuoteEvent += OnQuote;
_client.Error += OnError;
_subscriptionManager = new EventBasedDataQueueHandlerSubscriptionManager();
_subscriptionManager.SubscribeImpl += (s, t) => Subscribe(s);
_subscriptionManager.UnsubscribeImpl += (s, t) => Unsubscribe(s);
}
/// <summary>
/// Subscribe to the specified configuration
/// </summary>
/// <param name="dataConfig">defines the parameters to subscribe to a data feed</param>
/// <param name="newDataAvailableHandler">handler to be fired on new data available</param>
/// <returns>The new enumerator for this subscription request</returns>
public IEnumerator<BaseData> Subscribe(SubscriptionDataConfig dataConfig, EventHandler newDataAvailableHandler)
{
if (!CanSubscribe(dataConfig.Symbol))
{
return Enumerable.Empty<BaseData>().GetEnumerator();
}
var enumerator = _dataAggregator.Add(dataConfig, newDataAvailableHandler);
_subscriptionManager.Subscribe(dataConfig);
return enumerator;
}
/// <summary>
/// Sets the job we're subscribing for
/// </summary>
/// <param name="job">Job we're subscribing for</param>
public void SetJob(LiveNodePacket job)
{
}
/// <summary>
/// Adds the specified symbols to the subscription
/// </summary>
/// <param name="symbols">The symbols to be added keyed by SecurityType</param>
private bool Subscribe(IEnumerable<Symbol> symbols)
{
ProcessSubscriptionRequest();
return true;
}
/// <summary>
/// Removes the specified configuration
/// </summary>
/// <param name="dataConfig">Subscription config to be removed</param>
public void Unsubscribe(SubscriptionDataConfig dataConfig)
{
_subscriptionManager.Unsubscribe(dataConfig);
_dataAggregator.Remove(dataConfig);
}
/// <summary>
/// Removes the specified symbols to the subscription
/// </summary>
/// <param name="symbols">The symbols to be removed keyed by SecurityType</param>
private bool Unsubscribe(IEnumerable<Symbol> symbols)
{
ProcessSubscriptionRequest();
return true;
}
/// <summary>
/// Returns whether the data provider is connected
/// </summary>
/// <returns>true if the data provider is connected</returns>
public bool IsConnected => true;
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
_client.TradeEvent -= OnTrade;
_client.QuoteEvent -= OnQuote;
_client.Error -= OnError;
_client.Dispose();
_dataAggregator.DisposeSafely();
}
/// <summary>
/// Helper method used in QC backend
/// </summary>
/// <param name="markets">List of LEAN markets (exchanges) to subscribe</param>
public void SubscribeMarkets(List<string> markets)
{
Log.Trace($"CoinApiDataQueueHandler.SubscribeMarkets(): {string.Join(",", markets)}");
// we add '_' to be more precise, for example requesting 'BINANCE' doesn't match 'BINANCEUS'
SendHelloMessage(markets.Select(x => string.Concat(_symbolMapper.GetExchangeId(x.ToLowerInvariant()), "_")));
}
private void ProcessSubscriptionRequest()
{
if (_subscriptionsPending) return;
_lastSubscribeRequestUtcTime = DateTime.UtcNow;
_subscriptionsPending = true;
Task.Run(async () =>
{
while (true)
{
DateTime requestTime;
List<Symbol> symbolsToSubscribe;
lock (_lockerSubscriptions)
{
requestTime = _lastSubscribeRequestUtcTime.Add(_subscribeDelay);
// CoinAPI requires at least 5 seconds between hello messages
if (_nextHelloMessageUtcTime != DateTime.MinValue && requestTime < _nextHelloMessageUtcTime)
{
requestTime = _nextHelloMessageUtcTime;
}
symbolsToSubscribe = _subscriptionManager.GetSubscribedSymbols().ToList();
}
var timeToWait = requestTime - DateTime.UtcNow;
int delayMilliseconds;
if (timeToWait <= TimeSpan.Zero)
{
// minimum delay has passed since last subscribe request, send the Hello message
SubscribeSymbols(symbolsToSubscribe);
lock (_lockerSubscriptions)
{
_lastSubscribeRequestUtcTime = DateTime.UtcNow;
if (_subscriptionManager.GetSubscribedSymbols().Count() == symbolsToSubscribe.Count)
{
// no more subscriptions pending, task finished
_subscriptionsPending = false;
break;
}
}
delayMilliseconds = _subscribeDelay.Milliseconds;
}
else
{
delayMilliseconds = timeToWait.Milliseconds;
}
await Task.Delay(delayMilliseconds).ConfigureAwait(false);
}
});
}
/// <summary>
/// Returns true if we can subscribe to the specified symbol
/// </summary>
private static bool CanSubscribe(Symbol symbol)
{
// ignore unsupported security types
if (symbol.ID.SecurityType != SecurityType.Crypto)
return false;
// ignore universe symbols
return !symbol.Value.Contains("-UNIVERSE-");
}
/// <summary>
/// Subscribes to a list of symbols
/// </summary>
/// <param name="symbolsToSubscribe">The list of symbols to subscribe</param>
private void SubscribeSymbols(List<Symbol> symbolsToSubscribe)
{
Log.Trace($"CoinApiDataQueueHandler.SubscribeSymbols(): {string.Join(",", symbolsToSubscribe)}");
// subscribe to symbols using exact match
SendHelloMessage(symbolsToSubscribe.Select(x => {
try
{
var result = string.Concat(_symbolMapper.GetBrokerageSymbol(x), "$");
return result;
}
catch (Exception e)
{
Log.Error(e);
return null;
}
}).Where(x => x != null));
}
private void SendHelloMessage(IEnumerable<string> subscribeFilter)
{
var list = subscribeFilter.ToList();
if (list.Count == 0)
{
// If we use a null or empty filter in the CoinAPI hello message
// we will be subscribing to all symbols for all active exchanges!
// Only option is requesting an invalid symbol as filter.
list.Add("$no_symbol_requested$");
}
_client.SendHelloMessage(new Hello
{
apikey = Guid.Parse(_apiKey),
heartbeat = true,
subscribe_data_type = _streamingDataType,
subscribe_filter_symbol_id = list.ToArray()
});
_nextHelloMessageUtcTime = DateTime.UtcNow.Add(_minimumTimeBetweenHelloMessages);
}
private void OnTrade(object sender, Trade trade)
{
try
{
var symbol = GetSymbolUsingCache(trade.symbol_id);
if(symbol == null)
{
return;
}
var tick = new Tick(trade.time_exchange, symbol, string.Empty, string.Empty, quantity: trade.size, price: trade.price);
lock (symbol)
{
_dataAggregator.Update(tick);
}
}
catch (Exception e)
{
Log.Error(e);
}
}
private void OnQuote(object sender, Quote quote)
{
try
{
// only emit quote ticks if bid price or ask price changed
Tick previousQuote;
if (!_previousQuotes.TryGetValue(quote.symbol_id, out previousQuote)
|| quote.ask_price != previousQuote.AskPrice
|| quote.bid_price != previousQuote.BidPrice)
{
var symbol = GetSymbolUsingCache(quote.symbol_id);
if (symbol == null)
{
return;
}
var tick = new Tick(quote.time_exchange, symbol, string.Empty, string.Empty,
bidSize: quote.bid_size, bidPrice: quote.bid_price,
askSize: quote.ask_size, askPrice: quote.ask_price);
_previousQuotes[quote.symbol_id] = tick;
lock (symbol)
{
_dataAggregator.Update(tick);
}
}
}
catch (Exception e)
{
Log.Error(e);
}
}
private Symbol GetSymbolUsingCache(string ticker)
{
if(!_symbolCache.TryGetValue(ticker, out Symbol result))
{
try
{
result = _symbolMapper.GetLeanSymbol(ticker, SecurityType.Crypto, string.Empty);
}
catch (Exception e)
{
Log.Error(e);
// we store the null so we don't keep going into the same mapping error
result = null;
}
_symbolCache[ticker] = result;
}
return result;
}
private void OnError(object sender, Exception e)
{
Log.Error(e);
}
#region SynchronizingHistoryProvider
public override void Initialize(HistoryProviderInitializeParameters parameters)
{
// NOP
}
public override IEnumerable<Slice> GetHistory(IEnumerable<HistoryRequest> requests, DateTimeZone sliceTimeZone)
{
var subscriptions = new List<Subscription>();
foreach (var request in requests)
{
var history = GetHistory(request);
var subscription = CreateSubscription(request, history);
subscriptions.Add(subscription);
}
return CreateSliceEnumerableFromSubscriptions(subscriptions, sliceTimeZone);
}
public IEnumerable<BaseData> GetHistory(HistoryRequest historyRequest)
{
if (historyRequest.Symbol.SecurityType != SecurityType.Crypto)
{
Log.Error($"CoinApiDataQueueHandler.GetHistory(): Invalid security type {historyRequest.Symbol.SecurityType}");
yield break;
}
if (historyRequest.Resolution == Resolution.Tick)
{
Log.Error("CoinApiDataQueueHandler.GetHistory(): No historical ticks, only OHLCV timeseries");
yield break;
}
if (historyRequest.DataType == typeof(QuoteBar))
{
Log.Error("CoinApiDataQueueHandler.GetHistory(): No historical QuoteBars , only TradeBars");
yield break;
}
var resolutionTimeSpan = historyRequest.Resolution.ToTimeSpan();
var lastRequestedBarStartTime = historyRequest.EndTimeUtc.RoundDown(resolutionTimeSpan);
var currentStartTime = historyRequest.StartTimeUtc.RoundUp(resolutionTimeSpan);
var currentEndTime = lastRequestedBarStartTime;
// Perform a check of the number of bars requested, this must not exceed a static limit
var dataRequestedCount = (currentEndTime - currentStartTime).Ticks
/ resolutionTimeSpan.Ticks;
if (dataRequestedCount > HistoricalDataPerRequestLimit)
{
currentEndTime = currentStartTime
+ TimeSpan.FromTicks(resolutionTimeSpan.Ticks * HistoricalDataPerRequestLimit);
}
while (currentStartTime < lastRequestedBarStartTime)
{
var coinApiSymbol = _symbolMapper.GetBrokerageSymbol(historyRequest.Symbol);
var coinApiPeriod = _ResolutionToCoinApiPeriodMappings[historyRequest.Resolution];
// Time must be in ISO 8601 format
var coinApiStartTime = currentStartTime.ToStringInvariant("s");
var coinApiEndTime = currentEndTime.ToStringInvariant("s");
// Construct URL for rest request
var baseUrl =
"https://rest.coinapi.io/v1/ohlcv/" +
$"{coinApiSymbol}/history?period_id={coinApiPeriod}&limit={HistoricalDataPerRequestLimit}" +
$"&time_start={coinApiStartTime}&time_end={coinApiEndTime}";
// Execute
var client = new RestClient(baseUrl);
var restRequest = new RestRequest(Method.GET);
restRequest.AddHeader("X-CoinAPI-Key", _apiKey);
var response = client.Execute(restRequest);
// Log the information associated with the API Key's rest call limits.
TraceRestUsage(response);
// Deserialize to array
var coinApiHistoryBars = JsonConvert.DeserializeObject<HistoricalDataMessage[]>(response.Content);
// Can be no historical data for a short period interval
if (!coinApiHistoryBars.Any())
{
Log.Error($"CoinApiDataQueueHandler.GetHistory(): API returned no data for the requested period [{coinApiStartTime} - {coinApiEndTime}] for symbol [{historyRequest.Symbol}]");
continue;
}
foreach (var ohlcv in coinApiHistoryBars)
{
yield return
new TradeBar(ohlcv.TimePeriodStart, historyRequest.Symbol, ohlcv.PriceOpen, ohlcv.PriceHigh,
ohlcv.PriceLow, ohlcv.PriceClose, ohlcv.VolumeTraded, historyRequest.Resolution.ToTimeSpan());
}
currentStartTime = currentEndTime;
currentEndTime += TimeSpan.FromTicks(resolutionTimeSpan.Ticks * HistoricalDataPerRequestLimit);
}
}
#endregion
private void TraceRestUsage(IRestResponse response)
{
var total = GetHttpHeaderValue(response, "x-ratelimit-limit");
var used = GetHttpHeaderValue(response, "x-ratelimit-used");
var remaining = GetHttpHeaderValue(response, "x-ratelimit-remaining");
Log.Trace($"CoinApiDataQueueHandler.TraceRestUsage(): Used {used}, Remaining {remaining}, Total {total}");
}
private string GetHttpHeaderValue(IRestResponse response, string propertyName)
{
return response.Headers
.FirstOrDefault(x => x.Name == propertyName)?
.Value.ToString();
}
// WARNING: here to be called from tests to reduce explicitly the amount of request's output
protected void SetUpHistDataLimit(int limit)
{
HistoricalDataPerRequestLimit = limit;
}
}
}
| |
using UnityEngine;
using System.Collections;
/// <summary>
/// Provides functionality to control the 2D Camera View.
/// </summary>
[ExecuteInEditMode]
public class OTView : MonoBehaviour
{
public delegate void ScreenChangeDelegate();
public ScreenChangeDelegate onScreenChange = null;
//----------------------------------------------------------------------
// Public properties
//----------------------------------------------------------------------
/// <summary>
/// Camera view zoom value. zoom out < 0 > zoom in.
/// </summary>
/// <remarks>
/// Positive zoom values will zoom in where a value of 1 will double the size of your sprites.
/// Negative zoom values will zoom out where a value of -1 will half the size of your sprites.
/// A value of 0 (zero) should display the actual (pixel) size. Note that the actual pizel size
/// will only be pixel perfect when <see cref="OTView.alwaysPixelPerfect"/> is set to true or when the current
/// resolution is the <see cref="OTView.pixelPerfectResolution"/>.
/// </remarks>
///
public float zoom
{
get
{
return _zoom;
}
set
{
_zoom = value;
Update();
}
}
/// <summary>
/// Current view position (x/y).
/// </summary>
/// <remarks>
/// You can use the view's position to scroll or move the camera/view around in your
/// 2D world.
/// </remarks>
public Vector2 position
{
get
{
return _position;
}
set
{
_position = value;
}
}
/// <summary>
/// Current camera view rotation in degrees.
/// </summary>
public float rotation
{
get
{
return _rotation;
}
set
{
_rotation = value;
}
}
/// <summary>
/// Pixel perfect indicator
/// </summary>
/// <remarks>
/// If alwaysPixelPerfect is set to true, sprites will always be 'pixel perfect' ignoring the
/// current (device) resolution. If you would like to use a base resolution ( that is pixel
/// perfect ) and zoom your view depending on the current resolution, set this to false and
/// set your pixelResolution to the resolution on which the sprites should be pixel perfect.
/// <br></br><br></br>
/// <strong style="color:red" >!IMPORTANT</strong> To use pixel perfect sprites Mip Mapping
/// and texture compression should be disabled.
/// </remarks>
public bool alwaysPixelPerfect
{
get
{
return _alwaysPixelPerfect;
}
set
{
_alwaysPixelPerfect = value;
Update();
}
}
/// <summary>
/// Resolution on which sprites will be pixel perfect
/// </summary>
/// <remarks>
/// Use this to set the resolution on which spritys should be pixel perfect. This setting will
/// only be active when the alwaysPixelPerfect setting is set to false. Only the Y (height) value
/// of the resultion is used to calculate the zooming factor.
/// <br></br><br></br>
/// <strong style="color:red" >!IMPORTANT</strong> To use pixel perfect sprites Mip Mapping
/// and texture compression should be disabled.
/// </remarks>
public Vector2 pixelPerfectResolution
{
get
{
return _pixelPerfectResolution;
}
set
{
_pixelPerfectResolution = value;
if (!alwaysPixelPerfect) Update();
}
}
OTObject movementObject = null;
/// <summary>
/// Target object's position will followed.
/// </summary>
public GameObject movementTarget
{
get
{
return _movementTarget;
}
set
{
_movementTarget = value;
if (value!=null)
movementObject = movementTarget.GetComponent<OTObject>();
Update();
}
}
/// <summary>
/// Target object's rotation will be followed.
/// </summary>
public GameObject rotationTarget
{
get
{
return _rotationTarget;
}
set
{
_rotationTarget = value;
Update();
}
}
/// <summary>
/// World boundary for the view (camera)
/// </summary>
/// <remarks>
/// If world boundary is set this will restrict the camera
/// from leaving this boundary box. Setting this to Rect(0,0,0,0)
/// will impose no boundary restriction.
/// This is specified in pixel (world space) coordinates.
/// </remarks>
public Rect worldBounds
{
get
{
return _worldBounds;
}
set
{
_worldBounds = value;
Update();
}
}
public Camera cameraOverride = null;
/// <summary>
/// Camera object belonging to this this view.
/// </summary>
new public Camera camera
{
get
{
return _camera;
}
}
private bool IntersectRect(Rect r1, Rect r2)
{
return !( r2.xMin > r1.xMax
|| r2.xMax < r1.xMin
|| r2.yMin > r1.yMax
|| r2.yMax < r1.yMin
);
}
/// <summary>
/// Checks if a specific 2D coordinate is in view.
/// </summary>
public bool Contains(Vector2 v)
{
return IntersectRect(worldRect, new Rect(v.x,v.y,0,0));
}
/// <summary>
/// Checks if a specific object is in view.
/// </summary>
public bool Contains(OTObject o)
{
return IntersectRect(worldRect, o.rect);
}
/// <summary>
/// Position of the mousepointer in world coordinates.
/// </summary>
public Vector2 mouseWorldPosition
{
get
{
Vector3 wp = camera.ScreenToWorldPoint(Input.mousePosition);
return ((OT.world == OT.World.WorldSide2D)?(Vector2)wp:new Vector2(wp.x,wp.z));
}
}
/// <summary>
/// Position of the mousepointer in view coordinates.
/// </summary>
public Vector2 mouseViewPosition
{
get
{
return camera.ScreenToViewportPoint(Input.mousePosition);
}
}
/// <summary>
/// This view's rectangle in world coordinates.
/// </summary>
public Rect worldRect
{
get
{
return _worldRect;
}
}
private Camera _camera
{
get
{
if (cameraOverride!=null)
return cameraOverride;
else
if (OT.inputCameras[0]!=null)
return OT.inputCameras[0];
else
return Camera.main;
}
}
//----------------------------------------------------------------------
public float _zoom = 0f;
public Vector2 _position = Vector2.zero;
public float _rotation = 0;
public GameObject _movementTarget = null;
public GameObject _rotationTarget = null;
public Rect _worldBounds = new Rect(0, 0, 0, 0);
public bool _alwaysPixelPerfect = true;
public Vector2 _pixelPerfectResolution = new Vector2(1024, 768);
/// <summary>
/// Overrides the Orthello controlled Orthographic size of the camera
/// </summary>
public float customSize = 0;
/// <summary>
/// If checked will draw world bounds and view rectangle
/// </summary>
public bool drawGizmos = false;
/// <summary>
/// Color of view gizmos in scene
/// </summary>
public Color gizmosColor = Color.yellow;
/// <summary>
/// Z depth of the camera position
/// </summary>
public int cameraDepth = -1001;
/// <summary>
/// Far clipping range of the camera
/// </summary>
public int cameraRange = 2001;
public float sizeFactor
{
get
{
return sizeFact;
}
}
private float sizeFact = 1;
private Vector2 _position_ = Vector2.zero;
private float _zoom_ = 0;
private float _rotation_ = 0;
private Vector2 _currentScreen = Vector2.zero;
float resSize
{
get
{
if (customSize == 0)
{
if (alwaysPixelPerfect)
return (float)Screen.height / 2f;
else
{
float arDef = pixelPerfectResolution.x/pixelPerfectResolution.y;
float arCur = (float)Screen.width/(float)Screen.height;
if (arCur < arDef)
return (float)Screen.height / 2f * (pixelPerfectResolution.x / (float)Screen.width);
else
return (float)Screen.height / 2f * (pixelPerfectResolution.y / (float)Screen.height);
}
}
else
return customSize;
}
}
public void InitView()
{
SetCamera();
}
void SetCamera()
{
if (OT.world2D)
{
if (!camera.orthographic)
camera.orthographic = true;
CheckViewSize();
if (camera.near!=0)
camera.near = 0;
if (camera.far!= cameraRange)
camera.far = cameraRange;
if (OT.world == OT.World.WorldSide2D)
{
cameraDepth = -1000;
if (!camera.transform.rotation.Equals(Quaternion.identity))
camera.transform.rotation = Quaternion.identity;
if (!camera.transform.position.Equals(new Vector3(_position.x, _position.y, cameraDepth)))
camera.transform.position = new Vector3(_position.x, _position.y, cameraDepth);
}
else
{
cameraDepth = 1000;
if (!camera.transform.rotation.Equals(Quaternion.Euler(new Vector3(90,0,0))))
camera.transform.rotation = Quaternion.Euler(new Vector3(90,0,0));
if (!camera.transform.position.Equals(new Vector3(_position.x, cameraDepth, _position.y)))
camera.transform.position = new Vector3(_position.x, cameraDepth, _position.y);
}
if (!this.transform.position.Equals(camera.transform.position))
this.transform.position = camera.transform.position;
if (!this.transform.rotation.Equals(camera.transform.rotation))
this.transform.rotation = camera.transform.rotation;
}
else
drawGizmos = false;
}
float _customSize;
void Start()
{
_customSize = customSize;
_position_ = _position;
_rotation_ = _rotation;
_currentScreen = new Vector2(Screen.width,Screen.height);
_zoom_ = _zoom;
if (customSize != 0)
{
sizeFact = (customSize / pixelPerfectResolution.y) * 2f;
if (Application.isPlaying && alwaysPixelPerfect)
{
customSize *= Screen.height / pixelPerfectResolution.y;
_customSize = customSize;
}
}
else
sizeFact = 1;
if (movementTarget!=null)
movementObject = movementTarget.GetComponent<OTObject>();
GetWorldRect();
recordPrefab = true;
}
private Rect _worldRect;
Vector2 p1;
Vector2 p2;
Vector2 p3;
Vector2 p4;
Vector2 bl;
Vector2 tr;
void GetWorldRect()
{
if (OT.world == OT.World.World3D)
{
_worldRect = new Rect(0,0,0,0);
return;
}
Vector3 vs = camera.ScreenToWorldPoint(new Vector2(0, 0));
if (OT.world == OT.World.WorldSide2D)
p1 = vs;
else
p1 = new Vector2(vs.x,vs.z);
vs = camera.ScreenToWorldPoint(new Vector2(0, camera.pixelHeight));
if (OT.world == OT.World.WorldSide2D)
p2 = vs;
else
p2 = new Vector2(vs.x,vs.z);
vs = camera.ScreenToWorldPoint(new Vector2(camera.pixelWidth, 0));
if (OT.world == OT.World.WorldSide2D)
p3 = vs;
else
p3 = new Vector2(vs.x,vs.z);
vs = camera.ScreenToWorldPoint(new Vector2(camera.pixelWidth, camera.pixelHeight));
if (OT.world == OT.World.WorldSide2D)
p4 = vs;
else
p4 = new Vector2(vs.x,vs.z);
float x1, x2, y1, y2;
x1 = p1.x; x2 = p1.x;
y1 = p1.y; y2 = p1.y;
if (p2.x < x1) x1 = p2.x;
if (p2.y < y1) y1 = p2.y;
if (p2.x > x2) x2 = p2.x;
if (p2.y > y2) y2 = p2.y;
if (p3.x < x1) x1 = p3.x;
if (p3.y < y1) y1 = p3.y;
if (p3.x > x2) x2 = p3.x;
if (p3.y > y2) y2 = p3.y;
if (p4.x < x1) x1 = p4.x;
if (p4.y < y1) y1 = p4.y;
if (p4.x > x2) x2 = p4.x;
if (p4.y > y2) y2 = p4.y;
bl = new Vector2(x1, y1);
tr = new Vector2(x2, y2);
// Vector2 br = camera.ViewportToWorldPoint(new Vector2(1, 1));
Vector2 si = new Vector2(tr.x - bl.x, tr.y - bl.y);
_worldRect = new Rect(
camera.transform.position.x - si.x / 2,
((OT.world == OT.World.WorldSide2D)?camera.transform.position.y:camera.transform.position.z) - si.y / 2,
si.x,
si.y);
}
void AdjustToWorldBounds()
{
if (worldBounds.width != 0)
{
Vector2 pos = position;
bool clampX = (Mathf.Abs(worldBounds.width) >= Mathf.Abs(worldRect.width));
if (clampX)
{
float minX = _worldBounds.xMin;
float maxX = _worldBounds.xMax;
if (maxX < minX)
{
float tmp = minX;
minX = maxX;
maxX = tmp;
}
minX += Mathf.Abs(worldRect.width / 2);
maxX -= Mathf.Abs(worldRect.width / 2);
pos.x = Mathf.Clamp(pos.x, minX, maxX);
}
else
pos.x = (worldRect.xMin + worldRect.width / 2);
bool clampY = (Mathf.Abs(worldBounds.height) >= Mathf.Abs(worldRect.height));
if (clampY)
{
float minY = _worldBounds.yMin;
float maxY = _worldBounds.yMax;
if (maxY < minY)
{
float tmp = minY;
minY = maxY;
maxY = tmp;
}
minY += Mathf.Abs(worldRect.height / 2);
maxY -= Mathf.Abs(worldRect.height / 2);
pos.y = Mathf.Clamp(pos.y, minY, maxY);
}
else
pos.y = (worldRect.yMin + worldRect.height / 2);
position = pos;
}
}
bool getRect = false;
bool recordPrefab = false;
void EditorSettings()
{
if (camera == null)
return;
// aspect ration check - because it sometimes is forced back to 4:3 ???
float asp = (float)Screen.width / (float)Screen.height;
if (asp!=camera.aspect) return;
if (!Application.isPlaying)
{
if (_position_ == _position && OT.world2D)
{
if (OT.world == OT.World.WorldSide2D)
{
if (!Vector2.Equals((Vector2)camera.transform.position, _position))
{
// camera has been moved manually
_position = camera.transform.position;
_position_ = _position;
transform.position = camera.transform.position;
UpdateWorldRect();
recordPrefab = true;
getRect = true;
}
else
if (transform.position.x != _position.x || transform.position.y != _position.y)
{
// view object has been moved manually
camera.transform.position = new Vector3(transform.position.x, transform.position.y, cameraDepth);
_position = new Vector2(camera.transform.position.x, camera.transform.position.y);
_position_ = position;
UpdateWorldRect();
recordPrefab = true;
getRect = true;
}
if (transform.position.z != cameraDepth)
transform.position = new Vector3(transform.position.x,transform.position.y, cameraDepth);
}
else
{
if (!Vector2.Equals(new Vector2(camera.transform.position.x,camera.transform.position.z) , _position))
{
// camera has been moved manually
_position = new Vector2(camera.transform.position.x, camera.transform.position.z);
_position_ = _position;
transform.position = camera.transform.position;
UpdateWorldRect();
recordPrefab = true;
getRect = true;
}
else
if (transform.position.x != _position.x || transform.position.z != _position.y)
{
// view object has been moved manually
camera.transform.position = new Vector3(transform.position.x, cameraDepth, transform.position.z);
_position = new Vector2(camera.transform.position.x, camera.transform.position.z);
_position_ = position;
UpdateWorldRect();
recordPrefab = true;
getRect = true;
}
if (transform.position.y != cameraDepth)
transform.position = new Vector3(transform.position.x, cameraDepth, transform.position.z);
}
}
if (_rotation_ == _rotation && OT.world2D)
{
if (OT.world == OT.World.WorldSide2D)
{
if (transform.rotation.eulerAngles.z != rotation)
{
// view object has been rotated manually in editor
rotation = transform.rotation.eulerAngles.z;
camera.transform.rotation = transform.rotation;
recordPrefab = true;
getRect = true;
}
else
if (camera.transform.rotation.eulerAngles.z != rotation)
{
// camera has been rotated manually in editor
rotation = camera.transform.rotation.eulerAngles.z;
transform.rotation = camera.transform.rotation;
recordPrefab = true;
getRect = true;
}
}
else
{
if (transform.rotation.eulerAngles.y != rotation)
{
// view object has been rotated manually in editor
rotation = transform.rotation.eulerAngles.y;
camera.transform.rotation = transform.rotation;
recordPrefab = true;
getRect = true;
}
else
if (camera.transform.rotation.eulerAngles.y != rotation)
{
// camera has been rotated manually in editor
rotation = camera.transform.rotation.eulerAngles.y;
transform.rotation = camera.transform.rotation;
recordPrefab = true;
getRect = true;
}
}
}
}
if (OT.world2D && !camera.orthographic)
SetCamera();
}
void UpdateWorldRect()
{
Vector2 dv = position - _worldRect.center;
_worldRect.center = position;
p1 += dv;
p2 += dv;
p3 += dv;
p4 += dv;
}
void CheckViewSize()
{
// check camera size
if (camera.orthographicSize != resSize * (Mathf.Pow(2, _zoom * -1)))
{
camera.orthographicSize = resSize * Mathf.Pow(2, _zoom * -1);
GetWorldRect();
}
}
// Update is called once per frame
public void Update()
{
if (!OT.isValid) return;
#if UNITY_EDITOR
EditorSettings();
#endif
// detect a screen size change
if (_currentScreen.x != Screen.width || _currentScreen.y != Screen.height)
{
getRect = true;
_currentScreen = new Vector2(Screen.width,Screen.height);
camera.orthographicSize = resSize * Mathf.Pow(2, _zoom * -1);
_zoom_ = _zoom;
if (onScreenChange!=null)
onScreenChange();
}
if (customSize!=0)
{
if (customSize != _customSize)
{
_customSize = customSize;
sizeFact = (customSize / pixelPerfectResolution.y) * 2;
}
}
else
sizeFact = 1;
if (_zoom_ != _zoom || !Application.isPlaying)
{
getRect = true;
_zoom_ = _zoom;
CheckViewSize();
}
if (Application.isPlaying && OT.world2D)
{
// check movement and rotation targets
if (movementTarget != null)
{
Vector2 targetPos;
if (movementObject!=null)
targetPos = movementObject.position;
else
{
if (OT.world == OT.World.WorldTopDown2D)
targetPos = new Vector2(movementTarget.transform.position.x,movementTarget.transform.position.z);
else
targetPos = movementTarget.transform.position;
}
if (!position.Equals(targetPos))
{
position = targetPos;
UpdateWorldRect();
if (onScreenChange!=null)
onScreenChange();
}
}
if (rotationTarget != null)
{
if (OT.world == OT.World.WorldSide2D && rotationTarget.transform.eulerAngles.z!=rotation)
rotation = rotationTarget.transform.eulerAngles.z;
else
if (OT.world == OT.World.WorldTopDown2D && rotationTarget.transform.eulerAngles.y!=rotation)
rotation = rotationTarget.transform.eulerAngles.y;
}
}
if (_rotation_!=rotation && OT.world2D)
{
_rotation_ = rotation;
// match camera rotation with view rotation
if (OT.world == OT.World.WorldSide2D)
{
if (camera.transform.eulerAngles.z != rotation)
{
camera.transform.eulerAngles = new Vector3(0, 0, rotation);
transform.rotation = camera.transform.rotation;
getRect = true;
}
}
else
{
if (camera.transform.eulerAngles.y != rotation)
{
camera.transform.eulerAngles = new Vector3(90, rotation,0);
transform.rotation = camera.transform.rotation;
getRect = true;
}
}
}
if (getRect || _position_ != _position)
{
GetWorldRect();
getRect = false;
AdjustToWorldBounds();
if (_position_ != _position && OT.world2D)
{
_position_ = _position;
if (OT.world == OT.World.WorldSide2D)
{
if (camera.transform.position.x != _position.x || camera.transform.position.y != _position.y || camera.transform.position.z != cameraDepth)
{
// match camera and view postion
camera.transform.position = new Vector3(_position.x, _position.y, cameraDepth);
transform.position = camera.transform.position;
}
}
else
{
if (camera.transform.position.x != _position.x || camera.transform.position.z != _position.y || camera.transform.position.y != cameraDepth)
{
// match camera and view postion
camera.transform.position = new Vector3(_position.x, cameraDepth, _position.y);
transform.position = camera.transform.position;
}
}
UpdateWorldRect();
}
}
#if UNITY_EDITOR
if (recordPrefab && !Application.isPlaying)
{
UnityEditor.PrefabUtility.RecordPrefabInstancePropertyModifications(this);
recordPrefab = false;
}
#endif
}
void DrawRect(Rect r, Color c)
{
Gizmos.color = c;
if (OT.world == OT.World.WorldSide2D)
{
Gizmos.DrawLine(new Vector3(r.xMin, r.yMin, 900), new Vector3(r.xMax, r.yMin, 900));
Gizmos.DrawLine(new Vector3(r.xMin, r.yMin, 900), new Vector3(r.xMin, r.yMax, 900));
Gizmos.DrawLine(new Vector3(r.xMax, r.yMin, 900), new Vector3(r.xMax, r.yMax, 900));
Gizmos.DrawLine(new Vector3(r.xMin, r.yMax, 900), new Vector3(r.xMax, r.yMax, 900));
}
else
{
Gizmos.DrawLine(new Vector3(r.xMin, -900, r.yMin), new Vector3(r.xMax, -900, r.yMin));
Gizmos.DrawLine(new Vector3(r.xMin, -900, r.yMin), new Vector3(r.xMin, -900, r.yMax));
Gizmos.DrawLine(new Vector3(r.xMax, -900, r.yMin), new Vector3(r.xMax, -900, r.yMax));
Gizmos.DrawLine(new Vector3(r.xMin, -900, r.yMax), new Vector3(r.xMax, -900, r.yMax));
}
}
void DrawView(Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4, Color c)
{
Gizmos.color = c;
Gizmos.DrawLine(p1, p2);
Gizmos.DrawLine(p1, p3);
Gizmos.DrawLine(p2, p4);
Gizmos.DrawLine(p3, p4);
}
Color Darker(Color c)
{
return new Color(c.r * 0.5f, c.g * 0.5f, c.b * 0.5f);
}
protected void OnDrawGizmos()
{
if (OT.world3D)
return;
if (drawGizmos)
{
DrawRect(worldBounds, Darker(gizmosColor));
Rect r = worldRect;
if (OT.world == OT.World.WorldSide2D)
{
Vector3 gp1 = new Vector3(p1.x, p1.y, 900);
Vector3 gp2 = new Vector3(p2.x, p2.y, 900);
Vector3 gp3 = new Vector3(p3.x, p3.y, 900);
Vector3 gp4 = new Vector3(p4.x, p4.y, 900);
DrawView(gp1, gp2, gp3, gp4, Darker(gizmosColor));
gp1 = new Vector3(r.xMin, r.yMin, 900);
gp2 = new Vector3(r.xMax, r.yMin, 900);
gp3 = new Vector3(r.xMin, r.yMax, 900);
gp4 = new Vector3(r.xMax, r.yMax, 900);
DrawView(gp1,gp2,gp3,gp4, gizmosColor);
}
else
{
Vector3 gp1 = new Vector3(p1.x, -900, p1.y);
Vector3 gp2 = new Vector3(p2.x, -900, p2.y);
Vector3 gp3 = new Vector3(p3.x, -900, p3.y);
Vector3 gp4 = new Vector3(p4.x, -900, p4.y);
DrawView(gp1, gp2, gp3, gp4, Darker(gizmosColor));
gp1 = new Vector3(r.xMin, -900, r.yMin);
gp2 = new Vector3(r.xMax, -900, r.yMin);
gp3 = new Vector3(r.xMin, -900, r.yMax);
gp4 = new Vector3(r.xMax, -900, r.yMax);
DrawView(gp1,gp2,gp3,gp4, gizmosColor);
}
}
}
#if UNITY_EDITOR
void OnGUI()
{
if (!OT.isValid || OT.view == null)
return;
// we have to calculate the right Orthographic size because we
// coud be in edit mode and just captured the right screen dimensions
if (!Application.isPlaying)
CheckViewSize();
// GUI.Box(new Rect((Screen.width / 2) - 50, (Screen.height / 2) - 50, 100, 100), "");
}
#endif
}
| |
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace AutoDI
{
public sealed class ContainerMap : IContainer
{
public event EventHandler<TypeKeyNotFoundEventArgs> TypeKeyNotFound;
private static readonly MethodInfo MakeLazyMethod;
private static readonly MethodInfo MakeFuncMethod;
private readonly Dictionary<Type, IDelegateContainer> _accessors = new Dictionary<Type, IDelegateContainer>();
static ContainerMap()
{
var methods = typeof(ContainerMap).GetRuntimeMethods().ToList();
MakeLazyMethod = methods.Single(m => m.Name == nameof(MakeLazy));
MakeFuncMethod = methods.Single(m => m.Name == nameof(MakeFunc));
}
public void Add(IServiceCollection services)
{
var factories = new Dictionary<(Type, Lifetime), Func<IServiceProvider, object>>();
//NB: Order of items in the collection matter (last in wins)
foreach (ServiceDescriptor serviceDescriptor in services)
{
Type targetType = serviceDescriptor.GetTargetType();
Lifetime lifetime = serviceDescriptor.GetAutoDILifetime();
if (targetType is null || !factories.TryGetValue((targetType, lifetime), out Func<IServiceProvider, object> factory))
{
factory = GetFactory(serviceDescriptor, lifetime);
if (targetType != null)
{
factories[(targetType, lifetime)] = factory;
}
}
AddInternal(new DelegateContainer(serviceDescriptor, factory), serviceDescriptor.ServiceType);
}
}
public void Add(ServiceDescriptor serviceDescriptor)
{
AddInternal(new DelegateContainer(serviceDescriptor), serviceDescriptor.ServiceType);
}
private void AddInternal(DelegateContainer container, Type key)
{
if (_accessors.TryGetValue(key, out IDelegateContainer existing))
{
_accessors[key] = existing + container;
}
else
{
_accessors[key] = container;
}
}
public bool Remove<T>() => Remove(typeof(T));
public bool Remove(Type serviceType) => _accessors.Remove(serviceType);
public T Get<T>(IServiceProvider provider)
{
//https://github.com/Keboo/DoubleDownWat
object value = Get(typeof(T), provider);
if (value is T result)
{
return result;
}
return default(T);
}
public object Get(Type serviceType, IServiceProvider provider)
{
if (TryGet(serviceType, provider ?? new ContainerServiceProvider(this), out object result))
{
return result;
}
//Type key not found
var args = new TypeKeyNotFoundEventArgs(serviceType);
TypeKeyNotFound?.Invoke(this, args);
return args.Instance;
}
public IContainer CreatedNestedContainer()
{
var rv = new ContainerMap();
foreach (KeyValuePair<Type, IDelegateContainer> kvp in _accessors)
{
rv._accessors[kvp.Key] = kvp.Value.ForNestedContainer();
}
return rv;
}
public IEnumerator<Map> GetEnumerator() => _accessors.OrderBy(kvp => kvp.Key.FullName)
.SelectMany(kvp => kvp.Value.GetMaps(kvp.Key)).GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
/// <summary>
/// This method is used by AutoDI and not expected to be invoked directly.
/// </summary>
internal void CreateSingletons(IServiceProvider provider)
{
foreach (IDelegateContainer container in _accessors.Values)
{
container.InstantiateSingletons(provider);
}
}
private Lazy<T> MakeLazy<T>(IServiceProvider provider) => new Lazy<T>(() => Get<T>(provider));
private Func<T> MakeFunc<T>(IServiceProvider provider) => () => Get<T>(provider);
private bool TryGet(Type key, IServiceProvider provider, out object result)
{
if (_accessors.TryGetValue(key, out IDelegateContainer container))
{
result = container.Get(provider);
return true;
}
if (key.IsArray &&
key.GetElementType() is Type elementType &&
_accessors.TryGetValue(elementType, out container))
{
result = container.GetArray(elementType, provider);
return true;
}
if (key.IsConstructedGenericType)
{
Type genericType = key.GetGenericTypeDefinition();
if (genericType == typeof(Lazy<>))
{
result = MakeLazyMethod.MakeGenericMethod(key.GenericTypeArguments[0])
.Invoke(this, new object[] { provider });
return true;
}
if (genericType == typeof(Func<>))
{
result = MakeFuncMethod.MakeGenericMethod(key.GenericTypeArguments[0])
.Invoke(this, new object[] { provider });
return true;
}
if (genericType == typeof(IEnumerable<>) &&
_accessors.TryGetValue(key.GenericTypeArguments[0], out container))
{
result = container.GetArray(key.GenericTypeArguments[0], provider);
return true;
}
if (_accessors.TryGetValue(genericType, out container))
{
IDelegateContainer genericContainer = container.AsGeneric(key.GenericTypeArguments);
if (genericContainer != null)
{
_accessors.Add(key, genericContainer);
result = genericContainer.Get(provider);
return true;
}
}
}
return TryCreate(key, provider, out result);
}
private static bool TryCreate(Type desiredType, IServiceProvider provider, out object result)
{
if (desiredType.IsClass && !desiredType.IsAbstract && !desiredType.IsArray)
{
foreach (ConstructorInfo constructor in desiredType.GetConstructors().OrderByDescending(c => c.GetParameters().Length))
{
var parameters = constructor.GetParameters();
object[] parameterValues = new object[parameters.Length];
bool found = true;
for (int i = 0; i < parameters.Length; i++)
{
if (parameters[i].ParameterType.IsPointer)
{
found = false;
break;
}
parameterValues[i] = provider.GetService(parameters[i].ParameterType);
if (parameterValues[i] is null)
{
if (parameters[i].HasDefaultValue)
{
parameterValues[i] = parameters[i].DefaultValue;
}
else
{
found = false;
break;
}
}
}
if (found)
{
result = constructor.Invoke(parameterValues);
return true;
}
}
}
result = null;
return false;
}
private static Func<IServiceProvider, object> GetFactory(ServiceDescriptor descriptor, Lifetime lifetime)
{
return WithLifetime(GetFactoryMethod());
Func<IServiceProvider, object> GetFactoryMethod()
{
if (descriptor.ImplementationType != null)
{
return sp =>
{
if (TryCreate(descriptor.ImplementationType, sp, out object result))
{
return result;
}
return null;
};
}
if (descriptor.ImplementationFactory != null)
{
return descriptor.ImplementationFactory;
}
//NB: separate the instance from the ServiceDescriptor to avoid capturing both
object instance = descriptor.ImplementationInstance;
return _ => instance;
}
Func<IServiceProvider, object> WithLifetime(Func<IServiceProvider, object> factory)
{
switch (lifetime)
{
case Lifetime.Singleton:
case Lifetime.LazySingleton:
case Lifetime.Scoped:
{
var syncLock = new object();
object value = null;
return provider =>
{
if (value != null) return value;
lock (syncLock)
{
if (value != null) return value;
return value = factory(provider);
}
};
}
case Lifetime.WeakSingleton:
{
var weakRef = new WeakReference<object>(null);
return provider =>
{
lock (weakRef)
{
if (!weakRef.TryGetTarget(out object value))
{
value = factory(provider);
weakRef.SetTarget(value);
}
return value;
}
};
}
case Lifetime.Transient:
return factory;
default:
throw new InvalidOperationException($"Unknown lifetime '{lifetime}'");
}
}
}
private interface IDelegateContainer
{
void InstantiateSingletons(IServiceProvider provider);
IEnumerable<Map> GetMaps(Type sourceType);
IDelegateContainer ForNestedContainer();
object Get(IServiceProvider provider);
Array GetArray(Type elementType, IServiceProvider provider);
IDelegateContainer AsGeneric(Type[] genericTypeArguments);
}
private sealed class DelegateContainer : IDelegateContainer
{
private readonly ServiceDescriptor _serviceDescriptor;
private readonly Func<IServiceProvider, object> _factoryWithLifetime;
private Type TargetType { get; }
private Lifetime Lifetime { get; }
public DelegateContainer(ServiceDescriptor serviceDescriptor, Func<IServiceProvider, object> factory)
: this(serviceDescriptor.GetAutoDILifetime(), serviceDescriptor.GetTargetType(), factory)
{
_serviceDescriptor = serviceDescriptor ?? throw new ArgumentNullException(nameof(serviceDescriptor));
}
public DelegateContainer(ServiceDescriptor serviceDescriptor)
: this(serviceDescriptor.GetAutoDILifetime(),
serviceDescriptor.GetTargetType(),
GetFactory(serviceDescriptor, serviceDescriptor.GetAutoDILifetime()))
{
_serviceDescriptor = serviceDescriptor ?? throw new ArgumentNullException(nameof(serviceDescriptor));
}
private DelegateContainer(Lifetime lifetime, Type targetType,
Func<IServiceProvider, object> creationFactory)
{
Lifetime = lifetime;
TargetType = targetType;
_factoryWithLifetime = creationFactory;
}
public void InstantiateSingletons(IServiceProvider provider)
{
if (Lifetime == Lifetime.Singleton)
{
Get(provider);
}
}
public IEnumerable<Map> GetMaps(Type sourceType)
{
yield return new Map(sourceType, TargetType, Lifetime);
}
public IDelegateContainer ForNestedContainer()
{
switch (Lifetime)
{
case Lifetime.Scoped:
case Lifetime.WeakSingleton:
return new DelegateContainer(_serviceDescriptor);
default:
return this;
}
}
public Array GetArray(Type elementType, IServiceProvider provider)
{
var array = Array.CreateInstance(elementType, 1);
array.SetValue(Get(provider), 0);
return array;
}
public IDelegateContainer AsGeneric(Type[] genericTypeParameters)
{
if (_serviceDescriptor.ImplementationType?.IsGenericTypeDefinition != true)
{
throw new InvalidOperationException(
$"Attempted to retrieved closed generic for non-open generic type '{_serviceDescriptor.ImplementationType?.FullName ?? "Unknown"}' using '{_serviceDescriptor.ServiceType.FullName}'");
}
Type targetType = _serviceDescriptor.ImplementationType.MakeGenericType(genericTypeParameters);
var closedGenericDescriptor = new AutoDIServiceDescriptor(_serviceDescriptor.ServiceType, targetType, Lifetime);
return new DelegateContainer(closedGenericDescriptor);
}
public object Get(IServiceProvider provider) => _factoryWithLifetime(provider);
public static IDelegateContainer operator +(IDelegateContainer left, DelegateContainer right)
{
if (left is null) return right;
if (right is null) return left;
if (left is MulticastDelegateContainer multicastDelegateContainer)
{
multicastDelegateContainer.Add(right);
return multicastDelegateContainer;
}
return new MulticastDelegateContainer(left, right);
}
private sealed class MulticastDelegateContainer : IDelegateContainer
{
private List<IDelegateContainer> Containers { get; }
public MulticastDelegateContainer(params IDelegateContainer[] containers)
{
Containers = new List<IDelegateContainer>(containers);
}
public void Add(IDelegateContainer container)
{
Containers.Add(container);
}
public void InstantiateSingletons(IServiceProvider provider)
{
foreach (IDelegateContainer container in Containers)
{
container.InstantiateSingletons(provider);
}
}
public IEnumerable<Map> GetMaps(Type sourceType)
{
return Containers.SelectMany(c => c.GetMaps(sourceType));
}
public IDelegateContainer ForNestedContainer()
{
return new MulticastDelegateContainer(Containers.Select(x => x.ForNestedContainer()).ToArray());
}
public object Get(IServiceProvider provider) => Containers.Last().Get(provider);
public Array GetArray(Type elementType, IServiceProvider provider)
{
Array[] arrays = Containers.Select(c => c.GetArray(elementType, provider)).ToArray();
Array rv = Array.CreateInstance(elementType, arrays.Sum(x => x.Length));
int index = 0;
foreach (Array array in arrays)
{
Array.Copy(array, 0, rv, index, array.Length);
index += array.Length;
}
return rv;
}
public IDelegateContainer AsGeneric(Type[] genericTypeArguments) => null;
}
}
private class ContainerServiceProvider : IServiceProvider
{
private readonly IContainer _container;
public ContainerServiceProvider(IContainer container)
{
_container = container;
}
public object GetService(Type serviceType) => _container.Get(serviceType, this);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.ModelBinding;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;
using System.Data.Entity;
using Gnx.Models;
using Gnx.Providers;
using Gnx.Results;
using System.Web.Helpers;
namespace Gnx.Controllers
{
[Authorize]
[RoutePrefix("api/Account")]
public class AccountController : ApiController
{
private const string LocalLoginProvider = "Local";
private ApplicationDbContext db = new ApplicationDbContext();
public AccountController()
: this(Startup.UserManagerFactory(), Startup.OAuthOptions.AccessTokenFormat)
{
}
public AccountController(UserManager<IdentityUser> userManager,
ISecureDataFormat<AuthenticationTicket> accessTokenFormat)
{
UserManager = userManager;
AccessTokenFormat = accessTokenFormat;
RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));
}
public UserManager<IdentityUser> UserManager { get; private set; }
public RoleManager<IdentityRole> RoleManager { get; set; }
public ISecureDataFormat<AuthenticationTicket> AccessTokenFormat { get; private set; }
// GET api/Account/UserInfo
[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
[Route("UserInfo")]
public UserInfoViewModel GetUserInfo()
{
ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);
return new UserInfoViewModel
{
UserName = User.Identity.GetUserName(),
Email = UserManager.FindById( User.Identity.GetUserId()).Email,
HasRegistered = externalLogin == null,
LoginProvider = externalLogin != null ? externalLogin.LoginProvider : null
};
}
// POST api/Account/Logout
[Route("Logout")]
public IHttpActionResult Logout()
{
Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType);
return Ok();
}
// GET api/Account/ManageInfo?returnUrl=%2F&generateState=true
[Route("ManageInfo")]
public async Task<ManageInfoViewModel> GetManageInfo(string returnUrl, bool generateState = false)
{
IdentityUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user == null)
{
return null;
}
List<UserLoginInfoViewModel> logins = new List<UserLoginInfoViewModel>();
foreach (IdentityUserLogin linkedAccount in user.Logins)
{
logins.Add(new UserLoginInfoViewModel
{
LoginProvider = linkedAccount.LoginProvider,
ProviderKey = linkedAccount.ProviderKey
});
}
if (user.PasswordHash != null)
{
logins.Add(new UserLoginInfoViewModel
{
LoginProvider = LocalLoginProvider,
ProviderKey = user.UserName,
});
}
return new ManageInfoViewModel
{
LocalLoginProvider = LocalLoginProvider,
UserName = user.UserName,
Logins = logins,
ExternalLoginProviders = GetExternalLogins(returnUrl, generateState)
};
}
// POST api/Account/ChangePassword
[Route("ChangePassword")]
public async Task<IHttpActionResult> ChangePassword(ChangePasswordBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
IdentityResult result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword,
model.NewPassword);
IHttpActionResult errorResult = GetErrorResult(result);
if (errorResult != null)
{
return errorResult;
}
return Ok();
}
// POST api/Account/SetPassword
[Route("SetPassword")]
public async Task<IHttpActionResult> SetPassword(SetPasswordBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
IdentityResult result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);
IHttpActionResult errorResult = GetErrorResult(result);
if (errorResult != null)
{
return errorResult;
}
return Ok();
}
// POST api/Account/AddExternalLogin
[Route("AddExternalLogin")]
public async Task<IHttpActionResult> AddExternalLogin(AddExternalLoginBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
AuthenticationTicket ticket = AccessTokenFormat.Unprotect(model.ExternalAccessToken);
if (ticket == null || ticket.Identity == null || (ticket.Properties != null
&& ticket.Properties.ExpiresUtc.HasValue
&& ticket.Properties.ExpiresUtc.Value < DateTimeOffset.UtcNow))
{
return BadRequest("External login failure.");
}
ExternalLoginData externalData = ExternalLoginData.FromIdentity(ticket.Identity);
if (externalData == null)
{
return BadRequest("The external login is already associated with an account.");
}
IdentityResult result = await UserManager.AddLoginAsync(User.Identity.GetUserId(),
new UserLoginInfo(externalData.LoginProvider, externalData.ProviderKey));
IHttpActionResult errorResult = GetErrorResult(result);
if (errorResult != null)
{
return errorResult;
}
return Ok();
}
// POST api/Account/RemoveLogin
[Route("RemoveLogin")]
public async Task<IHttpActionResult> RemoveLogin(RemoveLoginBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
IdentityResult result;
if (model.LoginProvider == LocalLoginProvider)
{
result = await UserManager.RemovePasswordAsync(User.Identity.GetUserId());
}
else
{
result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(),
new UserLoginInfo(model.LoginProvider, model.ProviderKey));
}
IHttpActionResult errorResult = GetErrorResult(result);
if (errorResult != null)
{
return errorResult;
}
return Ok();
}
// GET api/Account/ExternalLogin
[OverrideAuthentication]
[HostAuthentication(DefaultAuthenticationTypes.ExternalCookie)]
[AllowAnonymous]
[Route("ExternalLogin", Name = "ExternalLogin")]
public async Task<IHttpActionResult> GetExternalLogin(string provider, string error = null)
{
if (error != null)
{
return Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error));
}
if (!User.Identity.IsAuthenticated)
{
return new ChallengeResult(provider, this);
}
ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);
if (externalLogin == null)
{
return InternalServerError();
}
if (externalLogin.LoginProvider != provider)
{
Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
return new ChallengeResult(provider, this);
}
IdentityUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider,
externalLogin.ProviderKey));
bool hasRegistered = user != null;
if (hasRegistered)
{
Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
ClaimsIdentity oAuthIdentity = await UserManager.CreateIdentityAsync(user,
OAuthDefaults.AuthenticationType);
ClaimsIdentity cookieIdentity = await UserManager.CreateIdentityAsync(user,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
}
else
{
IEnumerable<Claim> claims = externalLogin.GetClaims();
ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
Authentication.SignIn(identity);
}
return Ok();
}
// GET api/Account/ExternalLogins?returnUrl=%2F&generateState=true
[AllowAnonymous]
[Route("ExternalLogins")]
public IEnumerable<ExternalLoginViewModel> GetExternalLogins(string returnUrl, bool generateState = false)
{
IEnumerable<AuthenticationDescription> descriptions = Authentication.GetExternalAuthenticationTypes();
List<ExternalLoginViewModel> logins = new List<ExternalLoginViewModel>();
string state;
if (generateState)
{
const int strengthInBits = 256;
state = RandomOAuthStateGenerator.Generate(strengthInBits);
}
else
{
state = null;
}
foreach (AuthenticationDescription description in descriptions)
{
ExternalLoginViewModel login = new ExternalLoginViewModel
{
Name = description.Caption,
Url = Url.Route("ExternalLogin", new
{
provider = description.AuthenticationType,
response_type = "token",
client_id = Startup.PublicClientId,
redirect_uri = new Uri(Request.RequestUri, returnUrl).AbsoluteUri,
state = state
}),
State = state
};
logins.Add(login);
}
return logins;
}
// POST api/Account/Register
[AllowAnonymous]
[Route("Register")]
public async Task<IHttpActionResult> Register(RegisterBindingModel model)
{
#region old version kept here for sentiment - now moved tyo the seed method - run on update-database
//// create set of roles and admin user
//try
//{
// // test if admin user already created
// var hasAdmin = UserManager.FindByEmail("admin@geonetix.pl");
// if (hasAdmin == null)
// {
// // create set of roles
// var adminRole = new IdentityRole()
// {
// Name = "administrator"
// };
// var createAdminRole = await RoleManager.CreateAsync(adminRole);
// var superUserRole = new IdentityRole()
// {
// Name = "superuser"
// };
// var createSuperUserRole = await RoleManager.CreateAsync(superUserRole);
// var authenticatedUserRole = new IdentityRole()
// {
// Name = "authenticated"
// };
// var createAuthenticatedUserRole = await RoleManager.CreateAsync(authenticatedUserRole);
// var guestUserRole = new IdentityRole()
// {
// Name = "guest"
// };
// var createGuestUserRole = RoleManager.CreateAsync(guestUserRole);
// // create admin user
// var admin = new IdentityUser
// {
// UserName = "admin",
// Email = "admin@geonetix.pl",
// PasswordHash = Crypto.HashPassword("test111")
// };
// IdentityResult resultCreateAdmin = await UserManager.CreateAsync(admin, "test111");
// var userAdmin = UserManager.FindByEmail("admin@geonetix.pl");
// var roleresult = UserManager.AddToRole(userAdmin.Id, "administrator");
// }
//}
//catch (Exception ex)
//{
// string stoper = ex.Message;
//}
# endregion
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
IdentityUser user = new IdentityUser
{
UserName = model.UserName,
Email = model.Email
};
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
IHttpActionResult errorResult = GetErrorResult(result);
if (errorResult != null)
{
return errorResult;
}
return Ok();
}
// POST api/Account/RegisterExternal
[OverrideAuthentication]
[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
[Route("RegisterExternal")]
public async Task<IHttpActionResult> RegisterExternal(RegisterExternalBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);
if (externalLogin == null)
{
return InternalServerError();
}
IdentityUser user = new IdentityUser
{
UserName = model.UserName
};
user.Logins.Add(new IdentityUserLogin
{
LoginProvider = externalLogin.LoginProvider,
ProviderKey = externalLogin.ProviderKey
});
IdentityResult result = await UserManager.CreateAsync(user);
IHttpActionResult errorResult = GetErrorResult(result);
if (errorResult != null)
{
return errorResult;
}
return Ok();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
UserManager.Dispose();
}
base.Dispose(disposing);
}
#region Helpers
private IAuthenticationManager Authentication
{
get { return Request.GetOwinContext().Authentication; }
}
private IHttpActionResult GetErrorResult(IdentityResult result)
{
if (result == null)
{
return InternalServerError();
}
if (!result.Succeeded)
{
if (result.Errors != null)
{
foreach (string error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
if (ModelState.IsValid)
{
// No ModelState errors are available to send, so just return an empty BadRequest.
return BadRequest();
}
return BadRequest(ModelState);
}
return null;
}
private class ExternalLoginData
{
public string LoginProvider { get; set; }
public string ProviderKey { get; set; }
public string UserName { get; set; }
public IList<Claim> GetClaims()
{
IList<Claim> claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.NameIdentifier, ProviderKey, null, LoginProvider));
if (UserName != null)
{
claims.Add(new Claim(ClaimTypes.Name, UserName, null, LoginProvider));
}
return claims;
}
public static ExternalLoginData FromIdentity(ClaimsIdentity identity)
{
if (identity == null)
{
return null;
}
Claim providerKeyClaim = identity.FindFirst(ClaimTypes.NameIdentifier);
if (providerKeyClaim == null || String.IsNullOrEmpty(providerKeyClaim.Issuer)
|| String.IsNullOrEmpty(providerKeyClaim.Value))
{
return null;
}
if (providerKeyClaim.Issuer == ClaimsIdentity.DefaultIssuer)
{
return null;
}
return new ExternalLoginData
{
LoginProvider = providerKeyClaim.Issuer,
ProviderKey = providerKeyClaim.Value,
UserName = identity.FindFirstValue(ClaimTypes.Name)
};
}
}
private static class RandomOAuthStateGenerator
{
private static RandomNumberGenerator _random = new RNGCryptoServiceProvider();
public static string Generate(int strengthInBits)
{
const int bitsPerByte = 8;
if (strengthInBits % bitsPerByte != 0)
{
throw new ArgumentException("strengthInBits must be evenly divisible by 8.", "strengthInBits");
}
int strengthInBytes = strengthInBits / bitsPerByte;
byte[] data = new byte[strengthInBytes];
_random.GetBytes(data);
return HttpServerUtility.UrlTokenEncode(data);
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using RE;
namespace REMulti
{
[REItem("sort", "Sort", "Sort the items of a multiple input.")]
public partial class RESort : RE.REBaseItem
{
private RE.RELinkPointPatch patch1;
private RE.RELinkPointPatch patch2;
public RESort()
{
InitializeComponent();
patch1 = new RELinkPointPatch(lpInput, lpOutput);
patch2 = new RELinkPointPatch(lpPrepare, lpSortBy);
}
public override void LoadFromXml(System.Xml.XmlElement Element)
{
base.LoadFromXml(Element);
ignoreCaseToolStripMenuItem.Checked = StrToBool(Element.GetAttribute("ignorecase"));
numericToolStripMenuItem.Checked = StrToBool(Element.GetAttribute("numeric"));
descendingToolStripMenuItem.Checked = StrToBool(Element.GetAttribute("descending"));
allowDuplicatesToolStripMenuItem.Checked=StrToBool(Element.GetAttribute("allowduplicates"));
}
public override void SaveToXml(System.Xml.XmlElement Element)
{
base.SaveToXml(Element);
Element.SetAttribute("ignorecase", BoolToStr(ignoreCaseToolStripMenuItem.Checked));
Element.SetAttribute("numeric", BoolToStr(numericToolStripMenuItem.Checked));
Element.SetAttribute("descending", BoolToStr(descendingToolStripMenuItem.Checked));
Element.SetAttribute("allowduplicates", BoolToStr(allowDuplicatesToolStripMenuItem.Checked));
}
private bool _preparing;
private object _prepareData;
private bool _outputting;
private SortedDictionary<string, object> _data;
private List<object> _outputData;
private int _outputIndex;
private bool _registered;
private class RESortComparer : Comparer<string>
{
internal RESortComparer(bool IgnoreCase, bool Numeric, bool Descending, bool AllowDuplicates)
{
_ignorecase = IgnoreCase;
_numeric = Numeric;
_descending = Descending;
_allowdup = AllowDuplicates;
}
private bool _ignorecase;
private bool _numeric;
private bool _descending;
private bool _allowdup;
public override int Compare(string x, string y)
{
int r;
if (_numeric)
{
Int64 a = Convert.ToInt64(x);
Int64 b = Convert.ToInt64(y);
if (a < b)
r = -1;
else
if (a == b)
r = 0;
else
r = 1;
}
else
r = String.Compare(x, y, _ignorecase);
if (_allowdup && r == 0) r = 1;//dirty fix perhaps, but it works
if (_descending) return -r; else return r;
}
}
public override void Start()
{
base.Start();
_preparing = false;
_prepareData = null;
_outputting = false;
_data = null;
_registered = false;
}
public override void Stop()
{
base.Stop();
_data = null;
_outputData = null;
}
private void lpInput_Signal(RELinkPoint Sender, object Data)
{
if (_preparing || _outputting)
throw new EReUnexpectedInputException(lpInput);
else
if (lpOutput.IsConnected)
{
if (!_registered)
{
//register sequence end
lpOutput.Emit(lpOutput);
_registered = true;
}
if (_data == null)
_data = new SortedDictionary<string, object>(new RESortComparer(
ignoreCaseToolStripMenuItem.Checked,
numericToolStripMenuItem.Checked,
descendingToolStripMenuItem.Checked,
allowDuplicatesToolStripMenuItem.Checked));
if (lpPrepare.IsConnected)
{
_preparing = true;
_prepareData = Data;
lpPrepare.Emit(Data, true);
}
else
_data.Add(Data.ToString(), Data);
}
}
private void lpSortBy_Signal(RELinkPoint Sender, object Data)
{
if (_preparing)
{
_preparing = false;
_data.Add(Data.ToString(), _prepareData);
_prepareData = null;
}
else
throw new EReUnexpectedInputException(lpSortBy);
}
private void lpOutput_Signal(RELinkPoint Sender, object Data)
{
if (_outputting)
OutputNext();
else
if (_preparing)
throw new EReUnexpectedInputException(lpOutput);
else
{
_registered = false;
_outputting = true;
_outputIndex = 0;
_outputData = new List<object>(_data.Values);
_data = null;
OutputNext();
}
}
private void lpPrepare_Signal(RELinkPoint Sender, object Data)
{
if (_preparing)
{
//prepare to sortby track didn't post to sortby, cancel preparing and drop input?
_preparing = false;
}
//else OK! (assert _preparing set to false by lpSortBy_Signal)
}
private void OutputNext()
{
//assert _outputting
if (_outputIndex < _outputData.Count)
{
lpOutput.Emit(_outputData[_outputIndex], true);
_outputIndex++;
}
else
_outputting = false;
}
private void ignoreCaseToolStripMenuItem_Click(object sender, EventArgs e)
{
ignoreCaseToolStripMenuItem.Checked = !ignoreCaseToolStripMenuItem.Checked;
Modified = true;
}
private void numericToolStripMenuItem_Click(object sender, EventArgs e)
{
numericToolStripMenuItem.Checked = !numericToolStripMenuItem.Checked;
Modified = true;
}
private void descendingToolStripMenuItem_Click(object sender, EventArgs e)
{
descendingToolStripMenuItem.Checked = !descendingToolStripMenuItem.Checked;
Modified = true;
}
private void allowDuplicatesToolStripMenuItem_Click(object sender, EventArgs e)
{
allowDuplicatesToolStripMenuItem.Checked = !allowDuplicatesToolStripMenuItem.Checked;
Modified = true;
}
protected override void DisconnectAll()
{
//replacing base.DisconnectAll();
patch1.Disconnect();
patch2.Disconnect();
}
}
}
| |
// 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 ConvertToVector256SingleInt32()
{
var test = new SimpleUnaryOpTest__ConvertToVector256SingleInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__ConvertToVector256SingleInt32
{
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static Int32[] _data = new Int32[Op1ElementCount];
private static Vector256<Int32> _clsVar;
private Vector256<Int32> _fld;
private SimpleUnaryOpTest__DataTable<Single, Int32> _dataTable;
static SimpleUnaryOpTest__ConvertToVector256SingleInt32()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
}
public SimpleUnaryOpTest__ConvertToVector256SingleInt32()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
_dataTable = new SimpleUnaryOpTest__DataTable<Single, Int32>(_data, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx.ConvertToVector256Single(
Unsafe.Read<Vector256<Int32>>(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx.ConvertToVector256Single(
Avx.LoadVector256((Int32*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx.ConvertToVector256Single(
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx).GetMethod(nameof(Avx.ConvertToVector256Single), new Type[] { typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int32>>(_dataTable.inArrayPtr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx).GetMethod(nameof(Avx.ConvertToVector256Single), new Type[] { typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int32*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx).GetMethod(nameof(Avx.ConvertToVector256Single), new Type[] { typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx.ConvertToVector256Single(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector256<Int32>>(_dataTable.inArrayPtr);
var result = Avx.ConvertToVector256Single(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Avx.LoadVector256((Int32*)(_dataTable.inArrayPtr));
var result = Avx.ConvertToVector256Single(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArrayPtr));
var result = Avx.ConvertToVector256Single(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__ConvertToVector256SingleInt32();
var result = Avx.ConvertToVector256Single(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx.ConvertToVector256Single(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Int32> firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int32[] firstOp, Single[] result, [CallerMemberName] string method = "")
{
if (result[0] != (Single)(firstOp[0]))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (Single)(firstOp[i]))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.ConvertToVector256Single)}(Vector256<Int32>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
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 SecurityUsingOAuth.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ActionDescriptor.ReturnType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
using System.ServiceProcess;
using System.Text;
using NRack.Base;
using NRack.Base.Config;
using NRack.Server.Isolation;
using NRack.Server.Service;
namespace NRack.Server
{
public static partial class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
public static void Main(string[] args)
{
var isMono = NRackEnv.IsMono;
//If this application run in Mono/Linux, change the control script to be executable
if (isMono && Path.DirectorySeparatorChar == '/')
ChangeScriptExecutable();
if ((!isMono && !Environment.UserInteractive)//Windows Service
|| (isMono && !AppDomain.CurrentDomain.FriendlyName.Equals(Path.GetFileName(Assembly.GetEntryAssembly().CodeBase))))//MonoService
{
RunAsService();
return;
}
string exeArg = string.Empty;
if (args == null || args.Length < 1)
{
Console.WriteLine("Welcome to NRack.Server!");
Console.WriteLine("Please press a key to continue...");
Console.WriteLine("-[r]: Run this application as a console application;");
Console.WriteLine("-[i]: Install this application as a Windows Service;");
Console.WriteLine("-[u]: Uninstall this Windows Service application;");
while (true)
{
exeArg = Console.ReadKey().KeyChar.ToString();
Console.WriteLine();
if (Run(exeArg, null))
break;
}
}
else
{
exeArg = args[0];
if (!string.IsNullOrEmpty(exeArg))
exeArg = exeArg.TrimStart('-');
Run(exeArg, args);
}
}
static void ChangeScriptExecutable()
{
var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "NRack.sh");
try
{
if (!File.Exists(filePath))
return;
File.SetAttributes(filePath, (FileAttributes)((uint)File.GetAttributes(filePath) | 0x80000000));
}
catch
{
}
}
private static bool Run(string exeArg, string[] startArgs)
{
switch (exeArg.ToLower())
{
case ("i"):
SelfInstaller.InstallMe();
return true;
case ("u"):
SelfInstaller.UninstallMe();
return true;
case ("r"):
RunAsConsole();
return true;
case ("c"):
RunAsController(startArgs);
return true;
default:
Console.WriteLine("Invalid argument!");
return false;
}
}
private static bool setConsoleColor;
static void CheckCanSetConsoleColor()
{
try
{
Console.ForegroundColor = ConsoleColor.Green;
Console.ResetColor();
setConsoleColor = true;
}
catch
{
setConsoleColor = false;
}
}
private static void SetConsoleColor(ConsoleColor color)
{
if (setConsoleColor)
Console.ForegroundColor = color;
}
private static Dictionary<string, ControlCommand> m_CommandHandlers = new Dictionary<string, ControlCommand>(StringComparer.OrdinalIgnoreCase);
private static void AddCommand(string name, string description, Func<IBootstrap, string[], bool> handler)
{
var command = new ControlCommand
{
Name = name,
Description = description,
Handler = handler
};
m_CommandHandlers.Add(command.Name, command);
}
static void RunAsConsole()
{
Console.WriteLine("Welcome to NRack.Server!");
CheckCanSetConsoleColor();
Console.WriteLine("Initializing...");
IBootstrap bootstrap = BootstrapFactory.CreateBootstrap();
if (!bootstrap.Initialize())
{
SetConsoleColor(ConsoleColor.Red);
Console.WriteLine("Failed to initialize NRack.Server! Please check error log for more information!");
Console.ReadKey();
return;
}
Console.WriteLine("Starting...");
bootstrap.Start();
Console.WriteLine("-------------------------------------------------------------------");
foreach (var server in bootstrap.AppServers)
{
if (server.State == ServerState.Running)
{
SetConsoleColor(ConsoleColor.Green);
Console.WriteLine("- {0} has been started", server.Name);
}
else
{
SetConsoleColor(ConsoleColor.Red);
Console.WriteLine("- {0} failed to start", server.Name);
}
}
Console.ResetColor();
Console.WriteLine("-------------------------------------------------------------------");
Console.ResetColor();
Console.WriteLine("Enter key 'quit' to stop the NRack.Server.");
RegisterCommands();
ReadConsoleCommand(bootstrap);
bootstrap.Stop();
Console.WriteLine("The NRack.Server has been stopped!");
}
private static void RegisterCommands()
{
AddCommand("List", "List all server instances", ListCommand);
AddCommand("Start", "Start a server instance: Start {ServerName}", StartCommand);
AddCommand("Stop", "Stop a server instance: Stop {ServerName}", StopCommand);
}
private static void RunAsController(string[] arguments)
{
if (arguments == null || arguments.Length < 2)
{
Console.WriteLine("Invalid arguments!");
return;
}
var config = ConfigurationManager.GetSection("NRack") as IConfigSource;
if (config == null)
{
Console.WriteLine("NRack configuration is required!");
return;
}
var clientChannel = new IpcClientChannel();
ChannelServices.RegisterChannel(clientChannel, false);
IBootstrap bootstrap = null;
try
{
var remoteBootstrapUri = string.Format("ipc://NRack.Bootstrap[{0}]/Bootstrap.rem", Math.Abs(AppDomain.CurrentDomain.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar).GetHashCode()));
bootstrap = (IBootstrap)Activator.GetObject(typeof(IBootstrap), remoteBootstrapUri);
}
catch (RemotingException)
{
if (config.Isolation != IsolationMode.Process)
{
Console.WriteLine("Error: the NRack.Server has not been started!");
return;
}
}
RegisterCommands();
var cmdName = arguments[1];
ControlCommand cmd;
if (!m_CommandHandlers.TryGetValue(cmdName, out cmd))
{
Console.WriteLine("Unknown command");
return;
}
try
{
if (cmd.Handler(bootstrap, arguments.Skip(1).ToArray()))
Console.WriteLine("Ok");
}
catch (Exception e)
{
Console.WriteLine("Failed. " + e.Message);
}
}
static bool ListCommand(IBootstrap bootstrap, string[] arguments)
{
foreach (var s in bootstrap.AppServers)
{
Console.WriteLine("{0} - {1}", s.Name, s.State);
}
return false;
}
static bool StopCommand(IBootstrap bootstrap, string[] arguments)
{
var name = string.Empty;
if(arguments.Length > 1)
{
name = arguments[1];
}
if (string.IsNullOrEmpty(name))
{
Console.WriteLine("Server name is required!");
return false;
}
var server = bootstrap.AppServers.FirstOrDefault(s => s.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
if (server == null)
{
Console.WriteLine("The server was not found!");
return false;
}
server.Stop();
return true;
}
static bool StartCommand(IBootstrap bootstrap, string[] arguments)
{
var name = string.Empty;
if (arguments.Length > 1)
{
name = arguments[1];
}
if (string.IsNullOrEmpty(name))
{
Console.WriteLine("Server name is required!");
return false;
}
var server = bootstrap.AppServers.FirstOrDefault(s => s.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
if (server == null)
{
Console.WriteLine("The server was not found!");
return false;
}
server.Start();
return true;
}
static void ReadConsoleCommand(IBootstrap bootstrap)
{
var line = Console.ReadLine();
if (string.IsNullOrEmpty(line))
{
ReadConsoleCommand(bootstrap);
return;
}
if ("quit".Equals(line, StringComparison.OrdinalIgnoreCase))
return;
var cmdArray = line.Split(' ');
ControlCommand cmd;
if (!m_CommandHandlers.TryGetValue(cmdArray[0], out cmd))
{
Console.WriteLine("Unknown command");
ReadConsoleCommand(bootstrap);
return;
}
try
{
if(cmd.Handler(bootstrap, cmdArray))
Console.WriteLine("Ok");
}
catch (Exception e)
{
Console.WriteLine("Failed. " + e.Message + Environment.NewLine + e.StackTrace);
}
ReadConsoleCommand(bootstrap);
}
static void RunAsService()
{
var currentDomain = AppDomain.CurrentDomain;
#pragma warning disable 0618 // Type or member is obsolete
currentDomain.SetCachePath(Path.Combine(Path.Combine(currentDomain.BaseDirectory, IsolationAppConst.ShadowCopyDir), "Bootstrap"));
currentDomain.SetShadowCopyFiles();
#pragma warning restore 0618 // Type or member is obsolete
ServiceBase[] servicesToRun;
servicesToRun = new ServiceBase[] { new NRackService() };
ServiceBase.Run(servicesToRun);
}
}
}
| |
using EdiEngine.Common.Enums;
using EdiEngine.Common.Definitions;
using EdiEngine.Standards.X12_004010.Segments;
namespace EdiEngine.Standards.X12_004010.Maps
{
public class M_201 : MapLoop
{
public M_201() : base(null)
{
Content.AddRange(new MapBaseEntity[] {
new BGN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new L_N1(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 5 },
new L_LRQ(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 },
});
}
//1000
public class L_N1 : MapLoop
{
public L_N1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
});
}
}
//2000
public class L_LRQ : MapLoop
{
public L_LRQ(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LRQ() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 3 },
new YNQ() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 4 },
new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new III() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new RLD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 15 },
new MCD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new NTE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_NX1(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 10 },
new L_PEX(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 20 },
new L_AMT(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_IN1(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 15 },
new L_LX(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 5 },
});
}
}
//2100
public class L_NX1 : MapLoop
{
public L_NX1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new NX1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new NX2() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 30 },
new REA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new PDS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new PDE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 50 },
});
}
}
//2200
public class L_PEX : MapLoop
{
public L_PEX(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new PEX() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2300
public class L_AMT : MapLoop
{
public L_AMT(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new AMT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2400
public class L_IN1 : MapLoop
{
public L_IN1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new IN1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new IN2() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 10 },
new YNQ() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 19 },
new DTP() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 3 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new DMG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N10() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new FTH() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new AIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new PPY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 },
new L_PEX_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 },
new L_NX1_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new L_N1_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 },
new L_REA(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 },
new L_NM1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 },
new L_CDA(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 100 },
new L_FAA(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 100 },
new LS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_AMT_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new LE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2410
public class L_PEX_1 : MapLoop
{
public L_PEX_1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new PEX() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2420
public class L_NX1_1 : MapLoop
{
public L_NX1_1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new NX1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new NX2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 30 },
new N10() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new ARS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2430
public class L_N1_1 : MapLoop
{
public L_N1_1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new YNQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new EMS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2440
public class L_REA : MapLoop
{
public L_REA(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new REA() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 6 },
new NX1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new NX2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 30 },
});
}
}
//2450
public class L_NM1 : MapLoop
{
public L_NM1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new NM1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new ACT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
});
}
}
//2460
public class L_CDA : MapLoop
{
public L_CDA(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new CDA() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new YNQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2470
public class L_FAA : MapLoop
{
public L_FAA(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new FAA() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2480
public class L_AMT_1 : MapLoop
{
public L_AMT_1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new AMT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2500
public class L_LX : MapLoop
{
public L_LX(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LX() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
}
}
| |
///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// 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 Jim Heising 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.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Data;
using System.Windows.Forms;
using System.ComponentModel.Design;
namespace Controls
{
/// <summary>
/// Summary description for RoundedCornerPanel.
/// </summary>
///
[Designer("System.Windows.Forms.Design.ParentControlDesigner, System.Design", typeof(IDesigner))]
public class TabPanel : System.Windows.Forms.ScrollableControl
{
private int cornerRadius = 10;
private SolidBrush backBrush;
private Color panelColor = Color.White;
private Pen borderPen;
private GraphicsPath path;
private bool displayShadow = false;
private bool fadeShadow = true;
private int shadowOffset = 5;
private Color shadowColor = Color.Gray;
private bool selected = false;
private System.ComponentModel.Container components = null;
public TabPanel()
{
this.SetStyle(ControlStyles.SupportsTransparentBackColor | ControlStyles.UserPaint | ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
InitializeComponent();
this.DoubleBuffered = true;
backBrush = new SolidBrush(panelColor);
borderPen = new Pen(this.ForeColor, 1.0f);
path = new GraphicsPath();
CreateGraphicsPath();
}
private void CreateGraphicsPath()
{
int cornerDiameter = cornerRadius * 2;
path.Reset();
int halfBorderWidth = (int)(borderPen.Width / 2);
if (displayShadow)
{
path.AddArc(halfBorderWidth, halfBorderWidth, cornerDiameter, cornerDiameter, 180, 90);
if (!selected)
{
path.AddLine(this.Width - 1, 0, this.Width - 1, this.Height - shadowOffset - 1);
}
else
{
path.AddLine(this.Width + 1, 0, this.Width + 1, this.Height - shadowOffset - 1);
}
path.AddArc(halfBorderWidth, this.Height - cornerDiameter - halfBorderWidth - shadowOffset - 1, cornerDiameter, cornerDiameter, 90, 90);
}
else
{
path.AddArc(halfBorderWidth, halfBorderWidth, cornerDiameter, cornerDiameter, 180, 90);
if (!selected)
{
path.AddLine(this.Width - 1, 0, this.Width - 1, this.Height - 1);
}
else
{
path.AddLine(this.Width + 1, 0, this.Width + 1, this.Height - 1);
}
path.AddArc(halfBorderWidth, this.Height - cornerDiameter - halfBorderWidth - 1, cornerDiameter, cornerDiameter, 90, 90);
}
path.CloseFigure();
}
public bool Selected
{
get
{
return selected;
}
set
{
selected = value;
CreateGraphicsPath();
this.Invalidate();
}
}
/*private void Redraw()
{
this.Draw(null);
}*/
protected override void OnForeColorChanged(EventArgs e)
{
borderPen.Color = this.ForeColor;
this.Invalidate();
base.OnForeColorChanged(e);
}
public float BorderSize
{
get
{
return borderPen.Width;
}
set
{
borderPen.Width = value;
CreateGraphicsPath();
this.Invalidate();
}
}
protected override void OnBackColorChanged(EventArgs e)
{
base.OnBackColorChanged(e);
this.Invalidate();
}
public Color ShadowColor
{
get
{
return shadowColor;
}
set
{
shadowColor = value;
this.Invalidate();
}
}
/*public bool FadeShadow
{
get
{
return fadeShadow;
}
set
{
fadeShadow = value;
this.Invalidate();
}
}*/
public bool DisplayShadow
{
get
{
return displayShadow;
}
set
{
this.displayShadow = value;
CreateGraphicsPath();
this.Invalidate();
}
}
public int ShadowOffset
{
get
{
return shadowOffset;
}
set
{
shadowOffset = value;
CreateGraphicsPath();
this.Invalidate();
}
}
public Color PanelColor
{
get
{
return panelColor;
}
set
{
panelColor = value;
backBrush.Color = value;
this.Invalidate();
}
}
public int CornerRadius
{
get
{
return cornerRadius;
}
set
{
cornerRadius = value;
CreateGraphicsPath();
this.Invalidate();
}
}
protected override void OnPaint(PaintEventArgs e)
{
//e.Graphics.Clear(this.BackColor);
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
// Draw the shadow
if (displayShadow)
{
using (SolidBrush shadowBrush = new SolidBrush(shadowColor))
{
e.Graphics.TranslateTransform(shadowOffset, shadowOffset);
e.Graphics.FillPath(shadowBrush, path);
e.Graphics.ResetTransform();
}
}
e.Graphics.FillPath(backBrush, path);
e.Graphics.DrawPath(borderPen, path);
// If not selected, draw the page shadow
if (!selected)
{
using (LinearGradientBrush gradBrush = new LinearGradientBrush(new Point(this.Width - 6, 0), new Point(this.Width, 0), Color.FromArgb(0, 0, 0, 0), Color.FromArgb(100, 0, 0, 0)))
{
e.Graphics.FillRectangle(gradBrush, this.Width - 5, 0, 5, this.Height);
}
}
}
/*protected override void OnPaintBackground(PaintEventArgs pevent)
{
base.OnPaintBackground (pevent);
}*/
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Component 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()
{
//
// RoundedCornerPanel
//
this.Name = "RoundedCornerPanel";
this.Size = new System.Drawing.Size(144, 88);
this.Resize += new System.EventHandler(this.RoundedCornerPanel_Resize);
}
#endregion
private void RoundedCornerPanel_Resize(object sender, System.EventArgs e)
{
CreateGraphicsPath();
this.Invalidate();
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.PythonTools.Analysis;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Intellisense;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Language;
using Microsoft.PythonTools.Parsing;
using Microsoft.PythonTools.Parsing.Ast;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudioTools;
using Microsoft.VisualStudioTools.Navigation;
using Microsoft.VisualStudioTools.Project;
namespace Microsoft.PythonTools.Navigation {
internal class PythonLibraryNode : CommonLibraryNode {
private readonly CompletionResult _value;
public PythonLibraryNode(LibraryNode parent, CompletionResult value, IVsHierarchy hierarchy, uint itemId, IList<LibraryNode> children)
: base(parent, value.Name, value.Name, hierarchy, itemId, GetLibraryNodeType(value, parent), children: children) {
_value = value;
bool hasLocation = false;
foreach (var completion in value.Values) {
if (completion.locations.Any()) {
hasLocation = true;
}
}
if (hasLocation) {
CanGoToSource = true;
}
}
private static LibraryNodeType GetLibraryNodeType(CompletionResult value, LibraryNode parent) {
switch (value.MemberType) {
case PythonMemberType.Class:
return LibraryNodeType.Classes;
case PythonMemberType.Function:
//if (parent is PythonFileLibraryNode) {
// return LibraryNodeType.Classes | LibraryNodeType.Members;
//}
return LibraryNodeType.Members;
default:
return LibraryNodeType.Members;
}
}
protected PythonLibraryNode(PythonLibraryNode node) : base(node) {
_value = node._value;
}
protected PythonLibraryNode(PythonLibraryNode node, string newFullName) : base(node, newFullName) {
_value = node._value;
}
public override LibraryNode Clone() {
return new PythonLibraryNode(this);
}
public override LibraryNode Clone(string newFullName) {
return new PythonLibraryNode(this, newFullName);
}
public override StandardGlyphGroup GlyphType {
get {
switch (_value.MemberType) {
case PythonMemberType.Class:
return StandardGlyphGroup.GlyphGroupClass;
case PythonMemberType.Method:
case PythonMemberType.Function:
return StandardGlyphGroup.GlyphGroupMethod;
case PythonMemberType.Field:
case PythonMemberType.Instance:
return StandardGlyphGroup.GlyphGroupField;
case PythonMemberType.Constant:
return StandardGlyphGroup.GlyphGroupConstant;
case PythonMemberType.Module:
return StandardGlyphGroup.GlyphGroupModule;
default:
return StandardGlyphGroup.GlyphGroupUnknown;
}
}
}
public override string GetTextRepresentation(VSTREETEXTOPTIONS options) {
StringBuilder res = new StringBuilder();
foreach (var value in _value.Values) {
bool isAlias = false;
foreach (var desc in value.description) {
if (desc.kind == "name") {
if (desc.text != Name) {
isAlias = true;
}
}
}
if (isAlias) {
res.Append(Name);
res.Append(" (alias of ");
}
foreach (var desc in value.description) {
if (desc.kind == "enddecl") {
break;
}
res.Append(desc.text);
}
if (isAlias) {
res.Append(")");
}
}
if (res.Length == 0) {
return Name;
}
return res.ToString();
}
public override void FillDescription(_VSOBJDESCOPTIONS flags, IVsObjectBrowserDescription3 description) {
description.ClearDescriptionText();
foreach (var value in _value.Values) {
foreach (var desc in value.description) {
VSOBDESCRIPTIONSECTION kind;
switch (desc.kind) {
case "enddecl": kind = VSOBDESCRIPTIONSECTION.OBDS_ENDDECL; break;
case "name": kind = VSOBDESCRIPTIONSECTION.OBDS_NAME; break;
case "param": kind = VSOBDESCRIPTIONSECTION.OBDS_PARAM; break;
case "comma": kind = VSOBDESCRIPTIONSECTION.OBDS_COMMA; break;
default: kind = VSOBDESCRIPTIONSECTION.OBDS_MISC; break;
}
description.AddDescriptionText3(desc.text, kind, null);
}
}
}
public override void GotoSource(VSOBJGOTOSRCTYPE gotoType) {
// We do not support the "Goto Reference"
if (VSOBJGOTOSRCTYPE.GS_REFERENCE == gotoType) {
return;
}
foreach (var completion in _value.Values) {
foreach (var location in completion.locations) {
if (File.Exists(location.file)) {
PythonToolsPackage.NavigateTo(
Site,
location.file,
Guid.Empty,
location.line - 1,
location.column - 1
);
break;
}
}
}
}
public override IVsSimpleObjectList2 FindReferences() {
var analyzer = this.Hierarchy.GetPythonProject().GetAnalyzer();
List<AnalysisVariable> vars = new List<AnalysisVariable>();
if (analyzer != null) {
foreach (var value in _value.Values) {
foreach (var reference in value.locations) {
var entry = analyzer.GetAnalysisEntryFromPath(reference.file);
var analysis = VsProjectAnalyzer.AnalyzeExpressionAsync(
entry,
Name,
new SourceLocation(0, reference.line, reference.column)
).WaitOrDefault(1000);
vars.AddRange(analysis.Variables);
}
}
}
return EditFilter.GetFindRefLocations(
analyzer,
Site,
Name,
vars.ToArray()
);
}
public override int GetLibGuid(out Guid pGuid) {
pGuid = new Guid(CommonConstants.LibraryGuid);
return VSConstants.S_OK;
}
}
}
| |
using System;
using System.Collections.Generic;
using Skybrud.Essentials.Common;
using Skybrud.Essentials.Http;
using Skybrud.Essentials.Http.Client;
using Skybrud.Essentials.Http.Collections;
using Skybrud.Social.Google.Http;
using Skybrud.Social.Google.Options.Authentication;
using Skybrud.Social.Google.Responses.Authentication;
using Skybrud.Social.Google.Scopes;
namespace Skybrud.Social.Google.OAuth {
/// <summary>
/// A client for handling the communication with the Google APIs using OAuth 2.0. The client is also responsible
/// for the raw communication with the various Google APIs.
/// </summary>
public class GoogleOAuthClient : HttpClient {
private readonly Dictionary<Type, GoogleApiHttpClientBase> _apis = new Dictionary<Type, GoogleApiHttpClientBase>();
#region Properties
/// <summary>
/// Gets or sets the ID of the client/application.
/// </summary>
public string ClientId { get; set; }
/// <summary>
/// Gets or sets the the secret of the client/application. Guard this with your life!
/// </summary>
public string ClientSecret { get; set; }
/// <summary>
/// Gets or sets the redirect URL. Must be specified in Google's APIs console.
/// </summary>
public string RedirectUri { get; set; }
/// <summary>
/// Gets or sets the access token.
/// </summary>
public string AccessToken { get; set; }
/// <summary>
/// Gets or sets the server key.
/// </summary>
public string ServerKey { get; set; }
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance with default options.
/// </summary>
public GoogleOAuthClient() { }
/// <summary>
/// Initializes a new instance based on the specified <paramref name="accessToken"/>.
/// </summary>
/// <param name="accessToken">The access token of the user.</param>
public GoogleOAuthClient(string accessToken) {
AccessToken = accessToken;
}
/// <summary>
/// Initializes a new instance based on the specified <paramref name="clientId"/>, <paramref name="clientSecret"/> and <paramref name="redirectUri"/>.
/// </summary>
/// <param name="clientId">The ID of the client/application.</param>
/// <param name="clientSecret">The secret of the client/application.</param>
/// <param name="redirectUri">The redirect URI of the client/application.</param>
public GoogleOAuthClient(string clientId, string clientSecret, string redirectUri) {
ClientId = clientId;
ClientSecret = clientSecret;
RedirectUri = redirectUri;
}
#endregion
#region Methods
/// <summary>
/// Gets the authorization URL at accounts.google.com for your application.
/// </summary>
/// <param name="state">The state of the application.</param>
/// <param name="scope">The scope of the application.</param>
public string GetAuthorizationUrl(string state, string scope) {
return GetAuthorizationUrl(new GoogleAuthorizeOptions(state, scope));
}
/// <summary>
/// Gets the authorization URL at accounts.google.com for your application.
/// </summary>
/// <param name="state">The state of the application.</param>
/// <param name="scope">The scope of the application.</param>
/// <param name="offline">Whether the application should be enabled for offline access.</param>
public string GetAuthorizationUrl(string state, string scope, bool offline) {
return GetAuthorizationUrl(new GoogleAuthorizeOptions(state, scope, offline ? GoogleAccessType.Offline : GoogleAccessType.Online));
}
/// <summary>
/// Gets the authorization URL at accounts.google.com for your application.
/// </summary>
/// <param name="state">The state of the application.</param>
/// <param name="scope">The scope of the application.</param>
public string GetAuthorizationUrl(string state, GoogleScopeCollection scope) {
return GetAuthorizationUrl(new GoogleAuthorizeOptions(state, scope));
}
/// <summary>
/// Gets the authorization URL at accounts.google.com for your application.
/// </summary>
/// <param name="state">The state of the application.</param>
/// <param name="scope">The scope of the application.</param>
/// <param name="offline">Whether the application should be enabled for offline access.</param>
public string GetAuthorizationUrl(string state, GoogleScopeCollection scope, bool offline) {
return GetAuthorizationUrl(new GoogleAuthorizeOptions(state, scope, offline ? GoogleAccessType.Offline : GoogleAccessType.Online));
}
/// <summary>
/// Gets the authorization URL at accounts.google.com for your application.
/// </summary>
/// <param name="state">The state of the application.</param>
/// <param name="scope">The scope of the application.</param>
/// <param name="accessType">Whether the application should be enabled for offline access.</param>
/// <param name="prompt">A list of prompts to present the user. If <see cref="GooglePromptOption.None"/>, the user will be prompted only the first time your app requests access.</param>
public string GetAuthorizationUrl(string state, string scope, GoogleAccessType accessType, GooglePromptOption prompt) {
return GetAuthorizationUrl(new GoogleAuthorizeOptions(state, scope, accessType, prompt));
}
/// <summary>
/// Gets the authorization URL at accounts.google.com for your application.
/// </summary>
/// <param name="state">The state of the application.</param>
/// <param name="scope">The scope of the application.</param>
/// <param name="accessType">Whether the application should be enabled for offline access.</param>
/// <param name="prompt">A list of prompts to present the user. If <see cref="GooglePromptOption.None"/>, the user will be prompted only the first time your app requests access.</param>
public string GetAuthorizationUrl(string state, GoogleScopeCollection scope, GoogleAccessType accessType, GooglePromptOption prompt) {
return GetAuthorizationUrl(new GoogleAuthorizeOptions(state, scope, accessType, prompt));
}
/// <summary>
/// Gets the authorization URL at accounts.google.com for your application.
/// </summary>
/// <param name="options">The options for generating an authorization URL.</param>
public string GetAuthorizationUrl(GoogleAuthorizeOptions options) {
if (options == null) throw new ArgumentNullException(nameof(options));
return "https://accounts.google.com/o/oauth2/auth?" + options.GetQueryString(this);
}
/// <summary>
/// Returns an instance of <see cref="GoogleTokenResponse"/> with information about an access token exchanged
/// from the specified authorization <paramref name="code"/>.
/// </summary>
/// <param name="code">The authorization code.</param>
/// <returns>An instance of <see cref="GoogleTokenResponse"/>.</returns>
public GoogleTokenResponse GetAccessTokenFromAuthorizationCode(string code) {
// Validate the required parameters and properties
if (string.IsNullOrWhiteSpace(code)) throw new ArgumentNullException(nameof(code));
if (string.IsNullOrWhiteSpace(ClientId)) throw new PropertyNotSetException(nameof(ClientId));
if (string.IsNullOrWhiteSpace(ClientSecret)) throw new PropertyNotSetException(nameof(ClientSecret));
if (string.IsNullOrWhiteSpace(RedirectUri)) throw new PropertyNotSetException(nameof(RedirectUri));
// Declare the POST data
IHttpPostData postData = new HttpPostData();
postData.Add("code", code);
postData.Add("client_id", ClientId);
postData.Add("client_secret", ClientSecret);
postData.Add("redirect_uri", RedirectUri);
postData.Add("grant_type", "authorization_code");
// Initialize the request
HttpRequest request = HttpRequest.Post("https://accounts.google.com/o/oauth2/token", postData);
// Make the request to the server
IHttpResponse response = request.GetResponse();
// Parse the JSON response
return GoogleTokenResponse.ParseResponse(response);
}
/// <summary>
/// Returns an instance of <see cref="GoogleTokenResponse"/> with information about an access token exchanged
/// from the specified <paramref name="refreshToken"/>.
/// </summary>
/// <param name="refreshToken">The refresh token to exchange for a new access token.</param>
/// <returns>An instance of <see cref="GoogleTokenResponse"/>.</returns>
public GoogleTokenResponse GetAccessTokenFromRefreshToken(string refreshToken) {
// Validate the required parameters and properties
if (string.IsNullOrWhiteSpace(refreshToken)) throw new ArgumentNullException(nameof(refreshToken));
if (string.IsNullOrWhiteSpace(ClientId)) throw new PropertyNotSetException(nameof(ClientId));
if (string.IsNullOrWhiteSpace(ClientSecret)) throw new PropertyNotSetException(nameof(ClientSecret));
// Declare the POST data
IHttpPostData postData = new HttpPostData();
postData.Add("client_id", ClientId);
postData.Add("client_secret", ClientSecret);
postData.Add("refresh_token", refreshToken);
postData.Add("grant_type", "refresh_token");
// Initialize the request
HttpRequest request = HttpRequest.Post("https://accounts.google.com/o/oauth2/token", postData);
// Make the request to the server
IHttpResponse response = request.GetResponse();
// Parse the JSON response
return GoogleTokenResponse.ParseResponse(response);
}
/// <summary>
/// Gets information about the authenticated user.
/// </summary>
public IHttpResponse GetUserInfo() {
return Get("https://www.googleapis.com/oauth2/v2/userinfo");
}
/// <summary>
/// Returns the raw API implementation of type <typeparamref name="T"/>.
///
/// If an implementation of type <typeparamref name="T"/> hasn't yet been registered,
/// <paramref name="callback"/> will be used to initialize and register an implementation.
/// </summary>
/// <typeparam name="T">The type of the raw API implementation.</typeparam>
/// <param name="callback"></param>
/// <returns>An instance of <typeparamref name="T"/>.</returns>
public T GetApiClient<T>(Func<T> callback) where T : GoogleApiHttpClientBase {
Type type = typeof(T);
if (_apis.TryGetValue(type, out GoogleApiHttpClientBase api)) return (T) api;
T e = callback();
_apis.Add(type, e);
return e;
}
/// <summary>
/// Virtual method that can be used for configuring a request.
/// </summary>
/// <param name="request">The instance of <see cref="IHttpRequest"/> representing the request.</param>
protected override void PrepareHttpRequest(IHttpRequest request) {
// Append the access token or server if specified
if (!string.IsNullOrWhiteSpace(AccessToken)) {
// TODO: Specify access token in HTTP header instead
request.QueryString.Set("access_token", AccessToken);
} else if (!string.IsNullOrWhiteSpace(ServerKey)) {
request.QueryString.Set("key", ServerKey);
}
// Prepend scheme and host name if not already specified
if (request.Url.StartsWith("/")) request.Url = "https://www.googleapis.com" + request.Url;
}
#endregion
}
}
| |
/* Distributed as part of TiledSharp, Copyright 2012 Marshall Ward
* Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0 */
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Xml.Linq;
namespace TiledSharp
{
// TODO: The design here is all wrong. A Tileset should be a list of tiles,
// it shouldn't force the user to do so much tile ID management
public class TmxTileset : TmxDocument, ITmxElement
{
public int FirstGid {get; private set;}
public string Name {get; private set;}
public int TileWidth {get; private set;}
public int TileHeight {get; private set;}
public int Spacing {get; private set;}
public int Margin {get; private set;}
public int? TileCount {get; private set;}
public Collection<TmxTilesetTile> Tiles {get; private set;}
public TmxTileOffset TileOffset {get; private set;}
public PropertyDict Properties {get; private set;}
public TmxImage Image {get; private set;}
public TmxList<TmxTerrain> Terrains {get; private set;}
// TSX file constructor
public TmxTileset(XContainer xDoc, string tmxDir) :
this(xDoc.Element("tileset"), tmxDir) { }
// TMX tileset element constructor
public TmxTileset(XElement xTileset, string tmxDir = "")
{
var xFirstGid = xTileset.Attribute("firstgid");
var source = (string) xTileset.Attribute("source");
if (source != null)
{
// Prepend the parent TMX directory if necessary
source = Path.Combine(tmxDir, source);
// source is always preceded by firstgid
FirstGid = (int) xFirstGid;
// Everything else is in the TSX file
var xDocTileset = ReadXml(source);
var ts = new TmxTileset(xDocTileset, TmxDirectory);
Name = ts.Name;
TileWidth = ts.TileWidth;
TileHeight = ts.TileHeight;
Spacing = ts.Spacing;
Margin = ts.Margin;
TileCount = ts.TileCount;
TileOffset = ts.TileOffset;
Image = ts.Image;
Terrains = ts.Terrains;
Tiles = ts.Tiles;
Properties = ts.Properties;
}
else
{
// firstgid is always in TMX, but not TSX
if (xFirstGid != null)
FirstGid = (int) xFirstGid;
Name = (string) xTileset.Attribute("name");
TileWidth = (int) xTileset.Attribute("tilewidth");
TileHeight = (int) xTileset.Attribute("tileheight");
Spacing = (int?) xTileset.Attribute("spacing") ?? 0;
Margin = (int?) xTileset.Attribute("margin") ?? 0;
TileCount = (int?) xTileset.Attribute("tilecount");
TileOffset = new TmxTileOffset(xTileset.Element("tileoffset"));
Image = new TmxImage(xTileset.Element("image"), tmxDir);
Terrains = new TmxList<TmxTerrain>();
var xTerrainType = xTileset.Element("terraintypes");
if (xTerrainType != null) {
foreach (var e in xTerrainType.Elements("terrain"))
Terrains.Add(new TmxTerrain(e));
}
Tiles = new Collection<TmxTilesetTile>();
foreach (var xTile in xTileset.Elements("tile"))
{
var tile = new TmxTilesetTile(xTile, Terrains, tmxDir);
Tiles.Add(tile);
}
Properties = new PropertyDict(xTileset.Element("properties"));
}
}
}
public class TmxTileOffset
{
public int X {get; private set;}
public int Y {get; private set;}
public TmxTileOffset(XElement xTileOffset)
{
if (xTileOffset == null) {
X = 0;
Y = 0;
} else {
X = (int)xTileOffset.Attribute("x");
Y = (int)xTileOffset.Attribute("y");
}
}
}
public class TmxTerrain : ITmxElement
{
public string Name {get; private set;}
public int Tile {get; private set;}
public PropertyDict Properties {get; private set;}
public TmxTerrain(XElement xTerrain)
{
Name = (string)xTerrain.Attribute("name");
Tile = (int)xTerrain.Attribute("tile");
Properties = new PropertyDict(xTerrain.Element("properties"));
}
}
public class TmxTilesetTile
{
public int Id {get; private set;}
public Collection<TmxTerrain> TerrainEdges {get; private set;}
public double Probability {get; private set;}
public PropertyDict Properties {get; private set;}
public TmxImage Image {get; private set;}
public TmxList<TmxObjectGroup> ObjectGroups {get; private set;}
public Collection<TmxAnimationFrame> AnimationFrames {get; private set;}
// Human-readable aliases to the Terrain markers
public TmxTerrain TopLeft {
get { return TerrainEdges[0]; }
}
public TmxTerrain TopRight {
get { return TerrainEdges[1]; }
}
public TmxTerrain BottomLeft {
get { return TerrainEdges[2]; }
}
public TmxTerrain BottomRight {
get { return TerrainEdges[3]; }
}
public TmxTilesetTile(XElement xTile, TmxList<TmxTerrain> Terrains,
string tmxDir = "")
{
Id = (int)xTile.Attribute("id");
TerrainEdges = new Collection<TmxTerrain>();
int result;
TmxTerrain edge;
var strTerrain = (string)xTile.Attribute("terrain") ?? ",,,";
foreach (var v in strTerrain.Split(',')) {
var success = int.TryParse(v, out result);
if (success)
edge = Terrains[result];
else
edge = null;
TerrainEdges.Add(edge);
// TODO: Assert that TerrainEdges length is 4
}
Probability = (double?)xTile.Attribute("probability") ?? 1.0;
Image = new TmxImage(xTile.Element("image"), tmxDir);
ObjectGroups = new TmxList<TmxObjectGroup>();
foreach (var e in xTile.Elements("objectgroup"))
ObjectGroups.Add(new TmxObjectGroup(e));
AnimationFrames = new Collection<TmxAnimationFrame>();
if (xTile.Element("animation") != null) {
foreach (var e in xTile.Element("animation").Elements("frame"))
AnimationFrames.Add(new TmxAnimationFrame(e));
}
Properties = new PropertyDict(xTile.Element("properties"));
}
}
public class TmxAnimationFrame
{
public int Id {get; private set;}
public int Duration {get; private set;}
public TmxAnimationFrame(XElement xFrame)
{
Id = (int)xFrame.Attribute("tileid");
Duration = (int)xFrame.Attribute("duration");
}
}
}
| |
#define RunBuildingKnowledgeInNewThread7
using System;
using System.Configuration;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using Knowledge.Prospector.Common.Settings;
using Knowledge.Prospector.Common.Utilites;
using Knowledge.Prospector.Data.Collections;
using Knowledge.Prospector.Dictionaries;
using Knowledge.Prospector.IO;
using Knowledge.Prospector.IO.Articles;
using Knowledge.Prospector.IO.Documents;
using Knowledge.Prospector.IO.Documents.Providers;
using Knowledge.Prospector.Templates;
using Knowledge.Prospector.Templates.Handlers;
using Knowledge.Prospector.UIEnvironment.Resources;
namespace Knowledge.Prospector.UIEnvironment
{
public partial class KnowledgeBuilder : Form
{
private ProviderConfiguration<IOntology> _OnologyConfig = ConfigurationManager.GetSection("ontologies") as ProviderConfiguration<IOntology>;
private ProviderConfiguration<IDocumentProvider> _DocumentProviderConfig = ConfigurationManager.GetSection("documentProviders") as ProviderConfiguration<IDocumentProvider>;
public KnowledgeBuilder()
{
InitializeComponent();
}
private void Main_Load(object sender, EventArgs e)
{
txtDocumentsProviderSettings.Text = UISettings.Default.DocumentsProviderSettings;
txtOutputFileName.Text = UISettings.Default.OutputOntologySettings;
txtLoadFromDumpFileName.Text = UISettings.Default.LoadFromDumpFileName;
txtAddToDumpFileName.Text = UISettings.Default.SaveToDumpFileName;
cbOutputOntologyProvider.Items.AddRange(_OnologyConfig.Providers.ToArray());
cbOutputOntologyProvider.SelectedIndex = _OnologyConfig.GetIndex(UISettings.Default.OutputOntologyProviderName);
cbDocumentProviderProvider.Items.AddRange(_DocumentProviderConfig.Providers.ToArray());
cbDocumentProviderProvider.SelectedIndex = _DocumentProviderConfig.GetIndex(UISettings.Default.DocumentsProviderProviderName);
}
private void cbLoadFromDump_CheckedChanged(object sender, EventArgs e)
{
cmdBrowseLoadFromDumpFileName.Visible = cbLoadFromDump.Checked;
txtLoadFromDumpFileName.Visible = cbLoadFromDump.Checked;
}
private void cbAddToDump_CheckedChanged(object sender, EventArgs e)
{
cmdBrowseAddToDumpFileName.Visible = cbAddToDump.Checked;
txtAddToDumpFileName.Visible = cbAddToDump.Checked;
}
private void bBrowseLoadFromDumpFileName_Click(object sender, EventArgs e)
{
Utilities.OpenFile(txtLoadFromDumpFileName, PathUtils.DataPath + @"\Results\");
}
private void bBrowseAddToDumpFileName_Click(object sender, EventArgs e)
{
Utilities.OpenFile(txtAddToDumpFileName, PathUtils.DataPath + @"\Results\");
}
private void SaveUserSettings()
{
UISettings.Default.DocumentsProviderSettings = txtDocumentsProviderSettings.Text;
UISettings.Default.OutputOntologySettings = txtOutputFileName.Text;
UISettings.Default.LoadFromDumpFileName = txtLoadFromDumpFileName.Text;
UISettings.Default.SaveToDumpFileName = txtAddToDumpFileName.Text;
UISettings.Default.OutputOntologyProviderName = cbOutputOntologyProvider.SelectedIndex != -1
?
_OnologyConfig.Providers[cbOutputOntologyProvider.SelectedIndex].Name
: string.Empty;
UISettings.Default.DocumentsProviderProviderName = cbDocumentProviderProvider.SelectedIndex != -1
?
_DocumentProviderConfig.Providers[
cbDocumentProviderProvider.SelectedIndex].Name
: string.Empty;
UISettings.Default.Save();
}
private void bBuildKnowledges_Click(object sender, EventArgs e)
{
SaveUserSettings();
#if RunBuildingKnowledgeInNewThread
Thread t = new Thread(new ThreadStart(BuildKnowledges));
t.Start();
// t.Join();
#else
BuildKnowledges();
#endif
}
private bool IsInited = false;
public void BuildKnowledges()
{
#region UI
this.Cursor = Cursors.WaitCursor;
StatusLabel1.Text = Messages.InitializingDictionaries;
#endregion
if (!IsInited)
{
//Need to implement IsInited in new option handlers!
ShortcutManager.Instance.Init(ConfigurationManager.GetSection("shortcutManager"));
ClauseHolderManager.Instance.Init(ConfigurationManager.GetSection("clauseHolderManager"));
WordHolderManager.Instance.Init(ConfigurationManager.GetSection("wordHolderManager"));
EntityTemplateManager.GetInstance().Init(ConfigurationManager.GetSection("entityTemplateManager"));
//Init dictionaries
if (!DictionaryManager.GetInstance().IsInited)
{
DictionaryManager.GetInstance().Init((DictionaryManagerOptions)ConfigurationManager.GetSection("dictionaryManager"));
}
IsInited = true;
}
#region UI
DateTime startDT = DateTime.Now;
#endregion
//Reading file
#region UI
StatusLabel1.Text = Messages.ReadingSource;
#endregion
Provider<IDocumentProvider> documentProviderProvider = _DocumentProviderConfig[cbDocumentProviderProvider.Text];
IDocumentProvider documentProvider = documentProviderProvider.CreateProvidedClassInstance();
documentProvider.Init(txtDocumentsProviderSettings.Text);
//Graph
EntityGraph entityGraph;
if (cbLoadFromDump.Checked)
{
try
{
entityGraph = EntityGraph.LoadDump(txtLoadFromDumpFileName.Text);
}
catch
{
if (DialogResult.OK == MessageBox.Show("Ignore?", "Cannot load dump", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
entityGraph = new EntityGraph();
else
return;
}
}
else
entityGraph = new EntityGraph();
foreach (IDocument document in documentProvider)
{
foreach (IArticle article in document)
{
//Prospecting
#region UI
StatusLabel1.Text = Messages.Translating;
#endregion
IProspector prospector = ProspectorManager.Instance.GetProspector(article);
prospector.Prospect(entityGraph, article);
}
document.Close();
}
documentProvider.Close();
//Optimizing the graph
#region UI
StatusLabel1.Text = Messages.OptimizingGraph;
#endregion
EntityGraphOptimizer entityGraphOptimizer = new EntityGraphOptimizer(entityGraph);
entityGraphOptimizer.OptimizeSubclassRelationship();
entityGraphOptimizer.OptimizePropertyRelationships();
//Saving Graph to file
#region UI
StatusLabel1.Text = Messages.SavingGraph;
#endregion
Provider<IOntology> outputOntologyProvider = _OnologyConfig[cbOutputOntologyProvider.Text];
IOntology outputOntology = outputOntologyProvider.CreateProvidedClassInstance();
outputOntology.SaveGraph(entityGraph, txtOutputFileName.Text);
if(cbAddToDump.Checked)
entityGraph.Dump(txtAddToDumpFileName.Text);
#region UI
DateTime stopDT = DateTime.Now;
TimeSpan ts = stopDT - startDT;
StatusLabel1.Text = string.Format(Messages.BuildingCompliteFormat, ts.TotalMilliseconds);
StatusProgressBar1.Visible = false;
this.Cursor = Cursors.Default;
MessageBox.Show(string.Format("Done by {0} milliseconds", ts.TotalMilliseconds), "Knowledge Prospector", MessageBoxButtons.OK, MessageBoxIcon.Information);
#endregion
GC.Collect();
}
void translator_OnPartComplite()
{
StatusProgressBar1.PerformStep();
}
private void cmdBrowseOutputFile_Click(object sender, EventArgs e)
{
Utilities.OpenFile(txtOutputFileName, Path.Combine(PathUtils.DataPath, @"\Results\"));
}
protected Provider<IDocumentProvider> SelectedDocumentsProviderProvider
{
get { return _DocumentProviderConfig[cbDocumentProviderProvider.Text]; }
}
private void cmdEditDocumentsProviderOptions_Click(object sender, EventArgs e)
{
IProviderOptionsPlugin plugin = SelectedDocumentsProviderProvider.CreatePluginInstance();
plugin.OnPluginClosed += new PluginClosedEventHandler(plugin_OnPluginClosed);
plugin.ProviderOptions = txtDocumentsProviderSettings.Text;
plugin.ShowPlugin();
}
void plugin_OnPluginClosed(IProviderOptionsPlugin sender, PluginClosedEventArgs e)
{
if(e.OK)
txtDocumentsProviderSettings.Text = sender.ProviderOptions;
sender.OnPluginClosed -= plugin_OnPluginClosed;
}
}
}
| |
namespace AngleSharp.Css.Values
{
using System;
/// <summary>
/// Represents a transformation matrix value.
/// http://dev.w3.org/csswg/css-transforms/#mathematical-description
/// </summary>
public class TransformMatrix : IEquatable<TransformMatrix>
{
#region Fields
/// <summary>
/// Gets the zero matrix.
/// </summary>
public static readonly TransformMatrix Zero = new TransformMatrix();
/// <summary>
/// Gets the unity matrix.
/// </summary>
public static readonly TransformMatrix One = new TransformMatrix(1f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 0f, 0f);
private readonly Double[,] _matrix;
#endregion
#region ctor
private TransformMatrix()
{
_matrix = new Double[4, 4];
}
/// <summary>
/// Creates a new transformation matrix from a 1D-array.
/// </summary>
/// <param name="values">The array with values.</param>
public TransformMatrix(Double[] values)
: this()
{
if (values == null)
throw new ArgumentNullException(nameof(values));
if (values.Length != 16)
throw new ArgumentException("You need to provide 16 (4x4) values.", nameof(values));
var k = 0;
for (var i = 0; i < 4; i++)
{
for (var j = 0; j < 4; j++, k++)
{
_matrix[j, i] = values[k];
}
}
}
/// <summary>
/// Creates a transformation matrix.
/// </summary>
/// <param name="m11">The (1, 1) entry.</param>
/// <param name="m12">The (1, 2) entry.</param>
/// <param name="m13">The (1, 3) entry.</param>
/// <param name="m21">The (2, 1) entry.</param>
/// <param name="m22">The (2, 2) entry.</param>
/// <param name="m23">The (2, 3) entry.</param>
/// <param name="m31">The (3, 1) entry.</param>
/// <param name="m32">The (3, 2) entry.</param>
/// <param name="m33">The (3, 3) entry.</param>
/// <param name="tx">The x-translation entry.</param>
/// <param name="ty">The y-translation entry.</param>
/// <param name="tz">The z-translation entry.</param>
/// <param name="px">The x-perspective entry.</param>
/// <param name="py">The y-perspective entry.</param>
/// <param name="pz">The z-perspective entry.</param>
public TransformMatrix(
Double m11, Double m12, Double m13,
Double m21, Double m22, Double m23,
Double m31, Double m32, Double m33,
Double tx, Double ty, Double tz,
Double px, Double py, Double pz)
: this()
{
_matrix[0, 0] = m11;
_matrix[0, 1] = m12;
_matrix[0, 2] = m13;
_matrix[1, 0] = m21;
_matrix[1, 1] = m22;
_matrix[1, 2] = m23;
_matrix[2, 0] = m31;
_matrix[2, 1] = m32;
_matrix[2, 2] = m33;
_matrix[0, 3] = tx;
_matrix[1, 3] = ty;
_matrix[2, 3] = tz;
_matrix[3, 0] = px;
_matrix[3, 1] = py;
_matrix[3, 2] = pz;
_matrix[3, 3] = 1f;
}
#endregion
#region Properties
/// <summary>
/// Gets the element at the specified indices.
/// </summary>
/// <param name="row">The row index.</param>
/// <param name="col">The column index.</param>
/// <returns>The value of the cell.</returns>
public Double this[Int32 row, Int32 col] => _matrix[row, col];
/// <summary>
/// Gets the element of the 1st row, 1st column.
/// </summary>
public Double M11 => _matrix[0, 0];
/// <summary>
/// Gets the element of the 1st row, 2nd column.
/// </summary>
public Double M12 => _matrix[0, 1];
/// <summary>
/// Gets the element of the 1st row, 3rd column.
/// </summary>
public Double M13 => _matrix[0, 2];
/// <summary>
/// Gets the element of the 2nd row, 1st column.
/// </summary>
public Double M21 => _matrix[1, 0];
/// <summary>
/// Gets the element of the 2nd row, 2nd column.
/// </summary>
public Double M22 => _matrix[1, 1];
/// <summary>
/// Gets the element of the 2nd row, 3rd column.
/// </summary>
public Double M23 => _matrix[1, 2];
/// <summary>
/// Gets the element of the 3rd row, 1st column.
/// </summary>
public Double M31 => _matrix[2, 0];
/// <summary>
/// Gets the element of the 3rd row, 2nd column.
/// </summary>
public Double M32 => _matrix[2, 1];
/// <summary>
/// Gets the element of the 3rd row, 3rd column.
/// </summary>
public Double M33 => _matrix[2, 2];
/// <summary>
/// Gets the x-element of the translation vector.
/// </summary>
public Double Tx => _matrix[0, 3];
/// <summary>
/// Gets the y-element of the translation vector.
/// </summary>
public Double Ty => _matrix[1, 3];
/// <summary>
/// Gets the z-element of the translation vector.
/// </summary>
public Double Tz => _matrix[2, 3];
#endregion
#region Methods
/// <summary>
/// Checks for equality with the given other transformation matrix.
/// </summary>
/// <param name="other">The other transformation matrix.</param>
/// <returns>True if all elements are equal, otherwise false.</returns>
public Boolean Equals(TransformMatrix other)
{
var A = _matrix;
var B = other._matrix;
for (var i = 0; i < 4; i++)
{
for (var j = 0; j < 4; j++)
{
if (A[i, j] != B[i, j])
{
return false;
}
}
}
return true;
}
#endregion
#region Equality
/// <summary>
/// Tests if another object is equal to this object.
/// </summary>
/// <param name="obj">The object to test with.</param>
/// <returns>True if the two objects are equal, otherwise false.</returns>
public override Boolean Equals(Object obj) => obj is TransformMatrix other ? Equals(other) : false;
/// <summary>
/// Returns a hash code that defines the current length.
/// </summary>
/// <returns>The integer value of the hashcode.</returns>
public override Int32 GetHashCode()
{
var sum = 0.0;
for (var i = 0; i < 4; i++)
{
for (var j = 0; j < 4; j++)
{
sum += _matrix[i, j] * (4 * i + j);
}
}
return (Int32)(sum);
}
#endregion
}
}
| |
/*
* Copyright (c) 2007-2021 IowaComputerGurus Inc (http://www.iowacomputergurus.com)
* Copyright Contact: webmaster@iowacomputergurus.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 DotNetNuke.Common;
using DotNetNuke.Entities.Modules;
using DotNetNuke.UI.UserControls;
using ICG.Modules.DnnQuiz.Components.Controllers;
using ICG.Modules.DnnQuiz.Components.InfoObjects;
namespace ICG.Modules.DnnQuiz
{
/// <summary>
/// UI for question editing
/// </summary>
public partial class EditQuizQuestion : PortalModuleBase
{
private int _questionId = -1;
private int _quizId = -1;
/// <summary>
/// DotNetNuke Text Editor Declaration for Runtime Support. DO NOT REMOVE!!
/// </summary>
protected TextEditor txtPromptTextRich;
/// <summary>
/// Handles the Load event of the Page control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
protected void Page_Load(object sender, EventArgs e)
{
//Load parameters
if (Request.QueryString["questionId"] != null)
_questionId = int.Parse(Request.QueryString["questionId"]);
if (Request.QueryString["quizId"] != null)
_quizId = int.Parse(Request.QueryString["quizId"]);
if (!IsPostBack)
{
if (_questionId > 0 && _quizId > 0)
{
//Load the question
var questionInfo = QuizController.GetQuizQuestion(_questionId, this.ModuleId);
if (questionInfo != null)
{
txtPromptTextRich.Text = questionInfo.PromptText;
txtAnswer1.Text = questionInfo.Answer1;
txtAnswer2.Text = questionInfo.Answer2;
txtAnswer3.Text = questionInfo.Answer3;
txtAnswer4.Text = questionInfo.Answer4;
txtAnswer5.Text = questionInfo.Answer5;
//Take action for correct answers
if (questionInfo.CorrectAnswer.Equals(txtAnswer1.Text))
ddlCorrectAnswer.SelectedValue = "1";
else if (questionInfo.CorrectAnswer.Equals(txtAnswer2.Text))
ddlCorrectAnswer.SelectedValue = "2";
else if (questionInfo.CorrectAnswer.Equals(txtAnswer3.Text))
ddlCorrectAnswer.SelectedValue = "3";
else if (questionInfo.CorrectAnswer.Equals(txtAnswer4.Text))
ddlCorrectAnswer.SelectedValue = "4";
else if (questionInfo.CorrectAnswer.Equals(txtAnswer5.Text))
ddlCorrectAnswer.SelectedValue = "5";
}
else
{
//Invalid question id, redirect as an add
Response.Redirect(EditUrl("questionId", "-1", "EditQuestion"));
}
}
else if (_quizId == -1)
{
//Invalid, direct back to the module
Response.Redirect(Globals.NavigateURL(this.TabId));
}
}
}
/// <summary>
/// Returns the user back to the quiz
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnCancel_Click(object sender, EventArgs e)
{
Response.Redirect(EditUrl("quizId", _quizId.ToString()));
}
/// <summary>
/// Handles the Click event of the btnSave control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
protected void btnSave_Click(object sender, EventArgs e)
{
//Clear all validation errors
lblAnswer3Required.Visible = false;
lblAnswer4Required.Visible = false;
lblInvalidAnswer.Visible = false;
//start nested validation
if (Page.IsValid)
{
if (IsCorrectAnswerValid())
{
if (IsAnswerListValid())
{
//We can now save the question
var toSave = new QuizQuestionInfo
{
QuestionId = _questionId,
QuizId = _quizId,
ModuleId = this.ModuleId,
PromptText = txtPromptTextRich.Text,
Answer1 = txtAnswer1.Text,
Answer2 = txtAnswer2.Text,
Answer3 = txtAnswer3.Text,
Answer4 = txtAnswer4.Text,
Answer5 = txtAnswer5.Text
};
//Save the correct answer
switch (ddlCorrectAnswer.SelectedValue)
{
case "1":
toSave.CorrectAnswer = txtAnswer1.Text;
break;
case "2":
toSave.CorrectAnswer = txtAnswer2.Text;
break;
case "3":
toSave.CorrectAnswer = txtAnswer3.Text;
break;
case "4":
toSave.CorrectAnswer = txtAnswer4.Text;
break;
case "5":
toSave.CorrectAnswer = txtAnswer5.Text;
break;
}
//Persist value
QuizController.SaveQuestion(toSave);
//Call cancel to redirect
btnCancel_Click(sender, e);
}
}
}
}
/// <summary>
/// Validates that the selected option actually has a value.
/// </summary>
/// <returns></returns>
private bool IsCorrectAnswerValid()
{
var returnValue = false;
switch (ddlCorrectAnswer.SelectedValue)
{
case "1":
case "2":
//Validators guarantee this one
returnValue = true;
break;
case "3":
if(txtAnswer3.Text.Length == 0)
lblInvalidAnswer.Visible = true;
else
returnValue = true;
break;
case "4":
if(txtAnswer4.Text.Length == 0)
lblInvalidAnswer.Visible = true;
else
returnValue = true;
break;
case "5":
if(txtAnswer5.Text.Length == 0)
lblInvalidAnswer.Visible = true;
else
returnValue = true;
break;
}
return returnValue;
}
/// <summary>
/// Validates that proper answer ordering is completed
/// </summary>
/// <returns></returns>
private bool IsAnswerListValid()
{
bool returnValue = true;
//If option 5 filled, 3 and 4 must be
if (txtAnswer5.Text.Length > 0)
{
if (txtAnswer4.Text.Length == 0)
{
returnValue = false;
lblAnswer4Required.Visible = true;
}
if (txtAnswer3.Text.Length == 0)
{
returnValue = false;
lblAnswer3Required.Visible = true;
}
}
//if option 4 is filled, 3 must be as well
if (txtAnswer4.Text.Length > 0)
{
if (txtAnswer3.Text.Length == 0)
{
returnValue = false;
lblAnswer3Required.Visible = true;
}
}
//Return results
return returnValue;
}
}
}
| |
namespace Gu.State
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Gu.State.Internals;
/// <summary>Builder for creating <see cref="PropertiesSettings"/>.</summary>
public class PropertiesSettingsBuilder
{
private readonly HashSet<Type> ignoredTypes = new HashSet<Type>();
private readonly HashSet<Type> immutableTypes = new HashSet<Type>();
private readonly HashSet<PropertyInfo> ignoredProperties = new HashSet<PropertyInfo>(MemberInfoComparer<PropertyInfo>.Default);
private readonly Dictionary<Type, IEqualityComparer> comparers = new Dictionary<Type, IEqualityComparer>();
private readonly Dictionary<Type, CustomCopy> copyers = new Dictionary<Type, CustomCopy>();
/// <summary>
/// Create the settings object.
/// </summary>
/// <param name="referenceHandling">How references are handled.</param>
/// <param name="bindingFlags">What bindingflags to use.</param>
/// <returns>An instance of <see cref="PropertiesSettings"/>.</returns>
public PropertiesSettings CreateSettings(
ReferenceHandling referenceHandling = ReferenceHandling.Structural,
BindingFlags bindingFlags = Constants.DefaultPropertyBindingFlags)
{
if (this.ignoredProperties.Count == 0 &&
this.ignoredTypes is null &&
this.comparers.Count == 0 &&
this.copyers.Count == 0)
{
return PropertiesSettings.GetOrCreate(referenceHandling, bindingFlags);
}
return new PropertiesSettings(
this.ignoredProperties,
this.ignoredTypes,
this.immutableTypes,
this.comparers,
this.copyers,
referenceHandling,
bindingFlags);
}
/// <summary>Treat <typeparamref name="T"/> as immutable.</summary>
/// <typeparam name="T">The immutable type.</typeparam>
/// <returns>The builder instance for chaining.</returns>
public PropertiesSettingsBuilder AddImmutableType<T>()
{
return this.AddImmutableType(typeof(T));
}
/// <summary>Treat <paramref name="type"/> as immutable.</summary>
/// <param name="type">The immutable type.</param>
/// <returns>The builder instance for chaining.</returns>
public PropertiesSettingsBuilder AddImmutableType(Type type)
{
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
if (!this.immutableTypes.Add(type))
{
var message = $"Already added type: {type.FullName}\r\n" +
$"Nested Fields are not allowed";
throw new ArgumentException(message);
}
return this;
}
/// <summary>Ignore the type <typeparamref name="T"/> in the setting.</summary>
/// <typeparam name="T">The type to ignore.</typeparam>
/// <returns>The builder instance for chaining.</returns>
public PropertiesSettingsBuilder IgnoreType<T>()
{
return this.IgnoreType(typeof(T));
}
/// <summary>Ignore the type <paramref name="type"/> in the setting.</summary>
/// <param name="type">The type to ignore.</param>
/// <returns>The builder instance for chaining.</returns>
public PropertiesSettingsBuilder IgnoreType(Type type)
{
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
if (!this.ignoredTypes.Add(type))
{
var message = $"Already added type: {type.FullName}\r\n" +
$"Nested properties are not allowed";
throw new ArgumentException(message);
}
return this;
}
/// <summary>Ignore the property <paramref name="property"/> in the setting.</summary>
/// <param name="property">The property to ignore.</param>
/// <returns>The builder instance for chaining.</returns>
public PropertiesSettingsBuilder IgnoreProperty(PropertyInfo property)
{
if (property is null)
{
throw new ArgumentNullException(nameof(property));
}
if (!this.ignoredProperties.Add(property))
{
var message = $"Already added property: {property.DeclaringType?.FullName}.{property.Name}\r\n" +
$"Nested properties are not allowed";
throw new ArgumentException(message);
}
return this;
}
/// <summary>Ignore the property named <paramref name="name"/> for type <typeparamref name="TSource"/> in the setting.</summary>
/// <typeparam name="TSource">The type with the property to ignore.</typeparam>
/// <param name="name">The name of property to ignore.</param>
/// <returns>The builder instance for chaining.</returns>
public PropertiesSettingsBuilder IgnoreProperty<TSource>(string name)
{
if (name is null)
{
throw new ArgumentNullException(nameof(name));
}
var propertyInfo = typeof(TSource).GetProperty(name, Constants.DefaultFieldBindingFlags);
if (propertyInfo is null)
{
var message = $"{name} must be a property on {typeof(TSource).Name}\r\n" +
$"Nested properties are not allowed";
throw new ArgumentException(message);
}
return this.IgnoreProperty(propertyInfo);
}
/// <summary>
/// Sample: AddExplicitProperty{<typeparamref name="TSource"/>}(x => x.Bar).
/// </summary>
/// <typeparam name="TSource">The type of the parameter in the lambda.</typeparam>
/// <param name="property">Sample x => x.SomeProperty.</param>
/// <returns>Returns self for chaining.</returns>
public PropertiesSettingsBuilder IgnoreProperty<TSource>(Expression<Func<TSource, object>> property)
{
if (property is null)
{
throw new ArgumentNullException(nameof(property));
}
var memberExpression = property.Body as MemberExpression;
if (memberExpression is null)
{
if (property.Body.NodeType == ExpressionType.Convert)
{
memberExpression = (property.Body as UnaryExpression)?.Operand as MemberExpression;
}
}
if (memberExpression is null)
{
var message = $"{nameof(property)} must be a property expression like foo => foo.Bar\r\n" +
$"Nested properties are not allowed";
throw new ArgumentException(message);
}
if (memberExpression.Expression.NodeType != ExpressionType.Parameter)
{
var message = $"{nameof(property)} must be a property expression like foo => foo.Bar\r\n" +
$"Nested properties are not allowed";
throw new ArgumentException(message);
}
if (memberExpression.Member is PropertyInfo propertyInfo)
{
this.IgnoreProperty(propertyInfo);
return this;
}
else
{
var message = $"{nameof(property)} must be a property expression like foo => foo.Bar";
throw new ArgumentException(message);
}
}
/// <summary>Ignore indexers for type <typeparamref name="T"/> in the setting.</summary>
/// <typeparam name="T">The type with for which indexers are ignored.</typeparam>
/// <returns>The builder instance for chaining.</returns>
public PropertiesSettingsBuilder IgnoreIndexersFor<T>()
{
foreach (var indexer in typeof(T).GetProperties(Constants.DefaultFieldBindingFlags).Where(x => x.GetIndexParameters().Length > 0))
{
this.IgnoreProperty(indexer);
}
return this;
}
/// <summary>Add a custom comparer for type <typeparamref name="T"/> in the setting.</summary>
/// <typeparam name="T">The type.</typeparam>
/// <param name="comparer">The <see cref="IEqualityComparer{T}"/>.</param>
/// <returns>The builder instance for chaining.</returns>
public PropertiesSettingsBuilder AddComparer<T>(IEqualityComparer<T> comparer)
{
if (comparer is null)
{
throw new ArgumentNullException(nameof(comparer));
}
#pragma warning disable CA1508 // Avoid dead conditional code, broken analyzer
this.comparers[typeof(T)] = comparer as IEqualityComparer ?? CastingComparer.Create(comparer);
#pragma warning restore CA1508 // Avoid dead conditional code
return this;
}
/// <summary>Provide a custom copy implementation for <typeparamref name="T"/>.</summary>
/// <typeparam name="T">The type to copy.</typeparam>
/// <param name="copyMethod">
/// This method gets passed the source value, target value and returns the updated target value or a new target value.
/// </param>
/// <returns>Self.</returns>
public PropertiesSettingsBuilder AddCustomCopy<T>(Func<T, T, T> copyMethod)
{
if (copyMethod is null)
{
throw new ArgumentNullException(nameof(copyMethod));
}
this.copyers[typeof(T)] = CustomCopy.Create(copyMethod);
return this;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using NSubstitute;
using Xunit;
namespace Octokit.Tests.Clients
{
/// <summary>
/// Client tests mostly just need to make sure they call the IApiConnection with the correct
/// relative Uri. No need to fake up the response. All *those* tests are in ApiConnectionTests.cs.
/// </summary>
public class RepositoriesClientTests
{
public class TheConstructor
{
[Fact]
public void EnsuresNonNullArguments()
{
Assert.Throws<ArgumentNullException>(() => new RepositoriesClient(null));
}
}
public class TheCreateMethodForUser
{
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoriesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Create(null));
}
[Fact]
public void UsesTheUserReposUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
client.Create(new NewRepository("aName"));
connection.Received().Post<Repository>(Arg.Is<Uri>(u => u.ToString() == "user/repos"), Arg.Any<NewRepository>());
}
[Fact]
public void TheNewRepositoryDescription()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
var newRepository = new NewRepository("aName");
client.Create(newRepository);
connection.Received().Post<Repository>(Args.Uri, newRepository);
}
[Fact]
public async Task ThrowsRepositoryExistsExceptionWhenRepositoryExistsForCurrentUser()
{
var newRepository = new NewRepository("aName");
var response = Substitute.For<IResponse>();
response.StatusCode.Returns((HttpStatusCode)422);
response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":"
+ @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository"","
+ @"""code"":""custom"",""field"":""name"",""message"":""name already exists on this account""}]}");
var credentials = new Credentials("haacked", "pwd");
var connection = Substitute.For<IApiConnection>();
connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl);
connection.Connection.Credentials.Returns(credentials);
connection.Post<Repository>(Args.Uri, newRepository)
.Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); });
var client = new RepositoriesClient(connection);
var exception = await Assert.ThrowsAsync<RepositoryExistsException>(
() => client.Create(newRepository));
Assert.False(exception.OwnerIsOrganization);
Assert.Null(exception.Organization);
Assert.Equal("aName", exception.RepositoryName);
Assert.Null(exception.ExistingRepositoryWebUrl);
}
[Fact]
public async Task ThrowsExceptionWhenPrivateRepositoryQuotaExceeded()
{
var newRepository = new NewRepository("aName") { Private = true };
var response = Substitute.For<IResponse>();
response.StatusCode.Returns((HttpStatusCode)422);
response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":"
+ @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository"","
+ @"""code"":""custom"",""field"":""name"",""message"":"
+ @"""name can't be private. You are over your quota.""}]}");
var credentials = new Credentials("haacked", "pwd");
var connection = Substitute.For<IApiConnection>();
connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl);
connection.Connection.Credentials.Returns(credentials);
connection.Post<Repository>(Args.Uri, newRepository)
.Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); });
var client = new RepositoriesClient(connection);
var exception = await Assert.ThrowsAsync<PrivateRepositoryQuotaExceededException>(
() => client.Create(newRepository));
Assert.NotNull(exception);
}
}
public class TheCreateMethodForOrganization
{
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoriesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Create(null, new NewRepository("aName")));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Create("aLogin", null));
}
[Fact]
public async Task UsesTheOrganizationsReposUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
await client.Create("theLogin", new NewRepository("aName"));
connection.Received().Post<Repository>(
Arg.Is<Uri>(u => u.ToString() == "orgs/theLogin/repos"),
Args.NewRepository);
}
[Fact]
public async Task TheNewRepositoryDescription()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
var newRepository = new NewRepository("aName");
await client.Create("aLogin", newRepository);
connection.Received().Post<Repository>(Args.Uri, newRepository);
}
[Fact]
public async Task ThrowsRepositoryExistsExceptionWhenRepositoryExistsForSpecifiedOrg()
{
var newRepository = new NewRepository("aName");
var response = Substitute.For<IResponse>();
response.StatusCode.Returns((HttpStatusCode)422);
response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":"
+ @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository"","
+ @"""code"":""custom"",""field"":""name"",""message"":""name already exists on this account""}]}");
var connection = Substitute.For<IApiConnection>();
connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl);
connection.Post<Repository>(Args.Uri, newRepository)
.Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); });
var client = new RepositoriesClient(connection);
var exception = await Assert.ThrowsAsync<RepositoryExistsException>(
() => client.Create("illuminati", newRepository));
Assert.True(exception.OwnerIsOrganization);
Assert.Equal("illuminati", exception.Organization);
Assert.Equal("aName", exception.RepositoryName);
Assert.Equal(new Uri("https://github.com/illuminati/aName"), exception.ExistingRepositoryWebUrl);
Assert.Equal("There is already a repository named 'aName' in the organization 'illuminati'.",
exception.Message);
}
[Fact]
public async Task ThrowsValidationException()
{
var newRepository = new NewRepository("aName");
var response = Substitute.For<IResponse>();
response.StatusCode.Returns((HttpStatusCode)422);
response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":"
+ @"""http://developer.github.com/v3/repos/#create"",""errors"":[]}");
var connection = Substitute.For<IApiConnection>();
connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl);
connection.Post<Repository>(Args.Uri, newRepository)
.Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); });
var client = new RepositoriesClient(connection);
var exception = await Assert.ThrowsAsync<ApiValidationException>(
() => client.Create("illuminati", newRepository));
Assert.Null(exception as RepositoryExistsException);
}
[Fact]
public async Task ThrowsRepositoryExistsExceptionForEnterpriseInstance()
{
var newRepository = new NewRepository("aName");
var response = Substitute.For<IResponse>();
response.StatusCode.Returns((HttpStatusCode)422);
response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":"
+ @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository"","
+ @"""code"":""custom"",""field"":""name"",""message"":""name already exists on this account""}]}");
var connection = Substitute.For<IApiConnection>();
connection.Connection.BaseAddress.Returns(new Uri("https://example.com"));
connection.Post<Repository>(Args.Uri, newRepository)
.Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); });
var client = new RepositoriesClient(connection);
var exception = await Assert.ThrowsAsync<RepositoryExistsException>(
() => client.Create("illuminati", newRepository));
Assert.Equal("aName", exception.RepositoryName);
Assert.Equal(new Uri("https://example.com/illuminati/aName"), exception.ExistingRepositoryWebUrl);
}
}
public class TheDeleteMethod
{
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoriesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Delete(null, "aRepoName"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Delete("anOwner", null));
}
[Fact]
public async Task RequestsCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
await client.Delete("theOwner", "theRepoName");
connection.Received().Delete(Arg.Is<Uri>(u => u.ToString() == "repos/theOwner/theRepoName"));
}
}
public class TheGetMethod
{
[Fact]
public void RequestsCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
client.Get("fake", "repo");
connection.Received().Get<Repository>(Arg.Is<Uri>(u => u.ToString() == "repos/fake/repo"));
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoriesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get(null, "name"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", null));
}
}
public class TheGetAllPublicMethod
{
[Fact]
public void RequestsTheCorrectUrlAndReturnsRepositories()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
client.GetAllPublic();
connection.Received()
.GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "repositories"));
}
}
public class TheGetAllPublicSinceMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
client.GetAllPublic(new PublicRepositoryRequest(364));
connection.Received()
.GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "repositories?since=364"));
}
[Fact]
public void SendsTheCorrectParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
client.GetAllPublic(new PublicRepositoryRequest(364));
connection.Received()
.GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "repositories?since=364"));
}
}
public class TheGetAllForCurrentMethod
{
[Fact]
public void RequestsTheCorrectUrlAndReturnsRepositories()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
client.GetAllForCurrent();
connection.Received()
.GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "user/repos"));
}
[Fact]
public void CanFilterByType()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
var request = new RepositoryRequest
{
Type = RepositoryType.All
};
client.GetAllForCurrent(request);
connection.Received()
.GetAll<Repository>(
Arg.Is<Uri>(u => u.ToString() == "user/repos"),
Arg.Is<Dictionary<string, string>>(d => d["type"] == "all"));
}
[Fact]
public void CanFilterBySort()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
var request = new RepositoryRequest
{
Type = RepositoryType.Private,
Sort = RepositorySort.FullName
};
client.GetAllForCurrent(request);
connection.Received()
.GetAll<Repository>(
Arg.Is<Uri>(u => u.ToString() == "user/repos"),
Arg.Is<Dictionary<string, string>>(d =>
d["type"] == "private" && d["sort"] == "full_name"));
}
[Fact]
public void CanFilterBySortDirection()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
var request = new RepositoryRequest
{
Type = RepositoryType.Member,
Sort = RepositorySort.Updated,
Direction = SortDirection.Ascending
};
client.GetAllForCurrent(request);
connection.Received()
.GetAll<Repository>(
Arg.Is<Uri>(u => u.ToString() == "user/repos"),
Arg.Is<Dictionary<string, string>>(d =>
d["type"] == "member" && d["sort"] == "updated" && d["direction"] == "asc"));
}
[Fact]
public void CanFilterByVisibility()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
var request = new RepositoryRequest
{
Visibility = RepositoryVisibility.Private
};
client.GetAllForCurrent(request);
connection.Received()
.GetAll<Repository>(
Arg.Is<Uri>(u => u.ToString() == "user/repos"),
Arg.Is<Dictionary<string, string>>(d =>
d["visibility"] == "private"));
}
[Fact]
public void CanFilterByAffiliation()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
var request = new RepositoryRequest
{
Affiliation = RepositoryAffiliation.Owner,
Sort = RepositorySort.FullName
};
client.GetAllForCurrent(request);
connection.Received()
.GetAll<Repository>(
Arg.Is<Uri>(u => u.ToString() == "user/repos"),
Arg.Is<Dictionary<string, string>>(d =>
d["affiliation"] == "owner" && d["sort"] == "full_name"));
}
}
public class TheGetAllForUserMethod
{
[Fact]
public void RequestsTheCorrectUrlAndReturnsRepositories()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
client.GetAllForUser("username");
connection.Received()
.GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "users/username/repos"));
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var reposEndpoint = new RepositoriesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => reposEndpoint.GetAllForUser(null));
}
}
public class TheGetAllForOrgMethod
{
[Fact]
public void RequestsTheCorrectUrlAndReturnsRepositories()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
client.GetAllForOrg("orgname");
connection.Received()
.GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "orgs/orgname/repos"));
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var reposEndpoint = new RepositoriesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => reposEndpoint.GetAllForOrg(null));
}
}
public class TheGetAllBranchesMethod
{
[Fact]
public void ReturnsBranches()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
client.GetAllBranches("owner", "name");
connection.Received()
.GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/branches"), null, "application/vnd.github.loki-preview+json");
}
[Fact]
public async Task EnsuresArguments()
{
var client = new RepositoriesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllBranches(null, "repo"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllBranches("owner", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllBranches("", "repo"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllBranches("owner", ""));
}
}
public class TheGetAllContributorsMethod
{
[Fact]
public void GetsCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
client.GetAllContributors("owner", "name");
connection.Received()
.GetAll<RepositoryContributor>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/contributors"), Arg.Any<IDictionary<string, string>>());
}
[Fact]
public async Task EnsuresArguments()
{
var client = new RepositoriesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllContributors(null, "repo"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllContributors("owner", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllContributors("", "repo"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllContributors("owner", ""));
}
}
public class TheGetAllLanguagesMethod
{
[Fact]
public void GetsCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
client.GetAllLanguages("owner", "name");
connection.Received()
.Get<Dictionary<string, long>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/languages"));
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoriesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllLanguages(null, "repo"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllLanguages("owner", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllLanguages("", "repo"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllLanguages("owner", ""));
}
}
public class TheGetAllTeamsMethod
{
[Fact]
public void GetsCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
client.GetAllTeams("owner", "name");
connection.Received()
.GetAll<Team>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/teams"));
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoriesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTeams(null, "repo"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTeams("owner", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTeams("", "repo"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTeams("owner", ""));
}
}
public class TheGetAllTagsMethod
{
[Fact]
public void GetsCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
client.GetAllTags("owner", "name");
connection.Received()
.GetAll<RepositoryTag>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/tags"));
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoriesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTags(null, "repo"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTags("owner", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTags("", "repo"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTags("owner", ""));
}
}
public class TheGetBranchMethod
{
[Fact]
public void GetsCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
client.GetBranch("owner", "repo", "branch");
connection.Received()
.Get<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch"), null, "application/vnd.github.loki-preview+json");
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoriesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranch(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranch("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranch("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranch("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranch("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranch("owner", "repo", ""));
}
}
public class TheEditMethod
{
[Fact]
public void PatchesCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
var update = new RepositoryUpdate();
client.Edit("owner", "repo", update);
connection.Received()
.Patch<Repository>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo"), Arg.Any<RepositoryUpdate>());
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoriesClient(Substitute.For<IApiConnection>());
var update = new RepositoryUpdate();
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit(null, "repo", update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit("owner", null, update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.Edit("", "repo", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.Edit("owner", "", update));
}
}
public class TheCompareMethod
{
[Fact]
public async Task EnsureNonNullArguments()
{
var client = new RepositoryCommitsClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Compare(null, "repo", "base", "head"));
await Assert.ThrowsAsync<ArgumentException>(() => client.Compare("", "repo", "base", "head"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Compare("owner", null, "base", "head"));
await Assert.ThrowsAsync<ArgumentException>(() => client.Compare("owner", "", "base", "head"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Compare("owner", "repo", null, "head"));
await Assert.ThrowsAsync<ArgumentException>(() => client.Compare("owner", "repo", "", "head"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Compare("owner", "repo", "base", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.Compare("owner", "repo", "base", ""));
}
[Fact]
public void GetsCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryCommitsClient(connection);
client.Compare("owner", "repo", "base", "head");
connection.Received()
.Get<CompareResult>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/compare/base...head"));
}
[Fact]
public void EncodesUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryCommitsClient(connection);
client.Compare("owner", "repo", "base", "shiftkey/my-cool-branch");
connection.Received()
.Get<CompareResult>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/compare/base...shiftkey%2Fmy-cool-branch"));
}
}
public class TheGetCommitMethod
{
[Fact]
public async Task EnsureNonNullArguments()
{
var client = new RepositoryCommitsClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get(null, "repo", "reference"));
await Assert.ThrowsAsync<ArgumentException>(() => client.Get("", "repo", "reference"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", null, "reference"));
await Assert.ThrowsAsync<ArgumentException>(() => client.Get("owner", "", "reference"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.Get("owner", "repo", ""));
}
[Fact]
public void GetsCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryCommitsClient(connection);
client.Get("owner", "name", "reference");
connection.Received()
.Get<GitHubCommit>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/commits/reference"));
}
}
public class TheGetAllCommitsMethod
{
[Fact]
public async Task EnsureNonNullArguments()
{
var client = new RepositoryCommitsClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll(null, "repo"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("", "repo"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll("owner", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("owner", ""));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll("owner", "repo", null, ApiOptions.None));
}
[Fact]
public void GetsCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryCommitsClient(connection);
client.GetAll("owner", "name");
connection.Received()
.GetAll<GitHubCommit>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/commits"), Args.EmptyDictionary, Args.ApiOptions);
}
}
public class TheEditBranchMethod
{
[Fact]
public void GetsCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoriesClient(connection);
var update = new BranchUpdate();
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.EditBranch("owner", "repo", "branch", update);
connection.Received()
.Patch<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch"), Arg.Any<BranchUpdate>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoriesClient(Substitute.For<IApiConnection>());
var update = new BranchUpdate();
await Assert.ThrowsAsync<ArgumentNullException>(() => client.EditBranch(null, "repo", "branch", update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.EditBranch("owner", null, "branch", update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.EditBranch("owner", "repo", null, update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.EditBranch("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.EditBranch("", "repo", "branch", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.EditBranch("owner", "", "branch", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.EditBranch("owner", "repo", "", update));
}
}
public class TheGetSha1Method
{
[Fact]
public void EnsuresNonNullArguments()
{
var client = new RepositoryCommitsClient(Substitute.For<IApiConnection>());
Assert.ThrowsAsync<ArgumentException>(() => client.GetSha1("", "name", "reference"));
Assert.ThrowsAsync<ArgumentException>(() => client.GetSha1("owner", "", "reference"));
Assert.ThrowsAsync<ArgumentException>(() => client.GetSha1("owner", "name", ""));
}
[Fact]
public async Task EnsuresNonEmptyArguments()
{
var client = new RepositoryCommitsClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetSha1(null, "name", "reference"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetSha1("owner", null, "reference"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetSha1("owner", "name", null));
}
[Fact]
public void GetsCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryCommitsClient(connection);
client.GetSha1("owner", "name", "reference");
connection.Received()
.Get<string>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/commits/reference"), null, AcceptHeaders.CommitReferenceSha1Preview);
}
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// 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.Reflection;
using Gallio.Common.Collections;
using Gallio.Framework.Data;
using Gallio.Model;
using Gallio.Common.Reflection;
namespace Gallio.Framework.Pattern
{
/// <summary>
/// Declares that a type represents a test.
/// </summary>
/// <remarks>
/// <para>
/// Subclasses of this attribute can control what happens with the type.
/// </para>
/// <para>
/// At most one attribute of this type may appear on any given class.
/// </para>
/// <para>
/// A test type has no timeout by default.
/// </para>
/// </remarks>
/// <seealso cref="TestTypeDecoratorPatternAttribute"/>
[AttributeUsage(PatternAttributeTargets.TestType, AllowMultiple = false, Inherited = true)]
public class TestTypePatternAttribute : PatternAttribute
{
private static readonly Key<ObjectCreationSpec> FixtureObjectCreationSpecKey = new Key<ObjectCreationSpec>("FixtureObjectCreationSpec");
private const BindingFlags ConstructorBindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
private const BindingFlags NestedTypeBindingFlags = BindingFlags.Public | BindingFlags.NonPublic;
/// <summary>
/// Gets an instance of the test type pattern attribute to use when no
/// other pattern consumes the type.
/// </summary>
/// <remarks>
/// If the type can be inferred to be a test type then the pattern will behave as if the type has a
/// test type pattern attribute applied to it. Otherwise it will simply recurse into nested types.
/// </remarks>
/// <seealso cref="InferTestType"/>
public static readonly TestTypePatternAttribute AutomaticInstance = new AutomaticImpl();
/// <summary>
/// Gets or sets a number that defines an ordering for the test with respect to its siblings.
/// </summary>
/// <remarks>
/// <para>
/// Unless compelled otherwise by test dependencies, tests with a lower order number than
/// their siblings will run before those siblings and tests with the same order number
/// as their siblings with run in an arbitrary sequence with respect to those siblings.
/// </para>
/// </remarks>
/// <value>The test execution order with respect to siblings, initially zero.</value>
public int Order { get; set; }
/// <inheritdoc />
public override bool IsPrimary
{
get { return true; }
}
/// <inheritdoc />
public override IList<TestPart> GetTestParts(IPatternEvaluator evaluator, ICodeElementInfo codeElement)
{
return new[] { new TestPart() { IsTestContainer = true } };
}
/// <inheritdoc />
public override void Consume(IPatternScope containingScope, ICodeElementInfo codeElement, bool skipChildren)
{
//TODO: Review: Issue 762: Shouldn't the base method be invoked here?
//base.Consume(containingScope, codeElement, skipChildren);
var type = codeElement as ITypeInfo;
Validate(containingScope, type);
IPatternScope typeScope = containingScope.CreateChildTestScope(type.Name, type);
typeScope.TestBuilder.Kind = TestKinds.Fixture;
typeScope.TestBuilder.Order = Order;
InitializeTest(typeScope, type);
SetTestSemantics(typeScope.TestBuilder, type);
typeScope.TestBuilder.ApplyDeferredActions();
}
/// <summary>
/// Verifies that the attribute is being used correctly.
/// </summary>
/// <param name="containingScope">The containing scope.</param>
/// <param name="type">The type.</param>
/// <exception cref="PatternUsageErrorException">Thrown if the attribute is being used incorrectly.</exception>
protected virtual void Validate(IPatternScope containingScope, ITypeInfo type)
{
if (!containingScope.CanAddChildTest || type == null)
ThrowUsageErrorException("This attribute can only be used on a test type within a test assembly.");
if (!type.IsClass || type.ElementType != null)
ThrowUsageErrorException("This attribute can only be used on a class.");
}
/// <summary>
/// Initializes a test for a type after it has been added to the test model.
/// </summary>
/// <remarks>
/// <para>
/// The members of base types are processed before those of subtypes.
/// </para>
/// <para>
/// The default implementation processes all public members of the type including
/// the first constructor found, then recurses to process all public and non-public
/// nested types. Non-public members other than nested types are ignored.
/// </para>
/// </remarks>
/// <param name="typeScope">The type scope.</param>
/// <param name="type">The type.</param>
protected virtual void InitializeTest(IPatternScope typeScope, ITypeInfo type)
{
string xmlDocumentation = type.GetXmlDocumentation();
if (xmlDocumentation != null)
typeScope.TestBuilder.AddMetadata(MetadataKeys.XmlDocumentation, xmlDocumentation);
typeScope.Process(type);
if (type.IsGenericTypeDefinition)
{
foreach (IGenericParameterInfo parameter in type.GenericArguments)
typeScope.Consume(parameter, false, DefaultGenericParameterPattern);
}
ConsumeMembers(typeScope, type);
ConsumeConstructors(typeScope, type);
ConsumeNestedTypes(typeScope, type);
}
/// <summary>
/// Consumes type members including fields, properties, methods and events.
/// </summary>
/// <param name="typeScope">The scope to be used as the containing scope.</param>
/// <param name="type">The type whose members are to be consumed.</param>
protected void ConsumeMembers(IPatternScope typeScope, ITypeInfo type)
{
BindingFlags bindingFlags = GetMemberBindingFlags(type);
// TODO: We should probably process groups of members in sorted order working outwards
// from the base type, like an onion.
foreach (IFieldInfo field in CodeElementSorter.SortMembersByDeclaringType(type.GetFields(bindingFlags)))
typeScope.Consume(field, false, DefaultFieldPattern);
foreach (IPropertyInfo property in CodeElementSorter.SortMembersByDeclaringType(type.GetProperties(bindingFlags)))
typeScope.Consume(property, false, DefaultPropertyPattern);
foreach (IMethodInfo method in CodeElementSorter.SortMembersByDeclaringType(type.GetMethods(bindingFlags)))
typeScope.Consume(method, false, DefaultMethodPattern);
foreach (IEventInfo @event in CodeElementSorter.SortMembersByDeclaringType(type.GetEvents(bindingFlags)))
typeScope.Consume(@event, false, DefaultEventPattern);
}
/// <summary>
/// Consumes type constructors.
/// </summary>
/// <param name="typeScope">The scope to be used as the containing scope.</param>
/// <param name="type">The type whose constructors are to be consumed.</param>
protected void ConsumeConstructors(IPatternScope typeScope, ITypeInfo type)
{
if (ShouldConsumeConstructors(type))
{
// FIXME: Currently we arbitrarily choose the first constructor and throw away the rest.
// This should be replaced by a more intelligent mechanism that supports a constructor
// selection policy based on some criterion.
IConstructorInfo constructor = GetFirstConstructorWithPreferenceForPublicConsructor(type);
if (constructor != null)
typeScope.Consume(constructor, false, DefaultConstructorPattern);
}
}
private static IConstructorInfo GetFirstConstructorWithPreferenceForPublicConsructor(ITypeInfo type)
{
IConstructorInfo result = null;
foreach (IConstructorInfo constructor in type.GetConstructors(ConstructorBindingFlags))
{
if (constructor.IsPublic)
return constructor;
if (result == null)
result = constructor;
}
return result;
}
private static bool ShouldConsumeConstructors(ITypeInfo type)
{
return !type.IsAbstract && !type.IsInterface;
}
/// <summary>
/// Consumes nested types.
/// </summary>
/// <param name="typeScope">The scope to be used as the containing scope.</param>
/// <param name="type">The type whose nested types are to be consumed.</param>
protected void ConsumeNestedTypes(IPatternScope typeScope, ITypeInfo type)
{
foreach (ITypeInfo nestedType in type.GetNestedTypes(NestedTypeBindingFlags))
typeScope.Consume(nestedType, false, DefaultNestedTypePattern);
}
/// <summary>
/// Applies semantic actions to a test to estalish its runtime behavior.
/// </summary>
/// <remarks>
/// <para>
/// This method is called after <see cref="InitializeTest" />.
/// </para>
/// <para>
/// The default behavior for a <see cref="TestTypePatternAttribute" />
/// is to configure the test actions as follows:
/// <list type="bullet">
/// <item><see cref="PatternTestInstanceActions.BeforeTestInstanceChain" />: Set the
/// fixture instance name and <see cref="PatternTestInstanceState.FixtureType" />.</item>
/// <item><see cref="PatternTestInstanceActions.InitializeTestInstanceChain" />: Create
/// the fixture instance and set the <see cref="PatternTestInstanceState.FixtureInstance" />
/// property accordingly.</item>
/// <item><see cref="PatternTestInstanceActions.DisposeTestInstanceChain" />: If the fixture type
/// implements <see cref="IDisposable" />, disposes the fixture instance.</item>
/// <item><see cref="PatternTestInstanceActions.DecorateChildTestChain" />: Decorates the child's
/// <see cref="PatternTestInstanceActions.BeforeTestInstanceChain" /> to set its <see cref="PatternTestInstanceState.FixtureInstance" />
/// and <see cref="PatternTestInstanceState.FixtureType" /> properties to those
/// of the fixture. The child test may override these values later on but this
/// is a reasonable default setting for test methods within a fixture.</item>
/// </list>
/// </para>
/// <para>
/// You can override this method to change the semantics as required.
/// </para>
/// </remarks>
/// <param name="testBuilder">The test builder.</param>
/// <param name="type">The test type.</param>
protected virtual void SetTestSemantics(ITestBuilder testBuilder, ITypeInfo type)
{
testBuilder.TestInstanceActions.BeforeTestInstanceChain.After(
delegate(PatternTestInstanceState testInstanceState)
{
ObjectCreationSpec spec = testInstanceState.GetFixtureObjectCreationSpec(type);
testInstanceState.Data.SetValue(FixtureObjectCreationSpecKey, spec);
testInstanceState.FixtureType = spec.ResolvedType;
if (!testInstanceState.IsReusingPrimaryTestStep)
testInstanceState.NameBase = spec.Format(testInstanceState.NameBase, testInstanceState.Formatter);
});
testBuilder.TestInstanceActions.InitializeTestInstanceChain.After(
delegate(PatternTestInstanceState testInstanceState)
{
if (!type.IsAbstract && !type.IsInterface)
{
ObjectCreationSpec spec = testInstanceState.Data.GetValue(FixtureObjectCreationSpecKey);
testInstanceState.FixtureInstance = spec.CreateInstance();
}
});
testBuilder.TestInstanceActions.DisposeTestInstanceChain.After(
delegate(PatternTestInstanceState testInstanceState)
{
IDisposable dispose = testInstanceState.FixtureInstance as IDisposable;
if (dispose != null)
{
dispose.Dispose();
}
});
testBuilder.TestInstanceActions.DecorateChildTestChain.After(
delegate(PatternTestInstanceState testInstanceState, PatternTestActions decoratedTestActions)
{
decoratedTestActions.TestInstanceActions.BeforeTestInstanceChain.Before(delegate(PatternTestInstanceState childTestInstanceState)
{
IMemberInfo member = childTestInstanceState.Test.CodeElement as IMemberInfo;
if (member != null)
{
ITypeInfo memberDeclaringType = member.DeclaringType;
if (memberDeclaringType != null)
{
if (type.Equals(memberDeclaringType) || type.IsSubclassOf(memberDeclaringType))
{
childTestInstanceState.FixtureType = testInstanceState.FixtureType;
childTestInstanceState.FixtureInstance = testInstanceState.FixtureInstance;
}
}
}
});
});
}
/// <summary>
/// Gets the default pattern to apply to generic parameters that do not have a primary pattern, or null if none.
/// </summary>
/// <remarks>
/// <para>
/// The default implementation returns <see cref="TestParameterPatternAttribute.DefaultInstance" />.
/// </para>
/// </remarks>
protected virtual IPattern DefaultGenericParameterPattern
{
get { return TestParameterPatternAttribute.DefaultInstance; }
}
/// <summary>
/// Gets the default pattern to apply to methods that do not have a primary pattern, or null if none.
/// </summary>
/// <remarks>
/// <para>
/// The default implementation returns <c>null</c>.
/// </para>
/// </remarks>
protected virtual IPattern DefaultMethodPattern
{
get { return null; }
}
/// <summary>
/// Gets the default pattern to apply to events that do not have a primary pattern, or null if none.
/// </summary>
/// <remarks>
/// <para>
/// The default implementation returns <c>null</c>.
/// </para>
/// </remarks>
protected virtual IPattern DefaultEventPattern
{
get { return null; }
}
/// <summary>
/// Gets the default pattern to apply to fields that do not have a primary pattern, or null if none.
/// </summary>
/// <remarks>
/// <para>
/// The default implementation returns <see cref="TestParameterPatternAttribute.AutomaticInstance" />.
/// </para>
/// </remarks>
protected virtual IPattern DefaultFieldPattern
{
get { return TestParameterPatternAttribute.AutomaticInstance; }
}
/// <summary>
/// Gets the default pattern to apply to properties that do not have a primary pattern, or null if none.
/// </summary>
/// <remarks>
/// <para>
/// The default implementation returns <see cref="TestParameterPatternAttribute.AutomaticInstance" />.
/// </para>
/// </remarks>
protected virtual IPattern DefaultPropertyPattern
{
get { return TestParameterPatternAttribute.AutomaticInstance; }
}
/// <summary>
/// Gets the default pattern to apply to constructors that do not have a primary pattern, or null if none.
/// </summary>
/// <remarks>
/// <para>
/// The default implementation returns <see cref="TestConstructorPatternAttribute.DefaultInstance" />.
/// </para>
/// </remarks>
protected virtual IPattern DefaultConstructorPattern
{
get { return TestConstructorPatternAttribute.DefaultInstance; }
}
/// <summary>
/// Gets the default pattern to apply to nested types that do not have a primary pattern, or null if none.
/// </summary>
/// <remarks>
/// <para>
/// The default implementation returns <see cref="TestTypePatternAttribute.AutomaticInstance"/>.
/// </para>
/// </remarks>
protected virtual IPattern DefaultNestedTypePattern
{
get { return AutomaticInstance; }
}
/// <summary>
/// Gets the binding flags that should be used to enumerate non-nested type members
/// of the type for determining their contribution to the test fixture.
/// </summary>
/// <remarks>
/// <para>
/// Instance members are only included if the type is not abstract.
/// </para>
/// </remarks>
/// <param name="type">The type.</param>
/// <returns>The binding flags for enumerating members.</returns>
protected virtual BindingFlags GetMemberBindingFlags(ITypeInfo type)
{
BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
if (!type.IsAbstract)
bindingFlags |= BindingFlags.Instance;
return bindingFlags;
}
/// <summary>
/// Infers whether the type is a test type based on its structure.
/// </summary>
/// <remarks>
/// <para>
/// Returns true if the type any associated patterns, if it has
/// non-nested type members (subject to <see cref="GetMemberBindingFlags" />)
/// with patterns, if it has generic parameters with patterns, or if any
/// of its nested types satisfy the preceding rules.
/// </para>
/// </remarks>
/// <param name="evaluator">The pattern evaluator.</param>
/// <param name="type">The type.</param>
/// <returns>True if the type is likely a test type.</returns>
protected virtual bool InferTestType(IPatternEvaluator evaluator, ITypeInfo type)
{
if (evaluator.HasPatterns(type))
return true;
BindingFlags bindingFlags = GetMemberBindingFlags(type);
if (HasCodeElementWithPattern(evaluator, type.GetMethods(bindingFlags))
|| HasCodeElementWithPattern(evaluator, type.GetProperties(bindingFlags))
|| HasCodeElementWithPattern(evaluator, type.GetFields(bindingFlags))
|| HasCodeElementWithPattern(evaluator, type.GetEvents(bindingFlags)))
return true;
if (type.IsGenericTypeDefinition && HasCodeElementWithPattern(evaluator, type.GenericArguments))
return true;
if (ShouldConsumeConstructors(type)
&& HasCodeElementWithPattern(evaluator, type.GetConstructors(ConstructorBindingFlags)))
return true;
foreach (ITypeInfo nestedType in type.GetNestedTypes(NestedTypeBindingFlags))
if (InferTestType(evaluator, nestedType))
return true;
return false;
}
private static bool HasCodeElementWithPattern<T>(IPatternEvaluator evaluator, IEnumerable<T> elements)
where T : ICodeElementInfo
{
foreach (T element in elements)
if (evaluator.HasPatterns(element))
return true;
return false;
}
private sealed class AutomaticImpl : TestTypePatternAttribute
{
public override IList<TestPart> GetTestParts(IPatternEvaluator evaluator, ICodeElementInfo codeElement)
{
if (IsTest(evaluator, codeElement))
return base.GetTestParts(evaluator, codeElement);
return EmptyArray<TestPart>.Instance;
}
public override void Consume(IPatternScope containingScope, ICodeElementInfo codeElement, bool skipChildren)
{
//TODO: Review: Issue 762: Shouldn't the base method be invoked here?
//base.Consume(containingScope, codeElement, skipChildren);
if (IsTest(containingScope.Evaluator, codeElement))
base.Consume(containingScope, codeElement, skipChildren);
}
private bool IsTest(IPatternEvaluator evaluator, ICodeElementInfo codeElement)
{
ITypeInfo type = codeElement as ITypeInfo;
return type != null && InferTestType(evaluator, type);
}
}
}
}
| |
// 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.Globalization;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Tests
{
public static class SortedListTests
{
[Fact]
public static void Ctor_Empty()
{
var sortList = new SortedList();
Assert.Equal(0, sortList.Count);
Assert.Equal(0, sortList.Capacity);
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void Ctor_Int(int initialCapacity)
{
var sortList = new SortedList(initialCapacity);
Assert.Equal(0, sortList.Count);
Assert.Equal(initialCapacity, sortList.Capacity);
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Fact]
public static void Ctor_Int_NegativeInitialCapacity_ThrowsArgumentOutOfRangeException()
{
Assert.Throws<ArgumentOutOfRangeException>("initialCapacity", () => new SortedList(-1)); // InitialCapacity < 0
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void Ctor_IComparer_Int(int initialCapacity)
{
var sortList = new SortedList(new CustomComparer(), initialCapacity);
Assert.Equal(0, sortList.Count);
Assert.Equal(initialCapacity, sortList.Capacity);
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Fact]
public static void Ctor_IComparer_Int_NegativeInitialCapacity_ThrowsArgumentOutOfRangeException()
{
Assert.Throws<ArgumentOutOfRangeException>("value", () => new SortedList(new CustomComparer(), -1)); // InitialCapacity < 0
}
[Fact]
public static void Ctor_IComparer()
{
var sortList = new SortedList(new CustomComparer());
Assert.Equal(0, sortList.Count);
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Fact]
public static void Ctor_IComparer_Null()
{
var sortList = new SortedList((IComparer)null);
Assert.Equal(0, sortList.Count);
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Theory]
[InlineData(0, true)]
[InlineData(1, true)]
[InlineData(10, true)]
[InlineData(100, true)]
[InlineData(0, false)]
[InlineData(1, false)]
[InlineData(10, false)]
[InlineData(100, false)]
public static void Ctor_IDictionary(int count, bool sorted)
{
var hashtable = new Hashtable();
if (sorted)
{
// Create a hashtable in the correctly sorted order
for (int i = 0; i < count; i++)
{
hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2"));
}
}
else
{
// Create a hashtable in the wrong order and make sure it is sorted
for (int i = count - 1; i >= 0; i--)
{
hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2"));
}
}
var sortList = new SortedList(hashtable);
Assert.Equal(count, sortList.Count);
Assert.True(sortList.Capacity >= sortList.Count);
for (int i = 0; i < count; i++)
{
string key = "Key_" + i.ToString("D2");
string value = "Value_" + i.ToString("D2");
Assert.Equal(sortList.GetByIndex(i), value);
Assert.Equal(hashtable[key], sortList[key]);
}
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Fact]
public static void Ctor_IDictionary_NullDictionary_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("d", () => new SortedList((IDictionary)null)); // Dictionary is null
}
[Theory]
[InlineData(0, true)]
[InlineData(1, true)]
[InlineData(10, true)]
[InlineData(100, true)]
[InlineData(0, false)]
[InlineData(1, false)]
[InlineData(10, false)]
[InlineData(100, false)]
public static void Ctor_IDictionary_IComparer(int count, bool sorted)
{
var hashtable = new Hashtable();
if (sorted)
{
// Create a hashtable in the correctly sorted order
for (int i = count - 1; i >= 0; i--)
{
hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2"));
}
}
else
{
// Create a hashtable in the wrong order and make sure it is sorted
for (int i = 0; i < count; i++)
{
hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2"));
}
}
var sortList = new SortedList(hashtable, new CustomComparer());
Assert.Equal(count, sortList.Count);
Assert.True(sortList.Capacity >= sortList.Count);
for (int i = 0; i < count; i++)
{
string key = "Key_" + i.ToString("D2");
string value = "Value_" + i.ToString("D2");
string expectedValue = "Value_" + (count - i - 1).ToString("D2");
Assert.Equal(sortList.GetByIndex(i), expectedValue);
Assert.Equal(hashtable[key], sortList[key]);
}
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Fact]
public static void Ctor_IDictionary_IComparer_Null()
{
var sortList = new SortedList(new Hashtable(), null);
Assert.Equal(0, sortList.Count);
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
[Fact]
public static void Ctor_IDictionary_IComparer_NullDictionary_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("d", () => new SortedList(null, new CustomComparer())); // Dictionary is null
}
[Fact]
public static void DebuggerAttribute_Empty()
{
Assert.Equal("Count = 0", DebuggerAttributes.ValidateDebuggerDisplayReferences(new SortedList()));
}
[Fact]
public static void DebuggerAttribute_NormalList()
{
var list = new SortedList() { { "a", 1 }, { "b", 2 } };
DebuggerAttributeInfo debuggerAttribute = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(list);
PropertyInfo infoProperty = debuggerAttribute.Properties.Single(property => property.Name == "Items");
object[] items = (object[])infoProperty.GetValue(debuggerAttribute.Instance);
Assert.Equal(list.Count, items.Length);
}
[Fact]
public static void DebuggerAttribute_SynchronizedList()
{
var list = SortedList.Synchronized(new SortedList() { { "a", 1 }, { "b", 2 } });
DebuggerAttributeInfo debuggerAttribute = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(SortedList), list);
PropertyInfo infoProperty = debuggerAttribute.Properties.Single(property => property.Name == "Items");
object[] items = (object[])infoProperty.GetValue(debuggerAttribute.Instance);
Assert.Equal(list.Count, items.Length);
}
[Fact]
public static void DebuggerAttribute_NullSortedList_ThrowsArgumentNullException()
{
bool threwNull = false;
try
{
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(SortedList), null);
}
catch (TargetInvocationException ex)
{
threwNull = ex.InnerException is ArgumentNullException;
}
Assert.True(threwNull);
}
[Fact]
public static void EnsureCapacity_NewCapacityLessThanMin_CapsToMaxArrayLength()
{
// A situation like this occurs for very large lengths of SortedList.
// To avoid allocating several GBs of memory and making this test run for a very
// long time, we can use reflection to invoke SortedList's growth method manually.
// This is relatively brittle, as it relies on accessing a private method via reflection
// that isn't guaranteed to be stable.
const int InitialCapacity = 10;
const int MinCapacity = InitialCapacity * 2 + 1;
var sortedList = new SortedList(InitialCapacity);
MethodInfo ensureCapacity = sortedList.GetType().GetMethod("EnsureCapacity", BindingFlags.NonPublic | BindingFlags.Instance);
ensureCapacity.Invoke(sortedList, new object[] { MinCapacity });
Assert.Equal(MinCapacity, sortedList.Capacity);
}
[Fact]
public static void Add()
{
var sortList1 = new SortedList();
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < 100; i++)
{
string key = "Key_" + i.ToString("D2");
string value = "Value_" + i;
sortList2.Add(key, value);
Assert.True(sortList2.ContainsKey(key));
Assert.True(sortList2.ContainsValue(value));
Assert.Equal(i, sortList2.IndexOfKey(key));
Assert.Equal(i, sortList2.IndexOfValue(value));
Assert.Equal(i + 1, sortList2.Count);
}
});
}
[Fact]
public static void Add_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.Throws<ArgumentNullException>("key", () => sortList2.Add(null, 101)); // Key is null
Assert.Throws<ArgumentException>(null, () => sortList2.Add(1, 101)); // Key already exists
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void Clear(int count)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
sortList2.Clear();
Assert.Equal(0, sortList2.Count);
sortList2.Clear();
Assert.Equal(0, sortList2.Count);
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void Clone(int count)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
SortedList sortListClone = (SortedList)sortList2.Clone();
Assert.Equal(sortList2.Count, sortListClone.Count);
Assert.False(sortListClone.IsSynchronized); // IsSynchronized is not copied
Assert.Equal(sortList2.IsFixedSize, sortListClone.IsFixedSize);
Assert.Equal(sortList2.IsReadOnly, sortListClone.IsReadOnly);
for (int i = 0; i < sortListClone.Count; i++)
{
Assert.Equal(sortList2[i], sortListClone[i]);
}
});
}
[Fact]
public static void Clone_IsShallowCopy()
{
var sortList = new SortedList();
for (int i = 0; i < 10; i++)
{
sortList.Add(i, new Foo());
}
SortedList sortListClone = (SortedList)sortList.Clone();
string stringValue = "Hello World";
for (int i = 0; i < 10; i++)
{
Assert.Equal(stringValue, ((Foo)sortListClone[i]).StringValue);
}
// Now we remove an object from the original list, but this should still be present in the clone
sortList.RemoveAt(9);
Assert.Equal(stringValue, ((Foo)sortListClone[9]).StringValue);
stringValue = "Good Bye";
((Foo)sortList[0]).StringValue = stringValue;
Assert.Equal(stringValue, ((Foo)sortList[0]).StringValue);
Assert.Equal(stringValue, ((Foo)sortListClone[0]).StringValue);
// If we change the object, of course, the previous should not happen
sortListClone[0] = new Foo();
Assert.Equal(stringValue, ((Foo)sortList[0]).StringValue);
stringValue = "Hello World";
Assert.Equal(stringValue, ((Foo)sortListClone[0]).StringValue);
}
[Fact]
public static void ContainsKey()
{
var sortList1 = new SortedList();
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < 100; i++)
{
string key = "Key_" + i;
sortList2.Add(key, i);
Assert.True(sortList2.Contains(key));
Assert.True(sortList2.ContainsKey(key));
}
Assert.False(sortList2.ContainsKey("Non_Existent_Key"));
for (int i = 0; i < sortList2.Count; i++)
{
string removedKey = "Key_" + i;
sortList2.Remove(removedKey);
Assert.False(sortList2.Contains(removedKey));
Assert.False(sortList2.ContainsKey(removedKey));
}
});
}
[Fact]
public static void ContainsKey_NullKey_ThrowsArgumentNullException()
{
var sortList1 = new SortedList();
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.Throws<ArgumentNullException>("key", () => sortList2.Contains(null)); // Key is null
Assert.Throws<ArgumentNullException>("key", () => sortList2.ContainsKey(null)); // Key is null
});
}
[Fact]
public static void ContainsValue()
{
var sortList1 = new SortedList();
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < 100; i++)
{
sortList2.Add(i, "Value_" + i);
Assert.True(sortList2.ContainsValue("Value_" + i));
}
Assert.False(sortList2.ContainsValue("Non_Existent_Value"));
for (int i = 0; i < sortList2.Count; i++)
{
sortList2.Remove(i);
Assert.False(sortList2.ContainsValue("Value_" + i));
}
});
}
[Theory]
[InlineData(0, 0)]
[InlineData(1, 0)]
[InlineData(10, 0)]
[InlineData(100, 0)]
[InlineData(0, 50)]
[InlineData(1, 50)]
[InlineData(10, 50)]
[InlineData(100, 50)]
public static void CopyTo(int count, int index)
{
SortedList sortList1 = Helpers.CreateStringSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
var array = new object[index + count];
sortList2.CopyTo(array, index);
Assert.Equal(index + count, array.Length);
for (int i = index; i < index + count; i++)
{
int actualIndex = i - index;
string key = "Key_" + actualIndex.ToString("D2");
string value = "Value_" + actualIndex;
DictionaryEntry entry = (DictionaryEntry)array[i];
Assert.Equal(key, entry.Key);
Assert.Equal(value, entry.Value);
}
});
}
[Fact]
public static void CopyTo_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.Throws<ArgumentNullException>("array", () => sortList2.CopyTo(null, 0)); // Array is null
Assert.Throws<ArgumentException>(() => sortList2.CopyTo(new object[10, 10], 0)); // Array is multidimensional
Assert.Throws<ArgumentOutOfRangeException>("arrayIndex", () => sortList2.CopyTo(new object[100], -1)); // Index < 0
Assert.Throws<ArgumentException>(null, () => sortList2.CopyTo(new object[150], 51)); // Index + list.Count > array.Count
});
}
[Fact]
public static void GetByIndex()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < sortList2.Count; i++)
{
Assert.Equal(i, sortList2.GetByIndex(i));
int i2 = sortList2.IndexOfKey(i);
Assert.Equal(i, i2);
i2 = sortList2.IndexOfValue(i);
Assert.Equal(i, i2);
}
});
}
[Fact]
public static void GetByIndex_InvalidIndex_ThrowsArgumentOutOfRangeException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.Throws<ArgumentOutOfRangeException>("index", () => sortList2.GetByIndex(-1)); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => sortList2.GetByIndex(sortList2.Count)); // Index >= list.Count
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void GetEnumerator_IDictionaryEnumerator(int count)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.NotSame(sortList2.GetEnumerator(), sortList2.GetEnumerator());
IDictionaryEnumerator enumerator = sortList2.GetEnumerator();
for (int i = 0; i < 2; i++)
{
int counter = 0;
while (enumerator.MoveNext())
{
Assert.Equal(enumerator.Current, enumerator.Entry);
Assert.Equal(enumerator.Entry.Key, enumerator.Key);
Assert.Equal(enumerator.Entry.Value, enumerator.Value);
Assert.Equal(sortList2.GetKey(counter), enumerator.Entry.Key);
Assert.Equal(sortList2.GetByIndex(counter), enumerator.Entry.Value);
counter++;
}
Assert.Equal(count, counter);
enumerator.Reset();
}
});
}
[Fact]
public static void GetEnumerator_IDictionaryEnumerator_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
// If the underlying collection is modified, MoveNext, Reset, Entry, Key and Value throw, but Current etc. doesn't
IDictionaryEnumerator enumerator = sortList2.GetEnumerator();
enumerator.MoveNext();
sortList2.Add(101, 101);
Assert.NotNull(enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Reset());
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
// Current etc. throw if index < 0
enumerator = sortList2.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
// Current etc. throw after resetting
enumerator = sortList2.GetEnumerator();
enumerator.MoveNext();
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
// Current etc. throw if the current index is >= count
enumerator = sortList2.GetEnumerator();
while (enumerator.MoveNext()) ;
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void GetEnumerator_IEnumerator(int count)
{
SortedList sortList = Helpers.CreateIntSortedList(count);
Assert.NotSame(sortList.GetEnumerator(), sortList.GetEnumerator());
IEnumerator enumerator = sortList.GetEnumerator();
for (int i = 0; i < 2; i++)
{
int counter = 0;
while (enumerator.MoveNext())
{
DictionaryEntry dictEntry = (DictionaryEntry)enumerator.Current;
Assert.Equal(sortList.GetKey(counter), dictEntry.Key);
Assert.Equal(sortList.GetByIndex(counter), dictEntry.Value);
counter++;
}
Assert.Equal(count, counter);
enumerator.Reset();
}
}
[Fact]
public static void GetEnumerator_StartOfEnumeration_Clone()
{
SortedList sortedList = Helpers.CreateIntSortedList(10);
IDictionaryEnumerator enumerator = sortedList.GetEnumerator();
ICloneable cloneableEnumerator = (ICloneable)enumerator;
IDictionaryEnumerator clonedEnumerator = (IDictionaryEnumerator)cloneableEnumerator.Clone();
Assert.NotSame(enumerator, clonedEnumerator);
// Cloned and original enumerators should enumerate separately.
Assert.True(enumerator.MoveNext());
Assert.Equal(sortedList[0], enumerator.Value);
Assert.Throws<InvalidOperationException>(() => clonedEnumerator.Value);
Assert.True(clonedEnumerator.MoveNext());
Assert.Equal(sortedList[0], enumerator.Value);
Assert.Equal(sortedList[0], clonedEnumerator.Value);
// Cloned and original enumerators should enumerate in the same sequence.
for (int i = 1; i < sortedList.Count; i++)
{
Assert.True(enumerator.MoveNext());
Assert.NotEqual(enumerator.Current, clonedEnumerator.Current);
Assert.True(clonedEnumerator.MoveNext());
Assert.Equal(enumerator.Current, clonedEnumerator.Current);
}
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Equal(sortedList[sortedList.Count - 1], clonedEnumerator.Value);
Assert.False(clonedEnumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Throws<InvalidOperationException>(() => clonedEnumerator.Value);
}
[Fact]
public static void GetEnumerator_InMiddleOfEnumeration_Clone()
{
SortedList sortedList = Helpers.CreateIntSortedList(10);
IEnumerator enumerator = sortedList.GetEnumerator();
enumerator.MoveNext();
ICloneable cloneableEnumerator = (ICloneable)enumerator;
// Cloned and original enumerators should start at the same spot, even
// if the original is in the middle of enumeration.
IEnumerator clonedEnumerator = (IEnumerator)cloneableEnumerator.Clone();
Assert.Equal(enumerator.Current, clonedEnumerator.Current);
for (int i = 0; i < sortedList.Count - 1; i++)
{
Assert.True(clonedEnumerator.MoveNext());
}
Assert.False(clonedEnumerator.MoveNext());
}
[Fact]
public static void GetEnumerator_IEnumerator_Invalid()
{
SortedList sortList = Helpers.CreateIntSortedList(100);
// If the underlying collection is modified, MoveNext, Reset, Entry, Key and Value throw, but Current doesn't
IEnumerator enumerator = ((IEnumerable)sortList).GetEnumerator();
enumerator.MoveNext();
sortList.Add(101, 101);
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Reset());
// Current throws if index < 0
enumerator = sortList.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Current throw after resetting
enumerator = sortList.GetEnumerator();
enumerator.MoveNext();
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Current throw if the current index is >= count
enumerator = sortList.GetEnumerator();
while (enumerator.MoveNext()) ;
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void GetKeyList(int count)
{
SortedList sortList1 = Helpers.CreateStringSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys1 = sortList2.GetKeyList();
IList keys2 = sortList2.GetKeyList();
// Test we have copied the correct keys
Assert.Equal(count, keys1.Count);
Assert.Equal(count, keys2.Count);
for (int i = 0; i < keys1.Count; i++)
{
string key = "Key_" + i.ToString("D2");
Assert.Equal(key, keys1[i]);
Assert.Equal(key, keys2[i]);
Assert.True(sortList2.ContainsKey(keys1[i]));
}
});
}
[Fact]
public static void GetKeyList_IsSameAsKeysProperty()
{
var sortList = Helpers.CreateIntSortedList(10);
Assert.Same(sortList.GetKeyList(), sortList.Keys);
}
[Fact]
public static void GetKeyList_IListProperties()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
Assert.True(keys.IsReadOnly);
Assert.True(keys.IsFixedSize);
Assert.False(keys.IsSynchronized);
Assert.Equal(sortList2.SyncRoot, keys.SyncRoot);
});
}
[Fact]
public static void GetKeyList_Contains()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
for (int i = 0; i < keys.Count; i++)
{
string key = "Key_" + i.ToString("D2");
Assert.True(keys.Contains(key));
}
Assert.False(keys.Contains("Key_101")); // No such key
});
}
[Fact]
public static void GetKeyList_Contains_InvalidValueType_ThrowsInvalidOperationException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
Assert.Throws<InvalidOperationException>(() => keys.Contains("hello")); // Value is a different object type
});
}
[Fact]
public static void GetKeyList_IndexOf()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
for (int i = 0; i < keys.Count; i++)
{
string key = "Key_" + i.ToString("D2");
Assert.Equal(i, keys.IndexOf(key));
}
Assert.Equal(-1, keys.IndexOf("Key_101"));
});
}
[Fact]
public static void GetKeyList_IndexOf_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
Assert.Throws<ArgumentNullException>("key", () => keys.IndexOf(null)); // Value is null
Assert.Throws<InvalidOperationException>(() => keys.IndexOf("hello")); // Value is a different object type
});
}
[Theory]
[InlineData(0, 0)]
[InlineData(1, 0)]
[InlineData(10, 0)]
[InlineData(100, 0)]
[InlineData(0, 50)]
[InlineData(1, 50)]
[InlineData(10, 50)]
[InlineData(100, 50)]
public static void GetKeyList_CopyTo(int count, int index)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
object[] array = new object[index + count];
IList keys = sortList2.GetKeyList();
keys.CopyTo(array, index);
Assert.Equal(index + count, array.Length);
for (int i = index; i < index + count; i++)
{
Assert.Equal(keys[i - index], array[i]);
}
});
}
[Fact]
public static void GetKeyList_CopyTo_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
AssertExtensions.Throws<ArgumentNullException>("destinationArray", "dest", () => keys.CopyTo(null, 0)); // Array is null
AssertExtensions.Throws<ArgumentException>("array", null, () => keys.CopyTo(new object[10, 10], 0)); // Array is multidimensional -- in netfx ParamName is null
// Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("destinationIndex", "dstIndex", () => keys.CopyTo(new object[100], -1));
// Index + list.Count > array.Count
AssertExtensions.Throws<ArgumentException>("destinationArray", string.Empty, () => keys.CopyTo(new object[150], 51));
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void GetKeyList_GetEnumerator(int count)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
Assert.NotSame(keys.GetEnumerator(), keys.GetEnumerator());
IEnumerator enumerator = sortList2.GetEnumerator();
for (int i = 0; i < 2; i++)
{
int counter = 0;
while (enumerator.MoveNext())
{
object key = keys[counter];
DictionaryEntry entry = (DictionaryEntry)enumerator.Current;
Assert.Equal(key, entry.Key);
Assert.Equal(sortList2[key], entry.Value);
counter++;
}
Assert.Equal(count, counter);
enumerator.Reset();
}
});
}
[Fact]
public static void GetKeyList_GetEnumerator_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
// If the underlying collection is modified, MoveNext, Reset, Entry, Key and Value throw, but Current etc. doesn't
IEnumerator enumerator = keys.GetEnumerator();
enumerator.MoveNext();
sortList2.Add(101, 101);
Assert.NotNull(enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Reset());
// Current etc. throw if index < 0
enumerator = keys.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Current etc. throw after resetting
enumerator = keys.GetEnumerator();
enumerator.MoveNext();
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Current etc. throw if the current index is >= count
enumerator = keys.GetEnumerator();
while (enumerator.MoveNext()) ;
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
});
}
[Fact]
public static void GetKeyList_TryingToModifyCollection_ThrowsNotSupportedException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList keys = sortList2.GetKeyList();
Assert.Throws<NotSupportedException>(() => keys.Add(101));
Assert.Throws<NotSupportedException>(() => keys.Clear());
Assert.Throws<NotSupportedException>(() => keys.Insert(0, 101));
Assert.Throws<NotSupportedException>(() => keys.Remove(1));
Assert.Throws<NotSupportedException>(() => keys.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => keys[0] = 101);
});
}
[Theory]
[InlineData(0)]
[InlineData(100)]
public static void GetKey(int count)
{
SortedList sortList1 = Helpers.CreateStringSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < count; i++)
{
string key = "Key_" + i.ToString("D2");
Assert.Equal(key, sortList2.GetKey(sortList2.IndexOfKey(key)));
}
});
}
[Fact]
public static void GetKey_InvalidIndex_ThrowsArgumentOutOfRangeException()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.Throws<ArgumentOutOfRangeException>("index", () => sortList2.GetKey(-1)); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => sortList2.GetKey(sortList2.Count)); // Index >= count
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void GetValueList(int count)
{
SortedList sortList1 = Helpers.CreateStringSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values1 = sortList2.GetValueList();
IList values2 = sortList2.GetValueList();
// Test we have copied the correct values
Assert.Equal(count, values1.Count);
Assert.Equal(count, values2.Count);
for (int i = 0; i < values1.Count; i++)
{
string value = "Value_" + i;
Assert.Equal(value, values1[i]);
Assert.Equal(value, values2[i]);
Assert.True(sortList2.ContainsValue(values2[i]));
}
});
}
[Fact]
public static void GetValueList_IsSameAsValuesProperty()
{
var sortList = Helpers.CreateIntSortedList(10);
Assert.Same(sortList.GetValueList(), sortList.Values);
}
[Fact]
public static void GetValueList_IListProperties()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
Assert.True(values.IsReadOnly);
Assert.True(values.IsFixedSize);
Assert.False(values.IsSynchronized);
Assert.Equal(sortList2.SyncRoot, values.SyncRoot);
});
}
[Fact]
public static void GetValueList_Contains()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
for (int i = 0; i < values.Count; i++)
{
string value = "Value_" + i;
Assert.True(values.Contains(value));
}
// No such value
Assert.False(values.Contains("Value_101"));
Assert.False(values.Contains(101));
Assert.False(values.Contains(null));
});
}
[Fact]
public static void GetValueList_IndexOf()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
for (int i = 0; i < values.Count; i++)
{
string value = "Value_" + i;
Assert.Equal(i, values.IndexOf(value));
}
Assert.Equal(-1, values.IndexOf(101));
});
}
[Theory]
[InlineData(0, 0)]
[InlineData(1, 0)]
[InlineData(10, 0)]
[InlineData(100, 0)]
[InlineData(0, 50)]
[InlineData(1, 50)]
[InlineData(10, 50)]
[InlineData(100, 50)]
public static void GetValueList_CopyTo(int count, int index)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
object[] array = new object[index + count];
IList values = sortList2.GetValueList();
values.CopyTo(array, index);
Assert.Equal(index + count, array.Length);
for (int i = index; i < index + count; i++)
{
Assert.Equal(values[i - index], array[i]);
}
});
}
[Fact]
public static void GetValueList_CopyTo_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
AssertExtensions.Throws<ArgumentNullException>("destinationArray", "dest", () => values.CopyTo(null, 0)); // Array is null
AssertExtensions.Throws<ArgumentException>("array", null, () => values.CopyTo(new object[10, 10], 0)); // Array is multidimensional -- in netfx ParamName is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("destinationIndex", "dstIndex", () => values.CopyTo(new object[100], -1)); // Index < 0
AssertExtensions.Throws<ArgumentException>("destinationArray", string.Empty, () => values.CopyTo(new object[150], 51)); // Index + list.Count > array.Count
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public static void GetValueList_GetEnumerator(int count)
{
SortedList sortList1 = Helpers.CreateIntSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
Assert.NotSame(values.GetEnumerator(), values.GetEnumerator());
IEnumerator enumerator = sortList2.GetEnumerator();
for (int i = 0; i < 2; i++)
{
int counter = 0;
while (enumerator.MoveNext())
{
object key = values[counter];
DictionaryEntry entry = (DictionaryEntry)enumerator.Current;
Assert.Equal(key, entry.Key);
Assert.Equal(sortList2[key], entry.Value);
counter++;
}
Assert.Equal(count, counter);
enumerator.Reset();
}
});
}
[Fact]
public static void ValueList_GetEnumerator_Invalid()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
// If the underlying collection is modified, MoveNext, Reset, Entry, Key and Value throw, but Current etc. doesn't
IEnumerator enumerator = values.GetEnumerator();
enumerator.MoveNext();
sortList2.Add(101, 101);
Assert.NotNull(enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Reset());
// Current etc. throw if index < 0
enumerator = values.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Current etc. throw after resetting
enumerator = values.GetEnumerator();
enumerator.MoveNext();
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Current etc. throw if the current index is >= count
enumerator = values.GetEnumerator();
while (enumerator.MoveNext()) ;
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
});
}
[Fact]
public static void GetValueList_TryingToModifyCollection_ThrowsNotSupportedException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
IList values = sortList2.GetValueList();
Assert.Throws<NotSupportedException>(() => values.Add(101));
Assert.Throws<NotSupportedException>(() => values.Clear());
Assert.Throws<NotSupportedException>(() => values.Insert(0, 101));
Assert.Throws<NotSupportedException>(() => values.Remove(1));
Assert.Throws<NotSupportedException>(() => values.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => values[0] = 101);
});
}
[Fact]
public static void IndexOfKey()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < sortList2.Count; i++)
{
string key = "Key_" + i.ToString("D2");
string value = "Value_" + i;
int index = sortList2.IndexOfKey(key);
Assert.Equal(i, index);
Assert.Equal(value, sortList2.GetByIndex(index));
}
Assert.Equal(-1, sortList2.IndexOfKey("Non Existent Key"));
string removedKey = "Key_01";
sortList2.Remove(removedKey);
Assert.Equal(-1, sortList2.IndexOfKey(removedKey));
});
}
[Fact]
public static void IndexOfKey_NullKey_ThrowsArgumentNullException()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.Throws<ArgumentNullException>("key", () => sortList2.IndexOfKey(null)); // Key is null
});
}
[Fact]
public static void IndexOfValue()
{
SortedList sortList1 = Helpers.CreateStringSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < sortList2.Count; i++)
{
string value = "Value_" + i;
int index = sortList2.IndexOfValue(value);
Assert.Equal(i, index);
Assert.Equal(value, sortList2.GetByIndex(index));
}
Assert.Equal(-1, sortList2.IndexOfValue("Non Existent Value"));
string removedKey = "Key_01";
string removedValue = "Value_1";
sortList2.Remove(removedKey);
Assert.Equal(-1, sortList2.IndexOfValue(removedValue));
Assert.Equal(-1, sortList2.IndexOfValue(null));
sortList2.Add("Key_101", null);
Assert.NotEqual(-1, sortList2.IndexOfValue(null));
});
}
[Fact]
public static void IndexOfValue_SameValue()
{
var sortList1 = new SortedList();
sortList1.Add("Key_0", "Value_0");
sortList1.Add("Key_1", "Value_Same");
sortList1.Add("Key_2", "Value_Same");
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.Equal(1, sortList2.IndexOfValue("Value_Same"));
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(4)]
[InlineData(5000)]
public static void Capacity_Get_Set(int capacity)
{
var sortList = new SortedList();
sortList.Capacity = capacity;
Assert.Equal(capacity, sortList.Capacity);
// Ensure nothing changes if we set capacity to the same value again
sortList.Capacity = capacity;
Assert.Equal(capacity, sortList.Capacity);
}
[Fact]
public static void Capacity_Set_ShrinkingCapacity_ThrowsArgumentOutOfRangeException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.Throws<ArgumentOutOfRangeException>("value", () => sortList2.Capacity = sortList2.Count - 1); // Capacity < count
});
}
[Fact]
public static void Capacity_Set_Invalid()
{
var sortList1 = new SortedList();
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.Throws<ArgumentOutOfRangeException>("value", () => sortList2.Capacity = -1); // Capacity < 0
Assert.Throws<OutOfMemoryException>(() => sortList2.Capacity = int.MaxValue); // Capacity is too large
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
public static void Item_Get(int count)
{
SortedList sortList1 = Helpers.CreateStringSortedList(count);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < count; i++)
{
string key = "Key_" + i.ToString("D2");
string value = "Value_" + i;
Assert.Equal(value, sortList2[key]);
}
Assert.Null(sortList2["No Such Key"]);
string removedKey = "Key_01";
sortList2.Remove(removedKey);
Assert.Null(sortList2[removedKey]);
});
}
[Fact]
public static void Item_Get_DifferentCulture()
{
var sortList = new SortedList();
CultureInfo currentCulture = CultureInfo.CurrentCulture;
try
{
CultureInfo.CurrentCulture = new CultureInfo("en-US");
var cultureNames = new string[]
{
"cs-CZ","da-DK","de-DE","el-GR","en-US",
"es-ES","fi-FI","fr-FR","hu-HU","it-IT",
"ja-JP","ko-KR","nb-NO","nl-NL","pl-PL",
"pt-BR","pt-PT","ru-RU","sv-SE","tr-TR",
"zh-CN","zh-HK","zh-TW"
};
var installedCultures = new CultureInfo[cultureNames.Length];
var cultureDisplayNames = new string[installedCultures.Length];
int uniqueDisplayNameCount = 0;
foreach (string cultureName in cultureNames)
{
var culture = new CultureInfo(cultureName);
installedCultures[uniqueDisplayNameCount] = culture;
cultureDisplayNames[uniqueDisplayNameCount] = culture.DisplayName;
sortList.Add(cultureDisplayNames[uniqueDisplayNameCount], culture);
uniqueDisplayNameCount++;
}
// In Czech ch comes after h if the comparer changes based on the current culture of the thread
// we will not be able to find some items
CultureInfo.CurrentCulture = new CultureInfo("cs-CZ");
for (int i = 0; i < uniqueDisplayNameCount; i++)
{
Assert.Equal(installedCultures[i], sortList[installedCultures[i].DisplayName]);
}
}
catch (CultureNotFoundException)
{
}
finally
{
CultureInfo.CurrentCulture = currentCulture;
}
}
[Fact]
public static void Item_Set()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
// Change existing keys
for (int i = 0; i < sortList2.Count; i++)
{
sortList2[i] = i + 1;
Assert.Equal(i + 1, sortList2[i]);
// Make sure nothing bad happens when we try to set the key to its current valeu
sortList2[i] = i + 1;
Assert.Equal(i + 1, sortList2[i]);
}
// Add new keys
sortList2[101] = 2048;
Assert.Equal(2048, sortList2[101]);
sortList2[102] = null;
Assert.Equal(null, sortList2[102]);
});
}
[Fact]
public static void Item_Set_NullKey_ThrowsArgumentNullException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.Throws<ArgumentNullException>("key", () => sortList2[null] = 101); // Key is null
});
}
[Fact]
public static void RemoveAt()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
// Remove from end
for (int i = sortList2.Count - 1; i >= 0; i--)
{
sortList2.RemoveAt(i);
Assert.False(sortList2.ContainsKey(i));
Assert.False(sortList2.ContainsValue(i));
Assert.Equal(i, sortList2.Count);
}
});
}
[Fact]
public static void RemoveAt_InvalidIndex_ThrowsArgumentOutOfRangeException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.Throws<ArgumentOutOfRangeException>("index", () => sortList2.RemoveAt(-1)); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => sortList2.RemoveAt(sortList2.Count)); // Index >= count
});
}
[Fact]
public static void Remove()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
// Remove from the end
for (int i = sortList2.Count - 1; i >= 0; i--)
{
sortList2.Remove(i);
Assert.False(sortList2.ContainsKey(i));
Assert.False(sortList2.ContainsValue(i));
Assert.Equal(i, sortList2.Count);
}
sortList2.Remove(101); // No such key
});
}
[Fact]
public static void Remove_NullKey_ThrowsArgumentNullException()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.Throws<ArgumentNullException>("key", () => sortList2.Remove(null)); // Key is null
});
}
[Fact]
public static void SetByIndex()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < sortList2.Count; i++)
{
sortList2.SetByIndex(i, i + 1);
Assert.Equal(i + 1, sortList2.GetByIndex(i));
}
});
}
[Fact]
public static void SetByIndex_InvalidIndex_ThrowsArgumentOutOfRangeExeption()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
Assert.Throws<ArgumentOutOfRangeException>("index", () => sortList2.SetByIndex(-1, 101)); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => sortList2.SetByIndex(sortList2.Count, 101)); // Index >= list.Count
});
}
[Fact]
public static void Synchronized_IsSynchronized()
{
SortedList sortList = SortedList.Synchronized(new SortedList());
Assert.True(sortList.IsSynchronized);
}
[Fact]
public static void Synchronized_NullList_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("list", () => SortedList.Synchronized(null)); // List is null
}
[Fact]
public static void TrimToSize()
{
SortedList sortList1 = Helpers.CreateIntSortedList(100);
Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 =>
{
for (int i = 0; i < 10; i++)
{
sortList2.RemoveAt(0);
}
sortList2.TrimToSize();
Assert.Equal(sortList2.Count, sortList2.Capacity);
sortList2.Clear();
sortList2.TrimToSize();
Assert.Equal(0, sortList2.Capacity);
});
}
private class Foo
{
public string StringValue { get; set; } = "Hello World";
}
private class CustomComparer : IComparer
{
public int Compare(object obj1, object obj2) => -string.Compare(obj1.ToString(), obj2.ToString());
}
}
public class SortedList_SyncRootTests
{
private SortedList _sortListDaughter;
private SortedList _sortListGrandDaughter;
private const int NumberOfElements = 100;
[Fact]
[OuterLoop]
public void GetSyncRootBasic()
{
// Testing SyncRoot is not as simple as its implementation looks like. This is the working
// scenario we have in mind.
// 1) Create your Down to earth mother SortedList
// 2) Get a synchronized wrapper from it
// 3) Get a Synchronized wrapper from 2)
// 4) Get a synchronized wrapper of the mother from 1)
// 5) all of these should SyncRoot to the mother earth
var sortListMother = new SortedList();
for (int i = 0; i < NumberOfElements; i++)
{
sortListMother.Add("Key_" + i, "Value_" + i);
}
Assert.Equal(sortListMother.SyncRoot.GetType(), typeof(object));
SortedList sortListSon = SortedList.Synchronized(sortListMother);
_sortListGrandDaughter = SortedList.Synchronized(sortListSon);
_sortListDaughter = SortedList.Synchronized(sortListMother);
Assert.Equal(sortListSon.SyncRoot, sortListMother.SyncRoot);
Assert.Equal(sortListMother.SyncRoot, sortListSon.SyncRoot);
Assert.Equal(_sortListGrandDaughter.SyncRoot, sortListMother.SyncRoot);
Assert.Equal(_sortListDaughter.SyncRoot, sortListMother.SyncRoot);
Assert.Equal(sortListSon.SyncRoot, sortListMother.SyncRoot);
//we are going to rumble with the SortedLists with some threads
var workers = new Task[4];
for (int i = 0; i < workers.Length; i += 2)
{
var name = "Thread_worker_" + i;
var action1 = new Action(() => AddMoreElements(name));
var action2 = new Action(RemoveElements);
workers[i] = Task.Run(action1);
workers[i + 1] = Task.Run(action2);
}
Task.WaitAll(workers);
// Checking time
// Now lets see how this is done.
// Either there are some elements or none
var sortListPossible = new SortedList();
for (int i = 0; i < NumberOfElements; i++)
{
sortListPossible.Add("Key_" + i, "Value_" + i);
}
for (int i = 0; i < workers.Length; i++)
{
sortListPossible.Add("Key_Thread_worker_" + i, "Thread_worker_" + i);
}
//lets check the values if
IDictionaryEnumerator enumerator = sortListMother.GetEnumerator();
while (enumerator.MoveNext())
{
Assert.True(sortListPossible.ContainsKey(enumerator.Key));
Assert.True(sortListPossible.ContainsValue(enumerator.Value));
}
}
private void AddMoreElements(string threadName)
{
_sortListGrandDaughter.Add("Key_" + threadName, threadName);
}
private void RemoveElements()
{
_sortListDaughter.Clear();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Transactions;
using Microsoft.SqlServer.Server;
using Xunit;
using System.Threading.Tasks;
using System.Diagnostics;
namespace System.Data.SqlClient.ManualTesting.Tests
{
public class TvpTest
{
private const string TvpName = "@tvp";
private static readonly IList<SteAttributeKey> BoundariesTestKeys = new List<SteAttributeKey>(
new SteAttributeKey[] {
SteAttributeKey.SqlDbType,
SteAttributeKey.MultiValued,
SteAttributeKey.MaxLength,
SteAttributeKey.Precision,
SteAttributeKey.Scale,
SteAttributeKey.LocaleId,
SteAttributeKey.CompareOptions,
SteAttributeKey.TypeName,
SteAttributeKey.Type,
SteAttributeKey.Fields,
SteAttributeKey.Value
}).AsReadOnly();
// data value and server consts
private string _connStr;
[ActiveIssue(27858, TestPlatforms.AnyUnix)]
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
public void TestMain()
{
Assert.True(RunTestCoreAndCompareWithBaseline());
}
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
public void TestPacketNumberWraparound()
{
// this test uses a specifically crafted sql record enumerator and data to put the TdsParserStateObject.WritePacket(byte,bool)
// into a state where it can't differentiate between a packet in the middle of a large packet-set after a byte counter wraparound
// and the first packet of the connection and in doing so trips over a check for packet length from the input which has been
// forced to tell it that there is no output buffer space left, this causes an uncancellable infinite loop
// if the enumerator is completely read to the end then the bug is no longer present and the packet creation task returns,
// if the timeout occurs it is probable (but not absolute) that the write is stuck
var enumerator = new WraparoundRowEnumerator(1000000);
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
int returned = Task.WaitAny(
Task.Factory.StartNew(
() => RunPacketNumberWraparound(enumerator),
TaskCreationOptions.DenyChildAttach | TaskCreationOptions.LongRunning
),
Task.Delay(TimeSpan.FromSeconds(60))
);
stopwatch.Stop();
if (enumerator.MaxCount != enumerator.Count)
{
Console.WriteLine($"enumerator.Count={enumerator.Count}, enumerator.MaxCount={enumerator.MaxCount}, elapsed={stopwatch.Elapsed.TotalSeconds}");
}
Assert.True(enumerator.MaxCount == enumerator.Count);
}
public TvpTest()
{
_connStr = DataTestUtility.TcpConnStr;
}
private void RunTest()
{
Console.WriteLine("Starting test \'TvpTest\'");
StreamInputParam.Run(_connStr);
ColumnBoundariesTest();
QueryHintsTest();
SqlVariantParam.SendAllSqlTypesInsideVariant(_connStr);
DateTimeVariantTest.TestAllDateTimeWithDataTypeAndVariant(_connStr);
OutputParameter.Run(_connStr);
}
private bool RunTestCoreAndCompareWithBaseline()
{
string outputPath = "SqlParameterTest.out";
#if DEBUG
string baselinePath = "SqlParameterTest_DebugMode.bsl";
#else
string baselinePath = "SqlParameterTest_ReleaseMode.bsl";
#endif
var fstream = new FileStream(outputPath, FileMode.Create, FileAccess.Write, FileShare.Read);
var swriter = new StreamWriter(fstream, Encoding.UTF8);
// Convert all string writes of '\n' to '\r\n' so output files can be 'text' not 'binary'
var twriter = new CarriageReturnLineFeedReplacer(swriter);
Console.SetOut(twriter); // "redirect" Console.Out
// Run Test
RunTest();
Console.Out.Flush();
Console.Out.Dispose();
// Recover the standard output stream
StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
// Compare output file
var comparisonResult = FindDiffFromBaseline(baselinePath, outputPath);
if (string.IsNullOrEmpty(comparisonResult))
{
return true;
}
Console.WriteLine("Test Failed!");
Console.WriteLine("Please compare baseline : {0} with output :{1}", Path.GetFullPath(baselinePath), Path.GetFullPath(outputPath));
Console.WriteLine("Comparison Results : ");
Console.WriteLine(comparisonResult);
return false;
}
private string FindDiffFromBaseline(string baselinePath, string outputPath)
{
var expectedLines = File.ReadAllLines(baselinePath);
var outputLines = File.ReadAllLines(outputPath);
var comparisonSb = new StringBuilder();
// Start compare results
var expectedLength = expectedLines.Length;
var outputLength = outputLines.Length;
var findDiffLength = Math.Min(expectedLength, outputLength);
// Find diff for each lines
for (var lineNo = 0; lineNo < findDiffLength; lineNo++)
{
if (!expectedLines[lineNo].Equals(outputLines[lineNo]))
{
comparisonSb.AppendFormat("** DIFF at line {0} \n", lineNo);
comparisonSb.AppendFormat("A : {0} \n", outputLines[lineNo]);
comparisonSb.AppendFormat("E : {0} \n", expectedLines[lineNo]);
}
}
var startIndex = findDiffLength - 1;
if (startIndex < 0)
startIndex = 0;
if (findDiffLength < expectedLength)
{
comparisonSb.AppendFormat("** MISSING \n");
for (var lineNo = startIndex; lineNo < expectedLength; lineNo++)
{
comparisonSb.AppendFormat("{0} : {1}", lineNo, expectedLines[lineNo]);
}
}
if (findDiffLength < outputLength)
{
comparisonSb.AppendFormat("** EXTRA \n");
for (var lineNo = startIndex; lineNo < outputLength; lineNo++)
{
comparisonSb.AppendFormat("{0} : {1}", lineNo, outputLines[lineNo]);
}
}
return comparisonSb.ToString();
}
private sealed class CarriageReturnLineFeedReplacer : TextWriter
{
private TextWriter _output;
private int _lineFeedCount;
private bool _hasCarriageReturn;
internal CarriageReturnLineFeedReplacer(TextWriter output)
{
if (output == null)
throw new ArgumentNullException(nameof(output));
_output = output;
}
public int LineFeedCount
{
get { return _lineFeedCount; }
}
public override Encoding Encoding
{
get { return _output.Encoding; }
}
public override IFormatProvider FormatProvider
{
get { return _output.FormatProvider; }
}
public override string NewLine
{
get { return _output.NewLine; }
set { _output.NewLine = value; }
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
((IDisposable)_output).Dispose();
}
_output = null;
}
public override void Flush()
{
_output.Flush();
}
public override void Write(char value)
{
if ('\n' == value)
{
_lineFeedCount++;
if (!_hasCarriageReturn)
{ // X'\n'Y -> X'\r\n'Y
_output.Write('\r');
}
}
_hasCarriageReturn = '\r' == value;
_output.Write(value);
}
}
#region Main test methods
private void ColumnBoundariesTest()
{
IEnumerator<StePermutation> boundsMD = SteStructuredTypeBoundaries.AllColumnTypesExceptUdts.GetEnumerator(
BoundariesTestKeys);
TestTVPPermutations(SteStructuredTypeBoundaries.AllColumnTypesExceptUdts, false);
//Console.WriteLine("+++++++++++ UDT TVP tests ++++++++++++++");
//TestTVPPermutations(SteStructuredTypeBoundaries.UdtsOnly, true);
}
private void TestTVPPermutations(SteStructuredTypeBoundaries bounds, bool runOnlyDataRecordTest)
{
IEnumerator<StePermutation> boundsMD = bounds.GetEnumerator(BoundariesTestKeys);
object[][] baseValues = SteStructuredTypeBoundaries.GetSeparateValues(boundsMD);
IList<DataTable> dtList = GenerateDataTables(baseValues);
TransactionOptions opts = new TransactionOptions();
opts.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
// for each unique pattern of metadata
int iter = 0;
while (boundsMD.MoveNext())
{
Console.WriteLine("+++++++ Iteration {0} ++++++++", iter);
StePermutation tvpPerm = boundsMD.Current;
// Set up base command
SqlCommand cmd;
SqlParameter param;
cmd = new SqlCommand(GetProcName(tvpPerm));
cmd.CommandType = CommandType.StoredProcedure;
param = cmd.Parameters.Add(TvpName, SqlDbType.Structured);
param.TypeName = GetTypeName(tvpPerm);
// set up the server
try
{
CreateServerObjects(tvpPerm);
}
catch (SqlException se)
{
Console.WriteLine("SqlException creating objects: {0}", se.Number);
DropServerObjects(tvpPerm);
iter++;
continue;
}
// Send list of SqlDataRecords as value
Console.WriteLine("------IEnumerable<SqlDataRecord>---------");
try
{
param.Value = CreateListOfRecords(tvpPerm, baseValues);
ExecuteAndVerify(cmd, tvpPerm, baseValues, null);
}
catch (ArgumentException ae)
{
// some argument exceptions expected and should be swallowed
Console.WriteLine("Argument exception in value setup: {0}", ae.Message);
}
if (!runOnlyDataRecordTest)
{
// send DbDataReader
Console.WriteLine("------DbDataReader---------");
try
{
param.Value = new TvpRestartableReader(CreateListOfRecords(tvpPerm, baseValues));
ExecuteAndVerify(cmd, tvpPerm, baseValues, null);
}
catch (ArgumentException ae)
{
// some argument exceptions expected and should be swallowed
Console.WriteLine("Argument exception in value setup: {0}", ae.Message);
}
// send datasets
Console.WriteLine("------DataTables---------");
foreach (DataTable d in dtList)
{
param.Value = d;
ExecuteAndVerify(cmd, tvpPerm, null, d);
}
}
// And clean up
DropServerObjects(tvpPerm);
iter++;
}
}
private void QueryHintsTest()
{
using (SqlConnection conn = new SqlConnection(_connStr))
{
conn.Open();
Guid randomizer = Guid.NewGuid();
string typeName = string.Format("dbo.[QHint_{0}]", randomizer);
string procName = string.Format("dbo.[QHint_Proc_{0}]", randomizer);
string createTypeSql = string.Format(
"CREATE TYPE {0} AS TABLE("
+ " c1 Int DEFAULT -1,"
+ " c2 NVarChar(40) DEFAULT N'DEFUALT',"
+ " c3 DateTime DEFAULT '1/1/2006',"
+ " c4 Int DEFAULT -1)",
typeName);
string createProcSql = string.Format(
"CREATE PROC {0}(@tvp {1} READONLY) AS SELECT TOP(2) * FROM @tvp ORDER BY c1", procName, typeName);
string dropSql = string.Format("DROP PROC {0}; DROP TYPE {1}", procName, typeName);
try
{
SqlCommand cmd = new SqlCommand(createTypeSql, conn);
cmd.ExecuteNonQuery();
cmd.CommandText = createProcSql;
cmd.ExecuteNonQuery();
cmd.CommandText = procName;
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param = cmd.Parameters.Add("@tvp", SqlDbType.Structured);
SqlMetaData[] columnMetadata;
List<SqlDataRecord> rows = new List<SqlDataRecord>();
SqlDataRecord record;
Console.WriteLine("------- Sort order + uniqueness #1: simple -------");
columnMetadata = new SqlMetaData[] {
new SqlMetaData("", SqlDbType.Int, false, true, SortOrder.Ascending, 0),
new SqlMetaData("", SqlDbType.NVarChar, 40, false, true, SortOrder.Descending, 1),
new SqlMetaData("", SqlDbType.DateTime, false, true, SortOrder.Ascending, 2),
new SqlMetaData("", SqlDbType.Int, false, true, SortOrder.Descending, 3),
};
record = new SqlDataRecord(columnMetadata);
record.SetValues(0, "Z-value", DateTime.Parse("03/01/2000"), 5);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(1, "Y-value", DateTime.Parse("02/01/2000"), 6);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(1, "X-value", DateTime.Parse("01/01/2000"), 7);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(1, "X-value", DateTime.Parse("04/01/2000"), 8);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(1, "X-value", DateTime.Parse("04/01/2000"), 4);
rows.Add(record);
param.Value = rows;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
WriteReader(rdr);
}
rows.Clear();
Console.WriteLine("------- Sort order + uniqueness #2: mixed order -------");
columnMetadata = new SqlMetaData[] {
new SqlMetaData("", SqlDbType.Int, false, true, SortOrder.Descending, 3),
new SqlMetaData("", SqlDbType.NVarChar, 40, false, true, SortOrder.Descending, 0),
new SqlMetaData("", SqlDbType.DateTime, false, true, SortOrder.Ascending, 2),
new SqlMetaData("", SqlDbType.Int, false, true, SortOrder.Ascending, 1),
};
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 1);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 2);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Y-value", DateTime.Parse("01/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Y-value", DateTime.Parse("02/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(5, "X-value", DateTime.Parse("03/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(4, "X-value", DateTime.Parse("01/01/2000"), 3);
rows.Add(record);
param.Value = rows;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
WriteReader(rdr);
}
rows.Clear();
Console.WriteLine("------- default column #1: outer subset -------");
columnMetadata = new SqlMetaData[] {
new SqlMetaData("", SqlDbType.Int, true, false, SortOrder.Unspecified, -1),
new SqlMetaData("", SqlDbType.NVarChar, 40, false, false, SortOrder.Unspecified, -1),
new SqlMetaData("", SqlDbType.DateTime, false, false, SortOrder.Unspecified, -1),
new SqlMetaData("", SqlDbType.Int, true, false, SortOrder.Unspecified, -1),
};
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 1);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 2);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Y-value", DateTime.Parse("01/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Y-value", DateTime.Parse("02/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(5, "X-value", DateTime.Parse("03/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(4, "X-value", DateTime.Parse("01/01/2000"), 3);
rows.Add(record);
param.Value = rows;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
WriteReader(rdr);
}
rows.Clear();
Console.WriteLine("------- default column #1: middle subset -------");
columnMetadata = new SqlMetaData[] {
new SqlMetaData("", SqlDbType.Int, false, false, SortOrder.Unspecified, -1),
new SqlMetaData("", SqlDbType.NVarChar, 40, true, false, SortOrder.Unspecified, -1),
new SqlMetaData("", SqlDbType.DateTime, true, false, SortOrder.Unspecified, -1),
new SqlMetaData("", SqlDbType.Int, false, false, SortOrder.Unspecified, -1),
};
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 1);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 2);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Y-value", DateTime.Parse("01/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Y-value", DateTime.Parse("02/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(5, "X-value", DateTime.Parse("03/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(4, "X-value", DateTime.Parse("01/01/2000"), 3);
rows.Add(record);
param.Value = rows;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
WriteReader(rdr);
}
rows.Clear();
Console.WriteLine("------- default column #1: all -------");
columnMetadata = new SqlMetaData[] {
new SqlMetaData("", SqlDbType.Int, true, false, SortOrder.Unspecified, -1),
new SqlMetaData("", SqlDbType.NVarChar, 40, true, false, SortOrder.Unspecified, -1),
new SqlMetaData("", SqlDbType.DateTime, true, false, SortOrder.Unspecified, -1),
new SqlMetaData("", SqlDbType.Int, true, false, SortOrder.Unspecified, -1),
};
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 1);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 2);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Y-value", DateTime.Parse("01/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(6, "Y-value", DateTime.Parse("02/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(5, "X-value", DateTime.Parse("03/01/2000"), 3);
rows.Add(record);
record = new SqlDataRecord(columnMetadata);
record.SetValues(4, "X-value", DateTime.Parse("01/01/2000"), 3);
rows.Add(record);
param.Value = rows;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
WriteReader(rdr);
}
rows.Clear();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
SqlCommand cmd = new SqlCommand(dropSql, conn);
cmd.ExecuteNonQuery();
}
}
}
private static async Task RunPacketNumberWraparound(WraparoundRowEnumerator enumerator)
{
using (var connection = new SqlConnection(DataTestUtility.TcpConnStr))
using (var cmd = new SqlCommand("unimportant")
{
CommandType = System.Data.CommandType.StoredProcedure,
Connection = connection,
})
{
await cmd.Connection.OpenAsync();
cmd.Parameters.Add(new SqlParameter("@rows", SqlDbType.Structured)
{
TypeName = "unimportant",
Value = enumerator,
});
try
{
await cmd.ExecuteNonQueryAsync();
}
catch (Exception)
{
// ignore the errors caused by the sproc and table type not existing
}
}
}
#endregion
#region Utility Methods
private bool AllowableDifference(string source, object result, StePermutation metadata)
{
object value;
bool returnValue = false;
// turn result into a string
string resultStr = null;
if (result.GetType() == typeof(string))
{
resultStr = (string)result;
}
else if (result.GetType() == typeof(char[]))
{
resultStr = new string((char[])result);
}
else if (result.GetType() == typeof(SqlChars))
{
resultStr = new string(((SqlChars)result).Value);
}
if (resultStr != null)
{
if (source.Equals(resultStr))
{
returnValue = true;
}
else if (metadata.TryGetValue(SteAttributeKey.MaxLength, out value) && value != SteTypeBoundaries.s_doNotUseMarker)
{
int maxLength = (int)value;
if (maxLength < source.Length &&
source.Substring(0, maxLength).Equals(resultStr))
{
returnValue = true;
}
// Check for length extension due to fixed-length type
else if (maxLength > source.Length &&
resultStr.Length == maxLength &&
metadata.TryGetValue(SteAttributeKey.SqlDbType, out value) &&
value != SteTypeBoundaries.s_doNotUseMarker &&
(SqlDbType.Char == ((SqlDbType)value) ||
SqlDbType.NChar == ((SqlDbType)value)))
{
returnValue = true;
}
}
}
return returnValue;
}
private bool AllowableDifference(byte[] source, object result, StePermutation metadata)
{
object value;
bool returnValue = false;
// turn result into byte array
byte[] resultBytes = null;
if (result.GetType() == typeof(byte[]))
{
resultBytes = (byte[])result;
}
else if (result.GetType() == typeof(SqlBytes))
{
resultBytes = ((SqlBytes)result).Value;
}
if (resultBytes != null)
{
if (source.Equals(resultBytes) || resultBytes.Length == source.Length)
{
returnValue = true;
}
else if (metadata.TryGetValue(SteAttributeKey.MaxLength, out value) && value != SteTypeBoundaries.s_doNotUseMarker)
{
int maxLength = (int)value;
// allowable max-length adjustments
if (maxLength == resultBytes.Length)
{ // a bit optimistic, but what the heck.
// truncation
if (maxLength <= source.Length)
{
returnValue = true;
}
// Check for length extension due to fixed-length type
else if (metadata.TryGetValue(SteAttributeKey.SqlDbType, out value) && value != SteTypeBoundaries.s_doNotUseMarker &&
(SqlDbType.Binary == ((SqlDbType)value)))
{
returnValue = true;
}
}
}
}
return returnValue;
}
private bool AllowableDifference(SqlDecimal source, object result, StePermutation metadata)
{
object value;
object value2;
bool returnValue = false;
// turn result into SqlDecimal
SqlDecimal resultValue = SqlDecimal.Null;
if (result.GetType() == typeof(SqlDecimal))
{
resultValue = (SqlDecimal)result;
}
else if (result.GetType() == typeof(decimal))
{
resultValue = new SqlDecimal((decimal)result);
}
else if (result.GetType() == typeof(SqlMoney))
{
resultValue = new SqlDecimal(((SqlMoney)result).Value);
}
if (!resultValue.IsNull)
{
if (source.Equals(resultValue))
{
returnValue = true;
}
else if (metadata.TryGetValue(SteAttributeKey.SqlDbType, out value) &&
SteTypeBoundaries.s_doNotUseMarker != value &&
(SqlDbType.SmallMoney == (SqlDbType)value ||
SqlDbType.Money == (SqlDbType)value))
{
// Some server conversions seem to lose the decimal places
// TODO: Investigate and validate that this is acceptable!
SqlDecimal tmp = SqlDecimal.ConvertToPrecScale(source, source.Precision, 0);
if (tmp.Equals(resultValue))
{
returnValue = true;
}
else
{
tmp = SqlDecimal.ConvertToPrecScale(resultValue, resultValue.Precision, 0);
returnValue = tmp.Equals(source);
}
}
// check if value was altered by precision/scale conversion
else if (metadata.TryGetValue(SteAttributeKey.SqlDbType, out value) &&
SteTypeBoundaries.s_doNotUseMarker != value &&
SqlDbType.Decimal == (SqlDbType)value)
{
if (metadata.TryGetValue(SteAttributeKey.Scale, out value) &&
metadata.TryGetValue(SteAttributeKey.Precision, out value2) &&
SteTypeBoundaries.s_doNotUseMarker != value &&
SteTypeBoundaries.s_doNotUseMarker != value2)
{
SqlDecimal tmp = SqlDecimal.ConvertToPrecScale(source, (byte)value2, (byte)value);
returnValue = tmp.Equals(resultValue);
}
// check if value was changed to 1 by the restartable reader
// due to exceeding size limits of System.Decimal
if (resultValue == (SqlDecimal)1M)
{
try
{
decimal dummy = source.Value;
}
catch (OverflowException)
{
returnValue = true;
}
}
}
}
return returnValue;
}
private bool CompareValue(object result, object source, StePermutation metadata)
{
bool isMatch = false;
if (!IsNull(source))
{
if (!IsNull(result))
{
if (source.Equals(result) || result.Equals(source))
{
isMatch = true;
}
else
{
switch (Type.GetTypeCode(source.GetType()))
{
case TypeCode.String:
isMatch = AllowableDifference((string)source, result, metadata);
break;
case TypeCode.Object:
{
if (source is char[])
{
source = new string((char[])source);
isMatch = AllowableDifference((string)source, result, metadata);
}
else if (source is byte[])
{
isMatch = AllowableDifference((byte[])source, result, metadata);
}
else if (source is SqlBytes)
{
isMatch = AllowableDifference(((SqlBytes)source).Value, result, metadata);
}
else if (source is SqlChars)
{
source = new string(((SqlChars)source).Value);
isMatch = AllowableDifference((string)source, result, metadata);
}
else if (source is SqlInt64 && result is long)
{
isMatch = result.Equals(((SqlInt64)source).Value);
}
else if (source is SqlInt32 && result is int)
{
isMatch = result.Equals(((SqlInt32)source).Value);
}
else if (source is SqlInt16 && result is short)
{
isMatch = result.Equals(((SqlInt16)source).Value);
}
else if (source is SqlSingle && result is float)
{
isMatch = result.Equals(((SqlSingle)source).Value);
}
else if (source is SqlDouble && result is double)
{
isMatch = result.Equals(((SqlDouble)source).Value);
}
else if (source is SqlDateTime && result is DateTime)
{
isMatch = result.Equals(((SqlDateTime)source).Value);
}
else if (source is SqlMoney)
{
isMatch = AllowableDifference(new SqlDecimal(((SqlMoney)source).Value), result, metadata);
}
else if (source is SqlDecimal)
{
isMatch = AllowableDifference((SqlDecimal)source, result, metadata);
}
}
break;
case TypeCode.Decimal:
if (result is SqlDecimal || result is decimal || result is SqlMoney)
{
isMatch = AllowableDifference(new SqlDecimal((decimal)source), result, metadata);
}
break;
default:
break;
}
}
}
}
else
{
if (IsNull(result))
{
isMatch = true;
}
}
if (!isMatch)
{
ReportMismatch(source, result, metadata);
}
return isMatch;
}
private IList<SqlDataRecord> CreateListOfRecords(StePermutation tvpPerm, object[][] baseValues)
{
IList<StePermutation> fields = GetFields(tvpPerm);
SqlMetaData[] fieldMetadata = new SqlMetaData[fields.Count];
int i = 0;
foreach (StePermutation perm in fields)
{
fieldMetadata[i] = PermToSqlMetaData(perm);
i++;
}
List<SqlDataRecord> records = new List<SqlDataRecord>(baseValues.Length);
for (int rowOrd = 0; rowOrd < baseValues.Length; rowOrd++)
{
object[] row = baseValues[rowOrd];
SqlDataRecord rec = new SqlDataRecord(fieldMetadata);
records.Add(rec); // Call SetValue *after* Add to ensure record is put in list
for (int colOrd = 0; colOrd < row.Length; colOrd++)
{
// Set value in try-catch to prevent some errors from aborting run.
try
{
rec.SetValue(colOrd, row[colOrd]);
}
catch (OverflowException oe)
{
Console.WriteLine("Failed Row[{0}]Col[{1}] = {2}: {3}", rowOrd, colOrd, row[colOrd], oe.Message);
}
catch (ArgumentException ae)
{
Console.WriteLine("Failed Row[{0}]Col[{1}] = {2}: {3}", rowOrd, colOrd, row[colOrd], ae.Message);
}
}
}
return records;
}
private DataTable CreateNewTable(object[] row, ref Type[] lastRowTypes)
{
DataTable dt = new DataTable();
for (int i = 0; i < row.Length; i++)
{
object value = row[i];
Type t;
if ((null == value || DBNull.Value == value))
{
if (lastRowTypes[i] == null)
{
return null;
}
else
{
t = lastRowTypes[i];
}
}
else
{
t = value.GetType();
}
dt.Columns.Add(new DataColumn("Col" + i + "_" + t.Name, t));
lastRowTypes[i] = t;
}
return dt;
}
// create table type and proc that uses that type at the server
private void CreateServerObjects(StePermutation tvpPerm)
{
// Create the table type tsql
StringBuilder tsql = new StringBuilder();
tsql.Append("CREATE TYPE ");
tsql.Append(GetTypeName(tvpPerm));
tsql.Append(" AS TABLE(");
bool addSeparator = false;
int colOrdinal = 1;
foreach (StePermutation perm in GetFields(tvpPerm))
{
if (addSeparator)
{
tsql.Append(", ");
}
else
{
addSeparator = true;
}
// column name
tsql.Append("column");
tsql.Append(colOrdinal);
tsql.Append(" ");
// column type
SqlDbType dbType = (SqlDbType)perm[SteAttributeKey.SqlDbType];
switch (dbType)
{
case SqlDbType.BigInt:
tsql.Append("Bigint");
break;
case SqlDbType.Binary:
tsql.Append("Binary(");
object maxLenObj = perm[SteAttributeKey.MaxLength];
int maxLen;
if (maxLenObj == SteTypeBoundaries.s_doNotUseMarker)
{
maxLen = 8000;
}
else
{
maxLen = (int)maxLenObj;
}
tsql.Append(maxLen);
tsql.Append(")");
break;
case SqlDbType.Bit:
tsql.Append("Bit");
break;
case SqlDbType.Char:
tsql.Append("Char(");
tsql.Append(perm[SteAttributeKey.MaxLength]);
tsql.Append(")");
break;
case SqlDbType.DateTime:
tsql.Append("DateTime");
break;
case SqlDbType.Decimal:
tsql.Append("Decimal(");
tsql.Append(perm[SteAttributeKey.Precision]);
tsql.Append(", ");
tsql.Append(perm[SteAttributeKey.Scale]);
tsql.Append(")");
break;
case SqlDbType.Float:
tsql.Append("Float");
break;
case SqlDbType.Image:
tsql.Append("Image");
break;
case SqlDbType.Int:
tsql.Append("Int");
break;
case SqlDbType.Money:
tsql.Append("Money");
break;
case SqlDbType.NChar:
tsql.Append("NChar(");
tsql.Append(perm[SteAttributeKey.MaxLength]);
tsql.Append(")");
break;
case SqlDbType.NText:
tsql.Append("NText");
break;
case SqlDbType.NVarChar:
tsql.Append("NVarChar(");
tsql.Append(perm[SteAttributeKey.MaxLength]);
tsql.Append(")");
break;
case SqlDbType.Real:
tsql.Append("Real");
break;
case SqlDbType.UniqueIdentifier:
tsql.Append("UniqueIdentifier");
break;
case SqlDbType.SmallDateTime:
tsql.Append("SmallDateTime");
break;
case SqlDbType.SmallInt:
tsql.Append("SmallInt");
break;
case SqlDbType.SmallMoney:
tsql.Append("SmallMoney");
break;
case SqlDbType.Text:
tsql.Append("Text");
break;
case SqlDbType.Timestamp:
tsql.Append("Timestamp");
break;
case SqlDbType.TinyInt:
tsql.Append("TinyInt");
break;
case SqlDbType.VarBinary:
tsql.Append("VarBinary(");
tsql.Append(perm[SteAttributeKey.MaxLength]);
tsql.Append(")");
break;
case SqlDbType.VarChar:
tsql.Append("VarChar(");
tsql.Append(perm[SteAttributeKey.MaxLength]);
tsql.Append(")");
break;
case SqlDbType.Variant:
tsql.Append("Variant");
break;
case SqlDbType.Xml:
tsql.Append("Xml");
break;
case SqlDbType.Udt:
string typeName = (string)perm[SteAttributeKey.TypeName];
tsql.Append(typeName);
break;
case SqlDbType.Structured:
throw new NotSupportedException("Not supported");
}
colOrdinal++;
}
tsql.Append(")");
using (SqlConnection conn = new SqlConnection(_connStr))
{
conn.Open();
// execute it to create the type
SqlCommand cmd = new SqlCommand(tsql.ToString(), conn);
cmd.ExecuteNonQuery();
// and create the proc that uses the type
cmd.CommandText = string.Format("CREATE PROC {0}(@tvp {1} READONLY) AS SELECT * FROM @tvp order by {2}",
GetProcName(tvpPerm), GetTypeName(tvpPerm), colOrdinal - 1);
cmd.ExecuteNonQuery();
}
}
private bool DoesRowMatchMetadata(object[] row, DataTable table)
{
bool result = true;
if (row.Length != table.Columns.Count)
{
result = false;
}
else
{
for (int i = 0; i < row.Length; i++)
{
if (null != row[i] && DBNull.Value != row[i] && row[i].GetType() != table.Columns[i].DataType)
{
result = false;
}
}
}
return result;
}
private void DropServerObjects(StePermutation tvpPerm)
{
string dropText = "DROP PROC " + GetProcName(tvpPerm) + "; DROP TYPE " + GetTypeName(tvpPerm);
using (SqlConnection conn = new SqlConnection(_connStr))
{
conn.Open();
SqlCommand cmd = new SqlCommand(dropText, conn);
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException e)
{
Console.WriteLine("SqlException dropping objects: {0}", e.Number);
}
}
}
private void ExecuteAndVerify(SqlCommand cmd, StePermutation tvpPerm, object[][] objValues, DataTable dtValues)
{
using (SqlConnection conn = new SqlConnection(_connStr))
{
conn.Open();
cmd.Connection = conn;
// cmd.Transaction = conn.BeginTransaction();
// and run the command
try
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
VerifyColumnBoundaries(rdr, GetFields(tvpPerm), objValues, dtValues);
}
}
catch (SqlException se)
{
Console.WriteLine("SqlException. Error Code: {0}", se.Number);
}
catch (InvalidOperationException ioe)
{
Console.WriteLine("InvalidOp: {0}", ioe.Message);
}
catch (ArgumentException ae)
{
Console.WriteLine("ArgumentException: {0}", ae.Message);
}
// And clean up. If an error is thrown, the connection being recycled
// will roll back the transaction
if (null != cmd.Transaction)
{
// cmd.Transaction.Rollback();
}
}
}
private IList<DataTable> GenerateDataTables(object[][] values)
{
List<DataTable> dtList = new List<DataTable>();
Type[] valueTypes = new Type[values[0].Length];
foreach (object[] row in values)
{
DataTable targetTable = null;
if (0 < dtList.Count)
{
// shortcut for matching last table (most common scenario)
if (DoesRowMatchMetadata(row, dtList[dtList.Count - 1]))
{
targetTable = dtList[dtList.Count - 1];
}
else
{
foreach (DataTable candidate in dtList)
{
if (DoesRowMatchMetadata(row, candidate))
{
targetTable = candidate;
break;
}
}
}
}
if (null == targetTable)
{
targetTable = CreateNewTable(row, ref valueTypes);
if (null != targetTable)
{
dtList.Add(targetTable);
}
}
if (null != targetTable)
{
targetTable.Rows.Add(row);
}
}
return dtList;
}
private IList<StePermutation> GetFields(StePermutation tvpPerm)
{
return (IList<StePermutation>)tvpPerm[SteAttributeKey.Fields];
}
private string GetProcName(StePermutation tvpPerm)
{
return "dbo.[Proc_" + (string)tvpPerm[SteAttributeKey.TypeName] + "]";
}
private string GetTypeName(StePermutation tvpPerm)
{
return "dbo.[" + (string)tvpPerm[SteAttributeKey.TypeName] + "]";
}
private bool IsNull(object value)
{
return null == value ||
DBNull.Value == value ||
(value is INullable &&
((INullable)value).IsNull);
}
private SqlMetaData PermToSqlMetaData(StePermutation perm)
{
object attr;
SqlDbType sqlDbType;
int maxLength = 0;
byte precision = 0;
byte scale = 0;
string typeName = null;
Type type = null;
long localeId = 0;
SqlCompareOptions opts = SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth;
if (perm.TryGetValue(SteAttributeKey.SqlDbType, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
{
sqlDbType = (SqlDbType)attr;
}
else
{
throw new InvalidOperationException("PermToSqlMetaData: No SqlDbType available!");
}
if (perm.TryGetValue(SteAttributeKey.MaxLength, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
{
maxLength = (int)attr;
}
if (perm.TryGetValue(SteAttributeKey.Precision, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
{
precision = (byte)attr;
}
if (perm.TryGetValue(SteAttributeKey.Scale, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
{
scale = (byte)attr;
}
if (perm.TryGetValue(SteAttributeKey.LocaleId, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
{
localeId = (int)attr;
}
if (perm.TryGetValue(SteAttributeKey.CompareOptions, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
{
opts = (SqlCompareOptions)attr;
}
if (perm.TryGetValue(SteAttributeKey.TypeName, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
{
typeName = (string)attr;
}
if (perm.TryGetValue(SteAttributeKey.Type, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
{
type = (Type)attr;
}
//if (SqlDbType.Udt == sqlDbType)
//{
// return new SqlMetaData("", sqlDbType, type, typeName);
//}
//else
//{
return new SqlMetaData("", sqlDbType, maxLength, precision, scale, localeId, opts, type);
//}
}
private void ReportMismatch(object source, object result, StePermutation perm)
{
if (null == source)
{
source = "(null)";
}
if (null == result)
{
result = "(null)";
}
Console.WriteLine("Mismatch: Source = {0}, result = {1}, metadata={2}", source, result, perm.ToString());
}
private void VerifyColumnBoundaries(SqlDataReader rdr, IList<StePermutation> fieldMetaData, object[][] values, DataTable dt)
{
int rowOrd = 0;
int matches = 0;
while (rdr.Read())
{
for (int columnOrd = 0; columnOrd < rdr.FieldCount; columnOrd++)
{
object value;
// Special case to handle decimal values that may be too large for GetValue
if (!rdr.IsDBNull(columnOrd) && rdr.GetFieldType(columnOrd) == typeof(decimal))
{
value = rdr.GetSqlValue(columnOrd);
}
else
{
value = rdr.GetValue(columnOrd);
}
if (null != values)
{
if (CompareValue(value, values[rowOrd][columnOrd], fieldMetaData[columnOrd]))
{
matches++;
}
else
{
Console.WriteLine(" Row={0}, Column={1}", rowOrd, columnOrd);
}
}
else
{
if (CompareValue(value, dt.Rows[rowOrd][columnOrd], fieldMetaData[columnOrd]))
{
matches++;
}
else
{
Console.WriteLine(" Row={0}, Column={1}", rowOrd, columnOrd);
}
}
}
rowOrd++;
}
Console.WriteLine("Matches = {0}", matches);
}
private void WriteReader(SqlDataReader rdr)
{
int colCount = rdr.FieldCount;
do
{
Console.WriteLine("-------------");
while (rdr.Read())
{
for (int i = 0; i < colCount; i++)
{
Console.Write("{0} ", rdr.GetValue(i));
}
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine("-------------");
}
while (rdr.NextResult());
}
private void DumpSqlParam(SqlParameter param)
{
Console.WriteLine("Parameter {0}", param.ParameterName);
Console.WriteLine(" IsNullable: {0}", param.IsNullable);
Console.WriteLine(" LocaleId: {0}", param.LocaleId);
Console.WriteLine(" Offset: {0}", param.Offset);
Console.WriteLine(" CompareInfo: {0}", param.CompareInfo);
Console.WriteLine(" DbType: {0}", param.DbType);
Console.WriteLine(" Direction: {0}", param.Direction);
Console.WriteLine(" Precision: {0}", param.Precision);
Console.WriteLine(" Scale: {0}", param.Scale);
Console.WriteLine(" Size: {0}", param.Size);
Console.WriteLine(" SqlDbType: {0}", param.SqlDbType);
Console.WriteLine(" TypeName: {0}", param.TypeName);
//Console.WriteLine(" UdtTypeName: {0}", param.UdtTypeName);
Console.WriteLine(" XmlSchemaCollectionDatabase: {0}", param.XmlSchemaCollectionDatabase);
Console.WriteLine(" XmlSchemaCollectionName: {0}", param.XmlSchemaCollectionName);
Console.WriteLine(" XmlSchemaCollectionSchema: {0}", param.XmlSchemaCollectionOwningSchema);
}
#endregion
}
internal class TvpRestartableReader : DbDataReader
{
private IList<SqlDataRecord> _sourceData;
int _currentRow;
internal TvpRestartableReader(IList<SqlDataRecord> source) : base()
{
_sourceData = source;
Restart();
}
public void Restart()
{
_currentRow = -1;
}
public override int Depth
{
get { return 0; }
}
public override int FieldCount
{
get { return _sourceData[_currentRow].FieldCount; }
}
public override bool HasRows
{
get { return _sourceData.Count > 0; }
}
public override bool IsClosed
{
get { return false; }
}
public override int RecordsAffected
{
get { return 0; }
}
public override object this[int ordinal]
{
get { return GetValue(ordinal); }
}
public override object this[string name]
{
get { return GetValue(GetOrdinal(name)); }
}
public override void Close()
{
_currentRow = _sourceData.Count;
}
public override string GetDataTypeName(int ordinal)
{
return _sourceData[_currentRow].GetDataTypeName(ordinal);
}
public override IEnumerator GetEnumerator()
{
return _sourceData.GetEnumerator();
}
public override Type GetFieldType(int ordinal)
{
return _sourceData[_currentRow].GetFieldType(ordinal);
}
public override string GetName(int ordinal)
{
return _sourceData[_currentRow].GetName(ordinal);
}
public override int GetOrdinal(string name)
{
return _sourceData[_currentRow].GetOrdinal(name);
}
public override DataTable GetSchemaTable()
{
SqlDataRecord rec = _sourceData[0];
DataTable schemaTable = new DataTable();
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.ColumnName, typeof(string)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.ColumnOrdinal, typeof(int)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.ColumnSize, typeof(int)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.NumericPrecision, typeof(short)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.NumericScale, typeof(short)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.DataType, typeof(System.Type)));
schemaTable.Columns.Add(new DataColumn(SchemaTableOptionalColumn.ProviderSpecificDataType, typeof(System.Type)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.NonVersionedProviderType, typeof(int)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.ProviderType, typeof(int)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.IsLong, typeof(bool)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.AllowDBNull, typeof(bool)));
schemaTable.Columns.Add(new DataColumn(SchemaTableOptionalColumn.IsReadOnly, typeof(bool)));
schemaTable.Columns.Add(new DataColumn(SchemaTableOptionalColumn.IsRowVersion, typeof(bool)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.IsUnique, typeof(bool)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.IsKey, typeof(bool)));
schemaTable.Columns.Add(new DataColumn(SchemaTableOptionalColumn.IsAutoIncrement, typeof(bool)));
schemaTable.Columns.Add(new DataColumn(SchemaTableOptionalColumn.IsHidden, typeof(bool)));
schemaTable.Columns.Add(new DataColumn(SchemaTableOptionalColumn.BaseCatalogName, typeof(string)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.BaseSchemaName, typeof(string)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.BaseTableName, typeof(string)));
schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.BaseColumnName, typeof(string)));
for (int i = 0; i < rec.FieldCount; i++)
{
DataRow row = schemaTable.NewRow();
SqlMetaData md = rec.GetSqlMetaData(i);
row[SchemaTableColumn.ColumnName] = md.Name;
row[SchemaTableColumn.ColumnOrdinal] = i;
row[SchemaTableColumn.ColumnSize] = md.MaxLength;
row[SchemaTableColumn.NumericPrecision] = md.Precision;
row[SchemaTableColumn.NumericScale] = md.Scale;
row[SchemaTableColumn.DataType] = rec.GetFieldType(i);
row[SchemaTableOptionalColumn.ProviderSpecificDataType] = rec.GetFieldType(i);
row[SchemaTableColumn.NonVersionedProviderType] = (int)md.SqlDbType;
row[SchemaTableColumn.ProviderType] = (int)md.SqlDbType;
row[SchemaTableColumn.IsLong] = md.MaxLength == SqlMetaData.Max || md.MaxLength > 8000;
row[SchemaTableColumn.AllowDBNull] = true;
row[SchemaTableOptionalColumn.IsReadOnly] = true;
row[SchemaTableOptionalColumn.IsRowVersion] = md.SqlDbType == SqlDbType.Timestamp;
row[SchemaTableColumn.IsUnique] = false;
row[SchemaTableColumn.IsKey] = false;
row[SchemaTableOptionalColumn.IsAutoIncrement] = false;
row[SchemaTableOptionalColumn.IsHidden] = false;
row[SchemaTableOptionalColumn.BaseCatalogName] = null;
row[SchemaTableColumn.BaseSchemaName] = null;
row[SchemaTableColumn.BaseTableName] = null;
row[SchemaTableColumn.BaseColumnName] = md.Name;
schemaTable.Rows.Add(row);
}
return schemaTable;
}
public override bool GetBoolean(int ordinal)
{
return _sourceData[_currentRow].GetBoolean(ordinal);
}
public override byte GetByte(int ordinal)
{
return _sourceData[_currentRow].GetByte(ordinal);
}
public override long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length)
{
return _sourceData[_currentRow].GetBytes(ordinal, dataOffset, buffer, bufferOffset, length);
}
public override char GetChar(int ordinal)
{
return _sourceData[_currentRow].GetChar(ordinal);
}
public override long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length)
{
return _sourceData[_currentRow].GetChars(ordinal, dataOffset, buffer, bufferOffset, length);
}
public override DateTime GetDateTime(int ordinal)
{
return _sourceData[_currentRow].GetDateTime(ordinal);
}
public override decimal GetDecimal(int ordinal)
{
// DataRecord may have illegal values for Decimal...
decimal result;
try
{
result = _sourceData[_currentRow].GetDecimal(ordinal);
}
catch (OverflowException)
{
result = (decimal)1;
}
return result;
}
public override double GetDouble(int ordinal)
{
return _sourceData[_currentRow].GetDouble(ordinal);
}
public override float GetFloat(int ordinal)
{
return _sourceData[_currentRow].GetFloat(ordinal);
}
public override Guid GetGuid(int ordinal)
{
return _sourceData[_currentRow].GetGuid(ordinal);
}
public override short GetInt16(int ordinal)
{
return _sourceData[_currentRow].GetInt16(ordinal);
}
public override int GetInt32(int ordinal)
{
return _sourceData[_currentRow].GetInt32(ordinal);
}
public override long GetInt64(int ordinal)
{
return _sourceData[_currentRow].GetInt64(ordinal);
}
public override string GetString(int ordinal)
{
return _sourceData[_currentRow].GetString(ordinal);
}
public override object GetValue(int ordinal)
{
return _sourceData[_currentRow].GetValue(ordinal);
}
public override int GetValues(object[] values)
{
return _sourceData[_currentRow].GetValues(values);
}
public override bool IsDBNull(int ordinal)
{
return _sourceData[_currentRow].IsDBNull(ordinal);
}
public override bool NextResult()
{
Close();
return false;
}
public override bool Read()
{
_currentRow++;
return _currentRow < _sourceData.Count;
}
}
internal class WraparoundRowEnumerator : IEnumerable<SqlDataRecord>, IEnumerator<SqlDataRecord>
{
private int _count;
private int _maxCount;
private SqlDataRecord _record;
public WraparoundRowEnumerator(int maxCount)
{
_maxCount = maxCount;
_record = new SqlDataRecord(new SqlMetaData("someData", SqlDbType.VarBinary, 8000));
// 56 31 0 0 is result of calling BitConverter.GetBytes((int)7992)
// The rest of the bytes are just padding to get 56, 31, 0, 0 to be in bytes 8-11 of TdsParserStatObject._outBuff after the 256th packet
_record.SetBytes(
0,
0,
new byte[] { 1, 2, 56, 31, 0, 0, 7, 8, 9, 10, 11, 12, 13, 14 },
0,
14);
// change any of the 56 31 0 0 bytes and this program completes as expected in a couple seconds
}
public bool MoveNext()
{
_count++;
return _count < _maxCount;
}
public SqlDataRecord Current => _record;
object IEnumerator.Current => Current;
public int Count { get => this._count; set => this._count = value; }
public int MaxCount { get => this._maxCount; set => this._maxCount = value; }
public IEnumerator<SqlDataRecord> GetEnumerator() => this;
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public void Dispose() { }
public void Reset() { }
}
}
| |
/*
Copyright (c) 2012 - 2015 Antmicro <www.antmicro.com>
Authors:
* Konrad Kruczynski (kkruczynski@antmicro.com)
* Piotr Zierhoffer (pzierhoffer@antmicro.com)
* Mateusz Holenko (mholenko@antmicro.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.Reflection.Emit;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using Antmicro.Migrant.Hooks;
using System.Linq;
using Antmicro.Migrant.VersionTolerance;
using Antmicro.Migrant.Utilities;
namespace Antmicro.Migrant.Generators
{
internal class WriteMethodGenerator
{
internal WriteMethodGenerator(Type typeToGenerate, bool treatCollectionAsUserObject, int surrogateId, FieldInfo surrogatesField, MethodInfo writeObjectMethod)
{
typeWeAreGeneratingFor = typeToGenerate;
ObjectWriter.CheckLegality(typeToGenerate);
InitializeMethodInfos();
if(!typeToGenerate.IsArray)
{
dynamicMethod = new DynamicMethod(string.Format("Write_{0}", typeToGenerate.Name), MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard,
typeof(void), ParameterTypes, typeToGenerate, true);
}
else
{
var methodNo = Interlocked.Increment(ref WriteArrayMethodCounter);
dynamicMethod = new DynamicMethod(string.Format("WriteArray{0}_{1}", methodNo, typeToGenerate.Name), null, ParameterTypes, true);
}
generator = dynamicMethod.GetILGenerator();
// surrogates
if(surrogateId != -1)
{
generator.Emit(OpCodes.Ldarg_0); // used (1)
// obtain surrogate factory
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Ldfld, surrogatesField);
generator.Emit(OpCodes.Ldc_I4, surrogateId);
generator.Emit(OpCodes.Call, Helpers.GetMethodInfo<InheritanceAwareList<Delegate>>(x => x.GetByIndex(0)));
// call surrogate factory to obtain surrogate object
var delegateType = typeof(Func<,>).MakeGenericType(typeToGenerate, typeof(object));
generator.Emit(OpCodes.Castclass, delegateType);
generator.Emit(OpCodes.Ldarg_2);
generator.Emit(OpCodes.Call, delegateType.GetMethod("Invoke"));
// jump to surrogate serialization
generator.Emit(OpCodes.Call, writeObjectMethod); // (1) here
generator.Emit(OpCodes.Ret);
return;
}
var delegateTouchAndWriteTypeId = Helpers.GetMethodInfo<ObjectWriter, Type>((writer, type) => writer.TouchAndWriteTypeId(type));
generator.Emit(OpCodes.Ldarg_0); // objectWriter
generator.Emit(OpCodes.Ldarg_2);
generator.Emit(OpCodes.Call, Helpers.GetMethodInfo<object>(o => o.GetType()));
generator.Emit(OpCodes.Call, delegateTouchAndWriteTypeId);
generator.Emit(OpCodes.Pop);
// preserialization callbacks
GenerateInvokeCallback(typeToGenerate, typeof(PreSerializationAttribute));
var exceptionBlockNeeded = Helpers.GetMethodsWithAttribute(typeof(PostSerializationAttribute), typeToGenerate).Any() ||
Helpers.GetMethodsWithAttribute(typeof(LatePostSerializationAttribute), typeToGenerate).Any();
if(exceptionBlockNeeded)
{
generator.BeginExceptionBlock();
}
if(!GenerateSpecialWrite(typeToGenerate, treatCollectionAsUserObject))
{
GenerateWriteFields(gen =>
{
gen.Emit(OpCodes.Ldarg_2);
}, typeToGenerate);
}
if(exceptionBlockNeeded)
{
generator.BeginFinallyBlock();
}
// postserialization callbacks
GenerateInvokeCallback(typeToGenerate, typeof(PostSerializationAttribute));
GenerateAddCallbackToInvokeList(typeToGenerate, typeof(LatePostSerializationAttribute));
if(exceptionBlockNeeded)
{
generator.EndExceptionBlock();
}
generator.Emit(OpCodes.Ret);
}
internal DynamicMethod Method
{
get
{
return dynamicMethod;
}
}
private void InitializeMethodInfos()
{
primitiveWriterWriteInteger = Helpers.GetMethodInfo<PrimitiveWriter>(writer => writer.Write(0));
primitiveWriterWriteBoolean = Helpers.GetMethodInfo<PrimitiveWriter>(writer => writer.Write(false));
}
private void GenerateInvokeCallback(Type actualType, Type attributeType)
{
var methodsWithAttribute = Helpers.GetMethodsWithAttribute(attributeType, actualType);
foreach(var method in methodsWithAttribute)
{
if(!method.IsStatic)
{
generator.Emit(OpCodes.Ldarg_2); // object to serialize
}
if(method.IsVirtual)
{
generator.Emit(OpCodes.Callvirt, method);
}
else
{
generator.Emit(OpCodes.Call, method);
}
}
}
private void GenerateAddCallbackToInvokeList(Type actualType, Type attributeType)
{
var actionCtor = typeof(Action).GetConstructor(new [] { typeof(object), typeof(IntPtr) });
var stackPush = Helpers.GetMethodInfo<List<Action>>(x => x.Add(null));
var methodsWithAttribute = Helpers.GetMethodsWithAttribute(attributeType, actualType).ToList();
var count = methodsWithAttribute.Count;
if(count > 0)
{
generator.Emit(OpCodes.Ldarg_0); // objectWriter
generator.Emit(OpCodes.Ldfld, typeof(ObjectWriter).GetField("postSerializationHooks", BindingFlags.NonPublic | BindingFlags.Instance)); // invoke list
}
for(var i = 1; i < count; i++)
{
generator.Emit(OpCodes.Dup);
}
foreach(var method in methodsWithAttribute)
{
// let's make the delegate
if(method.IsStatic)
{
generator.Emit(OpCodes.Ldnull);
}
else
{
generator.Emit(OpCodes.Ldarg_2); // serialized object
}
generator.Emit(OpCodes.Ldftn, method);
generator.Emit(OpCodes.Newobj, actionCtor);
// and add it to invoke list
generator.Emit(OpCodes.Call, stackPush);
}
}
private void GenerateWriteFields(Action<ILGenerator> putValueToWriteOnTop, Type actualType)
{
var fields = StampHelpers.GetFieldsInSerializationOrder(actualType);
foreach(var field in fields)
{
GenerateWriteType(gen =>
{
putValueToWriteOnTop(gen);
gen.Emit(OpCodes.Ldfld, field);
}, field.FieldType);
}
}
private bool GenerateSpecialWrite(Type actualType, bool treatCollectionAsUserObject)
{
if(actualType.IsValueType)
{
// value type encountered here means it is in fact boxed value type
// according to protocol it is written as it would be written inlined
GenerateWriteValue(gen =>
{
gen.Emit(OpCodes.Ldarg_2); // value to serialize
gen.Emit(OpCodes.Unbox_Any, actualType);
}, actualType);
return true;
}
if(actualType.IsArray)
{
GenerateWriteArray(actualType);
return true;
}
if(typeof(MulticastDelegate).IsAssignableFrom(actualType))
{
GenerateWriteDelegate(gen =>
{
gen.Emit(OpCodes.Ldarg_2); // value to serialize
});
return true;
}
if(!treatCollectionAsUserObject)
{
CollectionMetaToken collectionToken;
if(CollectionMetaToken.TryGetCollectionMetaToken(actualType, out collectionToken))
{
GenerateWriteCollection(collectionToken);
return true;
}
}
return false;
}
private void GenerateWriteArray(Type actualType)
{
var elementType = actualType.GetElementType();
var rank = actualType.GetArrayRank();
if(rank != 1)
{
GenerateWriteMultidimensionalArray(actualType, elementType);
return;
}
generator.DeclareLocal(typeof(int)); // this is for counter
generator.DeclareLocal(elementType); // this is for the current element
generator.DeclareLocal(typeof(int)); // length of the array
// writing rank
generator.Emit(OpCodes.Ldarg_1); // primitiveWriter
generator.Emit(OpCodes.Ldc_I4_1);
generator.Emit(OpCodes.Call, primitiveWriterWriteInteger);
// writing length
generator.Emit(OpCodes.Ldarg_1); // primitiveWriter
generator.Emit(OpCodes.Ldarg_2); // array to serialize
generator.Emit(OpCodes.Castclass, actualType);
generator.Emit(OpCodes.Ldlen);
generator.Emit(OpCodes.Dup);
generator.Emit(OpCodes.Stloc_2);
generator.Emit(OpCodes.Call, primitiveWriterWriteInteger);
var loopEnd = generator.DefineLabel();
var loopBegin = generator.DefineLabel();
// writing elements
generator.Emit(OpCodes.Ldc_I4_0);
generator.Emit(OpCodes.Stloc_0);
generator.MarkLabel(loopBegin);
generator.Emit(OpCodes.Ldloc_0);
generator.Emit(OpCodes.Ldloc_2); // length of the array
generator.Emit(OpCodes.Bge, loopEnd);
generator.Emit(OpCodes.Ldarg_2); // array to serialize
generator.Emit(OpCodes.Castclass, actualType);
generator.Emit(OpCodes.Ldloc_0); // index
generator.Emit(OpCodes.Ldelem, elementType);
generator.Emit(OpCodes.Stloc_1); // we put current element to local variable
GenerateWriteType(gen =>
{
gen.Emit(OpCodes.Ldloc_1); // current element
}, elementType);
// loop book keeping
generator.Emit(OpCodes.Ldloc_0); // current index, which will be increased by 1
generator.Emit(OpCodes.Ldc_I4_1);
generator.Emit(OpCodes.Add);
generator.Emit(OpCodes.Stloc_0);
generator.Emit(OpCodes.Br, loopBegin);
generator.MarkLabel(loopEnd);
}
private void GenerateWriteMultidimensionalArray(Type actualType, Type elementType)
{
var rank = actualType.GetArrayRank();
// local for current element
generator.DeclareLocal(elementType);
// locals for indices
var indexLocals = new int[rank];
for(var i = 0; i < rank; i++)
{
indexLocals[i] = generator.DeclareLocal(typeof(int)).LocalIndex;
}
// locals for lengths
var lengthLocals = new int[rank];
for(var i = 0; i < rank; i++)
{
lengthLocals[i] = generator.DeclareLocal(typeof(int)).LocalIndex;
}
// writing rank
generator.Emit(OpCodes.Ldarg_1); // primitiveWriter
generator.Emit(OpCodes.Ldc_I4, rank);
generator.Emit(OpCodes.Call, primitiveWriterWriteInteger);
// writing lengths
for(var i = 0; i < rank; i++)
{
generator.Emit(OpCodes.Ldarg_1); // primitiveWriter
generator.Emit(OpCodes.Ldarg_2); // array to serialize
generator.Emit(OpCodes.Castclass, actualType);
generator.Emit(OpCodes.Ldc_I4, i);
generator.Emit(OpCodes.Call, Helpers.GetMethodInfo<Array>(array => array.GetLength(0)));
generator.Emit(OpCodes.Dup);
generator.Emit(OpCodes.Stloc, lengthLocals[i]);
generator.Emit(OpCodes.Call, primitiveWriterWriteInteger);
}
// writing elements
GenerateArrayWriteLoop(0, rank, indexLocals, lengthLocals, actualType, elementType);
}
private void GenerateArrayWriteLoop(int currentDimension, int rank, int[] indexLocals, int[] lengthLocals, Type arrayType, Type elementType)
{
var arrayWrittenLabel = generator.DefineLabel();
// check all the lengths and return if at least one is zero
for(var i = 0; i < rank; i++)
{
generator.Emit(OpCodes.Ldloc, lengthLocals[i]);
generator.Emit(OpCodes.Brfalse, arrayWrittenLabel);
}
// initalization
generator.Emit(OpCodes.Ldc_I4_0);
generator.Emit(OpCodes.Stloc, indexLocals[currentDimension]);
var loopBegin = generator.DefineLabel();
generator.MarkLabel(loopBegin);
if(currentDimension == rank - 1)
{
// writing the element
generator.Emit(OpCodes.Ldarg_2); // array to serialize
generator.Emit(OpCodes.Castclass, arrayType);
for(var i = 0; i < rank; i++)
{
generator.Emit(OpCodes.Ldloc, indexLocals[i]);
}
generator.Emit(OpCodes.Call, arrayType.GetMethod("Get"));
generator.Emit(OpCodes.Stloc_0);
GenerateWriteType(gen => gen.Emit(OpCodes.Ldloc_0), elementType);
}
else
{
GenerateArrayWriteLoop(currentDimension + 1, rank, indexLocals, lengthLocals, arrayType, elementType);
}
// incremeting index and loop exit condition check
generator.Emit(OpCodes.Ldloc, indexLocals[currentDimension]);
generator.Emit(OpCodes.Ldc_I4_1);
generator.Emit(OpCodes.Add);
generator.Emit(OpCodes.Dup);
generator.Emit(OpCodes.Stloc, indexLocals[currentDimension]);
generator.Emit(OpCodes.Ldloc, lengthLocals[currentDimension]);
generator.Emit(OpCodes.Blt, loopBegin);
generator.MarkLabel(arrayWrittenLabel);
}
private void GenerateWriteCollection(CollectionMetaToken token)
{
Type enumerableType;
Type enumeratorType;
if(token.IsDictionary)
{
enumerableType = typeof(IDictionary);
enumeratorType = typeof(IDictionaryEnumerator);
}
else
{
var genericTypes = new [] { token.FormalElementType };
enumerableType = token.IsGenericallyIterable ? typeof(IEnumerable<>).MakeGenericType(genericTypes) : typeof(IEnumerable);
enumeratorType = token.IsGenericallyIterable ? typeof(IEnumerator<>).MakeGenericType(genericTypes) : typeof(IEnumerator);
}
generator.DeclareLocal(enumeratorType); // iterator
if(token.IsDictionary)
{
generator.DeclareLocal(token.FormalKeyType);
generator.DeclareLocal(token.FormalValueType);
}
else
{
generator.DeclareLocal(token.FormalElementType);
}
// length of the collection
generator.Emit(OpCodes.Ldarg_1); // primitiveWriter
generator.Emit(OpCodes.Ldarg_2); // collection to serialize
if(token.CountMethod.IsStatic)
{
generator.Emit(OpCodes.Call, token.CountMethod);
}
else
{
generator.Emit(OpCodes.Callvirt, token.CountMethod);
}
generator.Emit(OpCodes.Call, primitiveWriterWriteInteger);
// elements
var getEnumeratorMethod = enumerableType.GetMethod("GetEnumerator");
generator.Emit(OpCodes.Ldarg_2); // collection to serialize
generator.Emit(OpCodes.Call, getEnumeratorMethod);
generator.Emit(OpCodes.Stloc_0);
var loopBegin = generator.DefineLabel();
generator.MarkLabel(loopBegin);
generator.Emit(OpCodes.Ldloc_0);
var finish = generator.DefineLabel();
generator.Emit(OpCodes.Call, Helpers.GetMethodInfo<IEnumerator>(x => x.MoveNext()));
generator.Emit(OpCodes.Brfalse, finish);
generator.Emit(OpCodes.Ldloc_0);
if(token.IsDictionary)
{
// key
generator.Emit(OpCodes.Nop);
generator.Emit(OpCodes.Call, enumeratorType.GetProperty("Key").GetGetMethod());
generator.Emit(OpCodes.Unbox_Any, token.FormalKeyType);
generator.Emit(OpCodes.Stloc_1);
GenerateWriteType(gen => gen.Emit(OpCodes.Ldloc_1), token.FormalKeyType);
// value
generator.Emit(OpCodes.Ldloc_0);
generator.Emit(OpCodes.Call, enumeratorType.GetProperty("Value").GetGetMethod());
generator.Emit(OpCodes.Unbox_Any, token.FormalValueType);
generator.Emit(OpCodes.Stloc_2);
GenerateWriteType(gen => gen.Emit(OpCodes.Ldloc_2), token.FormalValueType);
}
else
{
generator.Emit(OpCodes.Call, enumeratorType.GetProperty("Current").GetGetMethod());
generator.Emit(OpCodes.Stloc_1);
// operation on current element
GenerateWriteTypeLocal1(token.FormalElementType);
}
generator.Emit(OpCodes.Br, loopBegin);
generator.MarkLabel(finish);
}
private void GenerateWriteTypeLocal1(Type formalElementType)
{
GenerateWriteType(gen =>
{
gen.Emit(OpCodes.Ldloc_1);
}, formalElementType);
}
private void GenerateWriteType(Action<ILGenerator> putValueToWriteOnTop, Type formalType)
{
switch(Helpers.GetSerializationType(formalType))
{
case SerializationType.Transient:
// just omit it
return;
case SerializationType.Value:
GenerateWriteValue(putValueToWriteOnTop, formalType);
break;
case SerializationType.Reference:
GenerateWriteReference(putValueToWriteOnTop, formalType);
break;
}
}
private void GenerateWriteDelegate(Action<ILGenerator> putValueToWriteOnTop)
{
var delegateTouchAndWriteMethodId = Helpers.GetMethodInfo<ObjectWriter, MethodInfo>((writer, method) => writer.TouchAndWriteMethodId(method));
var delegateGetInvocationList = Helpers.GetMethodInfo<ObjectWriter, MulticastDelegate>((writer, md) => writer.GetDelegatesWithNonTransientTargets(md));
var delegateGetMethodInfo = typeof(MulticastDelegate).GetProperty("Method").GetGetMethod();
var delegateGetTarget = typeof(MulticastDelegate).GetProperty("Target").GetGetMethod();
var array = generator.DeclareLocal(typeof(Delegate[]));
var loopLength = generator.DeclareLocal(typeof(int));
var element = generator.DeclareLocal(typeof(Delegate));
generator.Emit(OpCodes.Ldarg_1); // primitiveWriter
generator.Emit(OpCodes.Ldarg_0); // objectWriter
putValueToWriteOnTop(generator); // delegate to serialize of type MulticastDelegate
generator.Emit(OpCodes.Call, delegateGetInvocationList);
generator.Emit(OpCodes.Castclass, typeof(Delegate[]));
generator.Emit(OpCodes.Dup);
generator.Emit(OpCodes.Stloc_S, array.LocalIndex);
generator.Emit(OpCodes.Ldlen);
generator.Emit(OpCodes.Dup);
generator.Emit(OpCodes.Stloc_S, loopLength.LocalIndex);
generator.Emit(OpCodes.Call, primitiveWriterWriteInteger);
GeneratorHelper.GenerateLoop(generator, loopLength, c =>
{
generator.Emit(OpCodes.Ldloc, array);
generator.Emit(OpCodes.Ldloc, c);
generator.Emit(OpCodes.Ldelem, element.LocalType);
generator.Emit(OpCodes.Stloc, element);
GenerateWriteReference(gen =>
{
gen.Emit(OpCodes.Ldloc, element);
gen.Emit(OpCodes.Call, delegateGetTarget);
}, typeof(object));
generator.Emit(OpCodes.Ldarg_0); // objectWriter
generator.Emit(OpCodes.Ldloc, element);
generator.Emit(OpCodes.Call, delegateGetMethodInfo);
generator.Emit(OpCodes.Call, delegateTouchAndWriteMethodId);
generator.Emit(OpCodes.Pop);
});
}
private void GenerateWriteValue(Action<ILGenerator> putValueToWriteOnTop, Type formalType)
{
ObjectWriter.CheckLegality(formalType, typeWeAreGeneratingFor);
if(formalType.IsEnum)
{
formalType = Enum.GetUnderlyingType(formalType);
}
var writeMethod = typeof(PrimitiveWriter).GetMethod("Write", new [] { formalType });
// if this method is null, then it is a non-primitive (i.e. custom) struct
if(writeMethod != null)
{
generator.Emit(OpCodes.Ldarg_1); // primitive writer waits there
putValueToWriteOnTop(generator);
generator.Emit(OpCodes.Call, writeMethod);
return;
}
var nullableUnderlyingType = Nullable.GetUnderlyingType(formalType);
if(nullableUnderlyingType != null)
{
var hasValue = generator.DefineLabel();
var finish = generator.DefineLabel();
var localIndex = generator.DeclareLocal(formalType).LocalIndex;
generator.Emit(OpCodes.Ldarg_1); // primitiveWriter
putValueToWriteOnTop(generator);
generator.Emit(OpCodes.Stloc_S, localIndex);
generator.Emit(OpCodes.Ldloca_S, localIndex);
generator.Emit(OpCodes.Call, formalType.GetProperty("HasValue").GetGetMethod());
generator.Emit(OpCodes.Brtrue_S, hasValue);
generator.Emit(OpCodes.Ldc_I4_0);
generator.Emit(OpCodes.Call, primitiveWriterWriteBoolean);
generator.Emit(OpCodes.Br, finish);
generator.MarkLabel(hasValue);
generator.Emit(OpCodes.Ldc_I4_1);
generator.Emit(OpCodes.Call, primitiveWriterWriteBoolean);
GenerateWriteValue(gen =>
{
generator.Emit(OpCodes.Ldloca_S, localIndex);
generator.Emit(OpCodes.Call, formalType.GetProperty("Value").GetGetMethod());
}, nullableUnderlyingType);
generator.MarkLabel(finish);
return;
}
if(formalType.IsGenericType && formalType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>))
{
var keyValueTypes = formalType.GetGenericArguments();
var localIndex = generator.DeclareLocal(formalType).LocalIndex;
GenerateWriteType(gen =>
{
putValueToWriteOnTop(gen);
// TODO: is there a better method of getting address?
// don't think so, looking at
// http://stackoverflow.com/questions/76274/
// we *may* do a little optimization if this value write takes
// place when dictionary is serialized (current KVP is stored in
// local 1 in such situation); the KVP may be, however, written
// independently
gen.Emit(OpCodes.Stloc_S, localIndex);
gen.Emit(OpCodes.Ldloca_S, localIndex);
gen.Emit(OpCodes.Call, formalType.GetProperty("Key").GetGetMethod());
}, keyValueTypes[0]);
GenerateWriteType(gen =>
{
// we assume here that the key write was invoked earlier (it should be
// if we're conforming to the protocol), so KeyValuePair is already
// stored as local
gen.Emit(OpCodes.Ldloca_S, localIndex);
gen.Emit(OpCodes.Call, formalType.GetProperty("Value").GetGetMethod());
}, keyValueTypes[1]);
}
else
{
GenerateWriteFields(putValueToWriteOnTop, formalType);
}
}
private void GenerateWriteReference(Action<ILGenerator> putValueToWriteOnTop, Type formalType)
{
var finish = generator.DefineLabel();
putValueToWriteOnTop(generator);
var isNotNull = generator.DefineLabel();
generator.Emit(OpCodes.Brtrue_S, isNotNull);
generator.Emit(OpCodes.Ldarg_1); // primitiveWriter
generator.Emit(OpCodes.Ldc_I4, Consts.NullObjectId);
generator.Emit(OpCodes.Call, primitiveWriterWriteInteger);
generator.Emit(OpCodes.Br, finish);
generator.MarkLabel(isNotNull);
var formalTypeIsActualType = (formalType.Attributes & TypeAttributes.Sealed) != 0;
if(!formalTypeIsActualType)
{
generator.Emit(OpCodes.Ldarg_0); // objectWriter
putValueToWriteOnTop(generator); // value to serialize
generator.Emit(OpCodes.Call, Helpers.GetMethodInfo<ObjectWriter, object>((writer, obj) => writer.CheckTransient(obj)));
var isNotTransient = generator.DefineLabel();
generator.Emit(OpCodes.Brfalse_S, isNotTransient);
generator.Emit(OpCodes.Ldarg_1); // primitiveWriter
generator.Emit(OpCodes.Ldc_I4, Consts.NullObjectId);
generator.Emit(OpCodes.Call, primitiveWriterWriteInteger);
generator.Emit(OpCodes.Br, finish);
generator.MarkLabel(isNotTransient);
generator.Emit(OpCodes.Ldarg_0); // objectWriter
putValueToWriteOnTop(generator);
generator.Emit(OpCodes.Call, Helpers.GetMethodInfo<ObjectWriter>(writer => writer.WriteObjectIdPossiblyInline(null)));
}
else
{
if(Helpers.CheckTransientNoCache(formalType))
{
generator.Emit(OpCodes.Ldarg_1); // primitiveWriter
generator.Emit(OpCodes.Ldc_I4, Consts.NullObjectId);
generator.Emit(OpCodes.Call, primitiveWriterWriteInteger);
}
else
{
generator.Emit(OpCodes.Ldarg_0); // objectWriter
putValueToWriteOnTop(generator);
generator.Emit(OpCodes.Call, Helpers.GetMethodInfo<ObjectWriter>(writer => writer.WriteObjectIdPossiblyInline(null)));
}
}
generator.MarkLabel(finish);
}
private MethodInfo primitiveWriterWriteInteger;
private MethodInfo primitiveWriterWriteBoolean;
private readonly ILGenerator generator;
private readonly DynamicMethod dynamicMethod;
private readonly Type typeWeAreGeneratingFor;
private static int WriteArrayMethodCounter;
private static readonly Type[] ParameterTypes = new [] {
typeof(ObjectWriter),
typeof(PrimitiveWriter),
typeof(object)
};
}
}
| |
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Octokit.Internal;
using Xunit;
namespace Octokit.Tests.Http
{
public class RedirectHandlerTests
{
[Fact]
public async Task OkStatusShouldPassThrough()
{
var handler = CreateMockHttpHandler(new HttpResponseMessage(HttpStatusCode.OK));
var adapter = new HttpClientAdapter(handler);
var httpRequestMessage = CreateRequest(HttpMethod.Get);
var response = await adapter.SendAsync(httpRequestMessage, new CancellationToken());
Assert.Equal(response.StatusCode, HttpStatusCode.OK);
Assert.Same(response.RequestMessage, httpRequestMessage);
}
[Theory]
[InlineData(HttpStatusCode.MovedPermanently)] // 301
[InlineData(HttpStatusCode.Found)] // 302
[InlineData(HttpStatusCode.TemporaryRedirect)] // 307
public async Task ShouldRedirectSameMethod(HttpStatusCode statusCode)
{
var redirectResponse = new HttpResponseMessage(statusCode);
redirectResponse.Headers.Location = new Uri("http://example.org/bar");
var handler = CreateMockHttpHandler(redirectResponse, new HttpResponseMessage(HttpStatusCode.OK));
var adapter = new HttpClientAdapter(handler);
var httpRequestMessage = CreateRequest(HttpMethod.Post);
var response = await adapter.SendAsync(httpRequestMessage, new CancellationToken());
Assert.Equal(response.RequestMessage.Method, httpRequestMessage.Method);
Assert.NotSame(response.RequestMessage, httpRequestMessage);
}
[Fact]
public async Task Status303ShouldRedirectChangeMethod()
{
var redirectResponse = new HttpResponseMessage(HttpStatusCode.SeeOther);
redirectResponse.Headers.Location = new Uri("http://example.org/bar");
var handler = CreateMockHttpHandler(redirectResponse, new HttpResponseMessage(HttpStatusCode.OK));
var adapter = new HttpClientAdapter(handler);
var httpRequestMessage = CreateRequest(HttpMethod.Post);
var response = await adapter.SendAsync(httpRequestMessage, new CancellationToken());
Assert.Equal(HttpMethod.Get, response.RequestMessage.Method);
Assert.NotSame(response.RequestMessage, httpRequestMessage);
}
[Fact]
public async Task RedirectWithSameHostShouldKeepAuthHeader()
{
var redirectResponse = new HttpResponseMessage(HttpStatusCode.Redirect);
redirectResponse.Headers.Location = new Uri("http://example.org/bar");
var handler = CreateMockHttpHandler(redirectResponse, new HttpResponseMessage(HttpStatusCode.OK));
var adapter = new HttpClientAdapter(handler);
var httpRequestMessage = CreateRequest(HttpMethod.Get);
httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue("fooAuth", "aparam");
var response = await adapter.SendAsync(httpRequestMessage, new CancellationToken());
Assert.NotSame(response.RequestMessage, httpRequestMessage);
Assert.Equal("fooAuth", response.RequestMessage.Headers.Authorization.Scheme);
}
[Theory]
[InlineData(HttpStatusCode.MovedPermanently)] // 301
[InlineData(HttpStatusCode.Found)] // 302
[InlineData(HttpStatusCode.SeeOther)] // 303
[InlineData(HttpStatusCode.TemporaryRedirect)] // 307
public async Task RedirectWithDifferentHostShouldLoseAuthHeader(HttpStatusCode statusCode)
{
var redirectResponse = new HttpResponseMessage(statusCode);
redirectResponse.Headers.Location = new Uri("http://example.net/bar");
var handler = CreateMockHttpHandler(redirectResponse, new HttpResponseMessage(HttpStatusCode.OK));
var adapter = new HttpClientAdapter(handler);
var httpRequestMessage = CreateRequest(HttpMethod.Get);
httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue("fooAuth", "aparam");
var response = await adapter.SendAsync(httpRequestMessage, new CancellationToken());
Assert.NotSame(response.RequestMessage, httpRequestMessage);
Assert.Null(response.RequestMessage.Headers.Authorization);
}
[Theory]
[InlineData(HttpStatusCode.MovedPermanently)] // 301
[InlineData(HttpStatusCode.Found)] // 302
[InlineData(HttpStatusCode.TemporaryRedirect)] // 307
public async Task Status301ShouldRedirectPOSTWithBody(HttpStatusCode statusCode)
{
var redirectResponse = new HttpResponseMessage(statusCode);
redirectResponse.Headers.Location = new Uri("http://example.org/bar");
var handler = CreateMockHttpHandler(redirectResponse, new HttpResponseMessage(HttpStatusCode.OK));
var adapter = new HttpClientAdapter(handler);
var httpRequestMessage = CreateRequest(HttpMethod.Post);
httpRequestMessage.Content = new StringContent("Hello World");
var response = await adapter.SendAsync(httpRequestMessage, new CancellationToken());
Assert.Equal(response.RequestMessage.Method, httpRequestMessage.Method);
Assert.NotSame(response.RequestMessage, httpRequestMessage);
}
// POST see other with content
[Fact]
public async Task Status303ShouldRedirectToGETWithoutBody()
{
var redirectResponse = new HttpResponseMessage(HttpStatusCode.SeeOther);
redirectResponse.Headers.Location = new Uri("http://example.org/bar");
var handler = CreateMockHttpHandler(redirectResponse, new HttpResponseMessage(HttpStatusCode.OK));
var adapter = new HttpClientAdapter(handler);
var httpRequestMessage = CreateRequest(HttpMethod.Post);
httpRequestMessage.Content = new StringContent("Hello World");
var response = await adapter.SendAsync(httpRequestMessage, new CancellationToken());
Assert.Equal(HttpMethod.Get, response.RequestMessage.Method);
Assert.NotSame(response.RequestMessage, httpRequestMessage);
Assert.Null(response.RequestMessage.Content);
}
[Fact]
public async Task Exceed3RedirectsShouldReturn()
{
var redirectResponse = new HttpResponseMessage(HttpStatusCode.Found);
redirectResponse.Headers.Location = new Uri("http://example.org/bar");
var redirectResponse2 = new HttpResponseMessage(HttpStatusCode.Found);
redirectResponse2.Headers.Location = new Uri("http://example.org/foo");
var handler = CreateMockHttpHandler(redirectResponse, redirectResponse2);
var adapter = new HttpClientAdapter(handler);
var httpRequestMessage = CreateRequest(HttpMethod.Get);
Assert.ThrowsAsync<InvalidOperationException>(
() => adapter.SendAsync(httpRequestMessage, new CancellationToken()));
}
static HttpRequestMessage CreateRequest(HttpMethod method)
{
var httpRequestMessage = new HttpRequestMessage();
httpRequestMessage.RequestUri = new Uri("http://example.org/foo");
httpRequestMessage.Method = method;
return httpRequestMessage;
}
static Func<HttpMessageHandler> CreateMockHttpHandler(HttpResponseMessage httpResponseMessage1, HttpResponseMessage httpResponseMessage2 = null)
{
return () => new MockRedirectHandler(httpResponseMessage1, httpResponseMessage2);
}
}
public class MockRedirectHandler : HttpMessageHandler
{
readonly HttpResponseMessage _response1;
readonly HttpResponseMessage _response2;
private bool _Response1Sent;
public MockRedirectHandler(HttpResponseMessage response1, HttpResponseMessage response2 = null)
{
_response1 = response1;
_response2 = response2;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (!_Response1Sent)
{
_Response1Sent = true;
_response1.RequestMessage = request;
return _response1;
}
else
{
_response2.RequestMessage = request;
return _response2;
}
}
}
}
| |
/* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using XenAdmin.Actions;
using XenAdmin.Core;
using XenAdmin.Model;
using XenAPI;
namespace XenAdmin.Dialogs.HealthCheck
{
public partial class HealthCheckSettingsDialog : XenDialogBase
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private readonly Pool pool;
private HealthCheckSettings healthCheckSettings;
private bool authenticationRequired;
private bool authenticated;
private string authenticationToken;
private string diagnosticToken;
private string xsUserName;
private string xsPassword;
internal override string HelpName => "HealthCheckSettingsDialog";
public HealthCheckSettingsDialog(Pool pool, bool enrollNow)
:base(pool.Connection)
{
this.pool = pool;
healthCheckSettings = pool.HealthCheckSettings();
if (enrollNow)
healthCheckSettings.Status = HealthCheckStatus.Enabled;
authenticated = healthCheckSettings.TryGetExistingTokens(pool.Connection, out authenticationToken, out diagnosticToken);
authenticationRequired = !authenticated;
xsUserName = healthCheckSettings.GetSecretInfo(pool.Connection, HealthCheckSettings.UPLOAD_CREDENTIAL_USER_SECRET);
xsPassword = healthCheckSettings.GetSecretInfo(pool.Connection, HealthCheckSettings.UPLOAD_CREDENTIAL_PASSWORD_SECRET);
InitializeComponent();
rubricLabel.Text = string.Format(rubricLabel.Text, BrandManager.Cis, BrandManager.ProductBrand);
label3.Text = string.Format(label3.Text, BrandManager.ProductBrand);
decentGroupBox1.Text = string.Format(decentGroupBox1.Text, BrandManager.Cis);
decentGroupBoxXSCredentials.Text = string.Format(decentGroupBoxXSCredentials.Text, BrandManager.ProductBrand);
currentXsCredentialsRadioButton.Text = string.Format(currentXsCredentialsRadioButton.Text, BrandManager.BrandConsole);
PopulateControls();
InitializeControls();
UpdateButtons();
}
private void PopulateControls()
{
var list = BuildDays();
var ds = new BindingSource(list, null);
dayOfWeekComboBox.DataSource = ds;
dayOfWeekComboBox.ValueMember = "key";
dayOfWeekComboBox.DisplayMember = "value";
var list1 = BuildHours();
var ds1 = new BindingSource(list1, null);
timeOfDayComboBox.DataSource = ds1;
timeOfDayComboBox.ValueMember = "key";
timeOfDayComboBox.DisplayMember = "value";
}
private Dictionary<int, string> BuildDays()
{
Dictionary<int, string> days = new Dictionary<int, string>();
foreach (var dayOfWeek in Enum.GetValues(typeof(DayOfWeek)))
{
days.Add((int)dayOfWeek, HelpersGUI.DayOfWeekToString((DayOfWeek)dayOfWeek, true));
}
return days;
}
private SortedDictionary<int, string> BuildHours()
{
SortedDictionary<int, string> hours = new SortedDictionary<int, string>();
for (int hour = 0; hour <= 23; hour++)
{
DateTime time = new DateTime(1900, 1, 1, hour, 0, 0);
hours.Add(hour, HelpersGUI.DateTimeToString(time, Messages.DATEFORMAT_HM, true));
}
return hours;
}
private void InitializeControls()
{
Text = String.Format(Messages.HEALTHCHECK_ENROLLMENT_TITLE, pool.Name());
tableLayoutPanel5.Visible = false;
if (authenticationRequired)
{
string noAuthTokenMessage = string.Format(Messages.HEALTHCHECK_AUTHENTICATION_RUBRIC_NO_TOKEN,
BrandManager.Cis, Messages.MY_CITRIX_CREDENTIALS_URL);
authRubricLinkLabel.Text = noAuthTokenMessage;
authRubricLinkLabel.LinkArea = new LinkArea(noAuthTokenMessage.IndexOf(Messages.MY_CITRIX_CREDENTIALS_URL),
Messages.MY_CITRIX_CREDENTIALS_URL.Length);
}
else
{
authRubricLinkLabel.Text = string.Format(Messages.HEALTHCHECK_AUTHENTICATION_RUBRIC_EXISTING_TOKEN,
BrandManager.Cis, BrandManager.BrandConsole);
authRubricLinkLabel.LinkArea = new LinkArea(0, 0);
}
enrollmentCheckBox.Checked = healthCheckSettings.Status != HealthCheckStatus.Disabled;
frequencyNumericBox.Value = healthCheckSettings.IntervalInWeeks;
dayOfWeekComboBox.SelectedValue = (int)healthCheckSettings.DayOfWeek;
timeOfDayComboBox.SelectedValue = healthCheckSettings.TimeOfDay;
existingAuthenticationRadioButton.Enabled = existingAuthenticationRadioButton.Checked = !authenticationRequired;
newAuthenticationRadioButton.Checked = authenticationRequired;
SetMyCitrixCredentials(existingAuthenticationRadioButton.Checked);
bool useCurrentXsCredentials = string.IsNullOrEmpty(xsUserName) || xsUserName == pool.Connection.Username;
newXsCredentialsRadioButton.Checked = !useCurrentXsCredentials;
currentXsCredentialsRadioButton.Checked = useCurrentXsCredentials;
SetXSCredentials(currentXsCredentialsRadioButton.Checked);
}
private bool ChangesMade()
{
if (enrollmentCheckBox.Checked && healthCheckSettings.Status != HealthCheckStatus.Enabled)
return true;
if (!enrollmentCheckBox.Checked && healthCheckSettings.Status != HealthCheckStatus.Disabled)
return true;
if (frequencyNumericBox.Value != healthCheckSettings.IntervalInWeeks)
return true;
if (dayOfWeekComboBox.SelectedIndex != (int)healthCheckSettings.DayOfWeek)
return true;
if (timeOfDayComboBox.SelectedIndex != healthCheckSettings.TimeOfDay)
return true;
if (authenticationToken != healthCheckSettings.GetSecretInfo(pool.Connection, HealthCheckSettings.UPLOAD_TOKEN_SECRET))
return true;
if (textboxXSUserName.Text != xsUserName)
return true;
if (textboxXSPassword.Text != xsPassword)
return true;
return false;
}
private void UpdateButtons()
{
okButton.Enabled = CheckCredentialsEntered() && !errorLabel.Visible;
}
private void okButton_Click(object sender, EventArgs e)
{
if (enrollmentCheckBox.Checked && newAuthenticationRadioButton.Checked)
CheckUploadAuthentication();
else
SaveAndClose();
}
private void SaveAndClose()
{
if (ChangesMade())
{
var newHealthCheckSettings = new HealthCheckSettings(pool.health_check_config);
newHealthCheckSettings.Status = enrollmentCheckBox.Checked ? HealthCheckStatus.Enabled : HealthCheckStatus.Disabled;
newHealthCheckSettings.IntervalInDays = (int)(frequencyNumericBox.Value * 7);
newHealthCheckSettings.DayOfWeek = (DayOfWeek)dayOfWeekComboBox.SelectedValue;
newHealthCheckSettings.TimeOfDay = (int)timeOfDayComboBox.SelectedValue;
newHealthCheckSettings. RetryInterval = HealthCheckSettings.DEFAULT_RETRY_INTERVAL;
new SaveHealthCheckSettingsAction(pool, newHealthCheckSettings, authenticationToken, diagnosticToken, textboxXSUserName.Text.Trim(), textboxXSPassword.Text, false).RunAsync();
new TransferHealthCheckSettingsAction(pool, newHealthCheckSettings, textboxXSUserName.Text.Trim(), textboxXSPassword.Text, true).RunAsync();
}
DialogResult = DialogResult.OK;
Close();
}
private void cancelButton_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void enrollmentCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (!enrollmentCheckBox.Checked)
HideTestCredentialsStatus();
UpdateButtons();
}
private void newXsCredentialsRadioButton_CheckedChanged(object sender, EventArgs e)
{
SetXSCredentials(currentXsCredentialsRadioButton.Checked);
testCredentialsButton.Enabled = newXsCredentialsRadioButton.Checked &&
!string.IsNullOrEmpty(textboxXSUserName.Text.Trim()) && !string.IsNullOrEmpty(textboxXSPassword.Text);
UpdateButtons();
}
private void SetXSCredentials(bool useCurrent)
{
if (useCurrent)
{
textboxXSUserName.Text = pool.Connection.Username;
textboxXSPassword.Text = pool.Connection.Password;
textboxXSUserName.Enabled = false;
textboxXSPassword.Enabled = false;
}
else
{
textboxXSUserName.Text = xsUserName;
textboxXSPassword.Text = xsPassword;
textboxXSUserName.Enabled = true;
textboxXSPassword.Enabled = true;
}
}
private void SetMyCitrixCredentials(bool useExisting)
{
if (useExisting)
{
//textBoxMyCitrixUsername.Text = String.Empty;
//textBoxMyCitrixPassword.Text = String.Empty;
textBoxMyCitrixUsername.Enabled = false;
textBoxMyCitrixPassword.Enabled = false;
}
else
{
//textBoxMyCitrixUsername.Text = String.Empty;
//textBoxMyCitrixPassword.Text = String.Empty;
textBoxMyCitrixUsername.Enabled = true;
textBoxMyCitrixPassword.Enabled = true;
}
}
private bool CheckCredentialsEntered()
{
if (!enrollmentCheckBox.Checked)
return true;
if (newAuthenticationRadioButton.Checked &&
(string.IsNullOrEmpty(textBoxMyCitrixUsername.Text.Trim()) || string.IsNullOrEmpty(textBoxMyCitrixPassword.Text)))
return false;
if (newXsCredentialsRadioButton.Checked &&
(string.IsNullOrEmpty(textboxXSUserName.Text.Trim()) || string.IsNullOrEmpty(textboxXSPassword.Text)))
return false;
return true;
}
private void CheckUploadAuthentication()
{
var action = new HealthCheckAuthenticationAction(textBoxMyCitrixUsername.Text.Trim(), textBoxMyCitrixPassword.Text.Trim(),
Registry.HealthCheckIdentityTokenDomainName, Registry.HealthCheckUploadGrantTokenDomainName, Registry.HealthCheckUploadTokenDomainName,
Registry.HealthCheckDiagnosticDomainName, Registry.HealthCheckProductKey, 0, true, true);
action.Completed += action_Completed;
okButton.Enabled = false;
pictureBoxStatus.Image = Images.StaticImages.ajax_loader;
labelStatus.Text = action.Description;
labelStatus.ForeColor = SystemColors.ControlText;
tableLayoutPanel5.Visible = true;
action.RunAsync();
}
private void action_Completed(ActionBase a)
{
Program.Invoke(this, () =>
{
if (!a.Succeeded || !(a is HealthCheckAuthenticationAction action))
{
authenticationToken = null;
authenticated = false;
}
else
{
authenticationToken = action.UploadToken; // current upload token
diagnosticToken = action.DiagnosticToken; // current diagnostic token
authenticated = !string.IsNullOrEmpty(authenticationToken) && !string.IsNullOrEmpty(diagnosticToken);
}
if (!authenticated)
{
pictureBoxStatus.Image = Images.StaticImages._000_error_h32bit_16;
labelStatus.Text = a.Exception != null ? a.Exception.Message : Messages.ERROR_UNKNOWN;
labelStatus.ForeColor = Color.Red;
okButton.Enabled = true;
return;
}
tableLayoutPanel5.Visible = false;
okButton.Enabled = true;
SaveAndClose();
});
}
private void credentials_TextChanged(object sender, EventArgs e)
{
tableLayoutPanel5.Visible = false;
UpdateButtons();
}
private void xsCredentials_TextChanged(object sender, EventArgs e)
{
testCredentialsButton.Enabled = newXsCredentialsRadioButton.Checked &&
!string.IsNullOrEmpty(textboxXSUserName.Text.Trim()) && !string.IsNullOrEmpty(textboxXSPassword.Text);
HideTestCredentialsStatus();
}
private void PolicyStatementLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
new HealthCheckPolicyStatementDialog().ShowDialog(this);
}
private void testCredentialsButton_Click(object sender, EventArgs e)
{
okButton.Enabled = false;
CheckXenServerCredentials();
}
private void CheckXenServerCredentials()
{
if (string.IsNullOrEmpty(textboxXSUserName.Text.Trim()) || string.IsNullOrEmpty(textboxXSPassword.Text))
return;
bool passedRbacChecks = false;
DelegatedAsyncAction action = new DelegatedAsyncAction(connection,
Messages.CREDENTIALS_CHECKING, "", "",
delegate
{
Session elevatedSession = null;
try
{
elevatedSession = connection.ElevatedSession(textboxXSUserName.Text.Trim(), textboxXSPassword.Text);
if (elevatedSession != null && (elevatedSession.IsLocalSuperuser || SessionAuthorized(elevatedSession, Role.ValidRoleList("pool.set_health_check_config", connection))))
passedRbacChecks = true;
}
catch (Failure f)
{
if (f.ErrorDescription.Count > 0 && f.ErrorDescription[0] == Failure.RBAC_PERMISSION_DENIED)
{
// we use a different error message here from the standard one in friendly names
throw new Exception(Messages.HEALTH_CHECK_USER_HAS_NO_PERMISSION_TO_CONNECT);
}
throw;
}
finally
{
if (elevatedSession != null)
{
elevatedSession.Connection.Logout(elevatedSession);
elevatedSession = null;
}
}
},
true);
action.Completed += delegate
{
log.DebugFormat("Logging with the new credentials returned: {0} ", passedRbacChecks);
Program.Invoke(Program.MainWindow, () =>
{
if (passedRbacChecks)
{
ShowTestCredentialsStatus(Images.StaticImages._000_Tick_h32bit_16, null);
okButton.Enabled = true;
}
else
{
okButton.Enabled = false;
ShowTestCredentialsStatus(Images.StaticImages._000_error_h32bit_16, action.Exception != null ? action.Exception.Message : Messages.HEALTH_CHECK_USER_NOT_AUTHORIZED);
}
textboxXSUserName.Enabled = textboxXSPassword.Enabled = testCredentialsButton.Enabled = newXsCredentialsRadioButton.Checked;
});
};
log.Debug("Testing logging in with the new credentials");
ShowTestCredentialsStatus(Images.StaticImages.ajax_loader, null);
textboxXSUserName.Enabled = textboxXSPassword.Enabled = testCredentialsButton.Enabled = false;
action.RunAsync();
}
private void ShowTestCredentialsStatus(Image image, string errorMessage)
{
testCredentialsStatusImage.Visible = true;
testCredentialsStatusImage.Image = image;
errorLabel.Text = errorMessage;
errorLabel.Visible = !string.IsNullOrEmpty(errorMessage);
}
private void HideTestCredentialsStatus()
{
testCredentialsStatusImage.Visible = false;
errorLabel.Visible = false;
}
private bool SessionAuthorized(Session s, List<Role> authorizedRoles)
{
UserDetails ud = s.CurrentUserDetails;
foreach (Role r in s.Roles)
{
if (authorizedRoles.Contains(r))
{
log.DebugFormat("Subject '{0}' is authorized to complete the action", ud.UserName ?? ud.UserSid);
return true;
}
}
log.DebugFormat("Subject '{0}' is not authorized to complete the action", ud.UserName ?? ud.UserSid);
return false;
}
private void newAuthenticationRadioButton_CheckedChanged(object sender, EventArgs e)
{
tableLayoutPanel5.Visible = false;
SetMyCitrixCredentials(existingAuthenticationRadioButton.Checked);
}
private void existingAuthenticationRadioButton_CheckedChanged(object sender, EventArgs e)
{
tableLayoutPanel5.Visible = false;
UpdateButtons();
}
private void authRubricLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Program.OpenURL(Messages.MY_CITRIX_CREDENTIALS_URL);
}
}
}
| |
/* ====================================================================
Copyright (C) 2008 samuelchoi - donated to RDL Project
-- most of the drawing originally came from Viewer
*/
using System;
using Oranikle.Report.Engine;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Text;
using System.Runtime.InteropServices;
namespace Oranikle.Report.Engine
{
///<summary>
/// Renders a report to TIF. This is a page oriented formatting renderer.
///</summary>
public class RenderTif : IPresent
{
Report r; // report
Stream tw; // where the output is going
Bitmap _tif;
float DpiX;
float DpiY;
bool _RenderColor;
public RenderTif(Report rep, IStreamGen sg)
{
r = rep;
tw = sg.GetStream();
_RenderColor = true;
}
/// <summary>
/// Set RenderColor to false if you want to create a fax compatible tiff in black and white
/// </summary>
public bool RenderColor
{
get { return _RenderColor; }
set { _RenderColor = value; }
}
public Report Report()
{
return r;
}
public bool IsPagingNeeded()
{
return true;
}
public void Start()
{
}
public void End()
{
}
public void RunPages(Pages pgs) // this does all the work
{
int pageNo = 1;
// STEP: processing a page.
foreach (Page p in pgs)
{
System.Drawing.Bitmap bm = CreateObjectBitmap();
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bm);
g.PageUnit = GraphicsUnit.Pixel;
g.ScaleTransform(1, 1);
DpiX = g.DpiX;
DpiY = g.DpiY;
// STEP: Fill backgroup
g.FillRectangle(Brushes.White, 0F, 0F, (float)bm.Width, (float)bm.Height);
// STEP: draw page to bitmap
ProcessPage(g, p);
// STEP:
System.Drawing.Bitmap bm2 = ConvertToBitonal(bm);
if (pageNo == 1)
_tif = bm2;
SaveBitmap(_tif, bm2, tw, pageNo);
pageNo++;
}
if (_tif != null)
{
// STEP: prepare encoder parameters
EncoderParameters encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = new EncoderParameter(
System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.Flush
);
// STEP:
_tif.SaveAdd(encoderParams);
}
return;
}
private void ProcessPage(Graphics g, IEnumerable p)
{
foreach (PageItem pi in p)
{
if (pi is PageTextHtml)
{ // PageTextHtml is actually a composite object (just like a page)
ProcessHtml(pi as PageTextHtml, g);
continue;
}
if (pi is PageLine)
{
PageLine pl = pi as PageLine;
DrawLine(
pl.SI.BColorLeft, pl.SI.BStyleLeft, pl.SI.BWidthLeft,
g, PixelsX(pl.X), PixelsY(pl.Y), PixelsX(pl.X2), PixelsY(pl.Y2)
);
continue;
}
RectangleF rect = new RectangleF(PixelsX(pi.X), PixelsY(pi.Y), PixelsX(pi.W), PixelsY(pi.H));
if (pi.SI.BackgroundImage != null)
{ // put out any background image
PageImage i = pi.SI.BackgroundImage;
DrawImage(i, g, rect);
}
if (pi is PageText)
{
PageText pt = pi as PageText;
DrawString(pt, g, rect);
}
else if (pi is PageImage)
{
PageImage i = pi as PageImage;
DrawImage(i, g, rect);
}
else if (pi is PageRectangle)
{
this.DrawBackground(g, rect, pi.SI);
}
else if (pi is PageEllipse)
{
PageEllipse pe = pi as PageEllipse;
DrawEllipse(pe, g, rect);
}
else if (pi is PagePie)
{
PagePie pp = pi as PagePie;
DrawPie(pp, g, rect);
}
else if (pi is PagePolygon)
{
PagePolygon ppo = pi as PagePolygon;
FillPolygon(ppo, g, rect);
}
else if (pi is PageCurve)
{
PageCurve pc = pi as PageCurve;
DrawCurve(pc.SI.BColorLeft, pc.SI.BStyleLeft, pc.SI.BWidthLeft,
g, pc.Points, pc.Offset, pc.Tension);
}
DrawBorder(pi, g, rect);
}
}
private void ProcessHtml(PageTextHtml pth, System.Drawing.Graphics g)
{
pth.Build(g); // Builds the subobjects that make up the html
this.ProcessPage(g, pth);
}
private void DrawLine(Color c, BorderStyleEnum bs, float w, Graphics g, float x, float y, float x2, float y2)
{
if (bs == BorderStyleEnum.None || c.IsEmpty || w <= 0) // nothing to draw
return;
Pen p = null;
try
{
p = new Pen(c, w);
switch (bs)
{
case BorderStyleEnum.Dashed:
p.DashStyle = DashStyle.Dash;
break;
case BorderStyleEnum.Dotted:
p.DashStyle = DashStyle.Dot;
break;
case BorderStyleEnum.Double:
case BorderStyleEnum.Groove:
case BorderStyleEnum.Inset:
case BorderStyleEnum.Solid:
case BorderStyleEnum.Outset:
case BorderStyleEnum.Ridge:
case BorderStyleEnum.WindowInset:
default:
p.DashStyle = DashStyle.Solid;
break;
}
g.DrawLine(p, x, y, x2, y2);
}
finally
{
if (p != null)
p.Dispose();
}
}
private void DrawCurve(Color c, BorderStyleEnum bs, float w, Graphics g,
PointF[] points, int Offset, float Tension)
{
if (bs == BorderStyleEnum.None || c.IsEmpty || w <= 0) // nothing to draw
return;
Pen p = null;
try
{
p = new Pen(c, w);
switch (bs)
{
case BorderStyleEnum.Dashed:
p.DashStyle = DashStyle.Dash;
break;
case BorderStyleEnum.Dotted:
p.DashStyle = DashStyle.Dot;
break;
case BorderStyleEnum.Double:
case BorderStyleEnum.Groove:
case BorderStyleEnum.Inset:
case BorderStyleEnum.Solid:
case BorderStyleEnum.Outset:
case BorderStyleEnum.Ridge:
case BorderStyleEnum.WindowInset:
default:
p.DashStyle = DashStyle.Solid;
break;
}
PointF[] tmp = new PointF[points.Length];
for (int i = 0; i < points.Length; i++)
{
tmp[i].X = PixelsX(points[i].X);
tmp[i].Y = PixelsY(points[i].Y);
}
g.DrawCurve(p, tmp, Offset, tmp.Length - 1, Tension);
}
finally
{
if (p != null)
p.Dispose();
}
}
private void DrawEllipse(PageEllipse pe, Graphics g, RectangleF r)
{
StyleInfo si = pe.SI;
if (!si.BackgroundColor.IsEmpty)
{
g.FillEllipse(new SolidBrush(si.BackgroundColor), r);
}
if (si.BStyleTop != BorderStyleEnum.None)
{
Pen p = new Pen(si.BColorTop, si.BWidthTop);
switch (si.BStyleTop)
{
case BorderStyleEnum.Dashed:
p.DashStyle = DashStyle.Dash;
break;
case BorderStyleEnum.Dotted:
p.DashStyle = DashStyle.Dot;
break;
case BorderStyleEnum.Double:
case BorderStyleEnum.Groove:
case BorderStyleEnum.Inset:
case BorderStyleEnum.Solid:
case BorderStyleEnum.Outset:
case BorderStyleEnum.Ridge:
case BorderStyleEnum.WindowInset:
default:
p.DashStyle = DashStyle.Solid;
break;
}
g.DrawEllipse(p, r);
}
}
private void FillPolygon(PagePolygon pp, Graphics g, RectangleF r)
{
StyleInfo si = pp.SI;
PointF[] tmp = new PointF[pp.Points.Length];
if (!si.BackgroundColor.IsEmpty)
{
for (int i = 0; i < pp.Points.Length; i++)
{
tmp[i].X = PixelsX(pp.Points[i].X);
tmp[i].Y = PixelsY(pp.Points[i].Y);
}
g.FillPolygon(new SolidBrush(si.BackgroundColor), tmp);
}
}
private void DrawPie(PagePie pp, Graphics g, RectangleF r)
{
StyleInfo si = pp.SI;
if (!si.BackgroundColor.IsEmpty)
{
g.FillPie(new SolidBrush(si.BackgroundColor), (int)r.X, (int)r.Y, (int)r.Width, (int)r.Height, (float)pp.StartAngle, (float)pp.SweepAngle);
}
if (si.BStyleTop != BorderStyleEnum.None)
{
Pen p = new Pen(si.BColorTop, si.BWidthTop);
switch (si.BStyleTop)
{
case BorderStyleEnum.Dashed:
p.DashStyle = DashStyle.Dash;
break;
case BorderStyleEnum.Dotted:
p.DashStyle = DashStyle.Dot;
break;
case BorderStyleEnum.Double:
case BorderStyleEnum.Groove:
case BorderStyleEnum.Inset:
case BorderStyleEnum.Solid:
case BorderStyleEnum.Outset:
case BorderStyleEnum.Ridge:
case BorderStyleEnum.WindowInset:
default:
p.DashStyle = DashStyle.Solid;
break;
}
g.DrawPie(p, r, pp.StartAngle, pp.SweepAngle);
}
}
private void DrawString(PageText pt, Graphics g, RectangleF r)
{
StyleInfo si = pt.SI;
string s = pt.Text;
Font drawFont = null;
StringFormat drawFormat = null;
Brush drawBrush = null;
try
{
// STYLE
System.Drawing.FontStyle fs = 0;
if (si.FontStyle == FontStyleEnum.Italic)
fs |= System.Drawing.FontStyle.Italic;
switch (si.TextDecoration)
{
case TextDecorationEnum.Underline:
fs |= System.Drawing.FontStyle.Underline;
break;
case TextDecorationEnum.LineThrough:
fs |= System.Drawing.FontStyle.Strikeout;
break;
case TextDecorationEnum.Overline:
case TextDecorationEnum.None:
break;
}
// WEIGHT
switch (si.FontWeight)
{
case FontWeightEnum.Bold:
case FontWeightEnum.Bolder:
case FontWeightEnum.W500:
case FontWeightEnum.W600:
case FontWeightEnum.W700:
case FontWeightEnum.W800:
case FontWeightEnum.W900:
fs |= System.Drawing.FontStyle.Bold;
break;
default:
break;
}
try
{
drawFont = new Font(si.GetFontFamily(), si.FontSize, fs); // si.FontSize already in points
}
catch (ArgumentException)
{
drawFont = new Font("Arial", si.FontSize, fs); // if this fails we'll let the error pass thru
}
// ALIGNMENT
drawFormat = new StringFormat();
switch (si.TextAlign)
{
case TextAlignEnum.Right:
drawFormat.Alignment = StringAlignment.Far;
break;
case TextAlignEnum.Center:
drawFormat.Alignment = StringAlignment.Center;
break;
case TextAlignEnum.Left:
default:
drawFormat.Alignment = StringAlignment.Near;
break;
}
if (pt.SI.WritingMode == WritingModeEnum.tb_rl)
{
drawFormat.FormatFlags |= StringFormatFlags.DirectionRightToLeft;
drawFormat.FormatFlags |= StringFormatFlags.DirectionVertical;
}
switch (si.VerticalAlign)
{
case VerticalAlignEnum.Bottom:
drawFormat.LineAlignment = StringAlignment.Far;
break;
case VerticalAlignEnum.Middle:
drawFormat.LineAlignment = StringAlignment.Center;
break;
case VerticalAlignEnum.Top:
default:
drawFormat.LineAlignment = StringAlignment.Near;
break;
}
// draw the background
DrawBackground(g, r, si);
// adjust drawing rectangle based on padding
RectangleF r2 = new RectangleF(r.Left + si.PaddingLeft,
r.Top + si.PaddingTop,
r.Width - si.PaddingLeft - si.PaddingRight,
r.Height - si.PaddingTop - si.PaddingBottom);
drawBrush = new SolidBrush(si.Color);
if (pt.NoClip) // request not to clip text
{
g.DrawString(pt.Text, drawFont, drawBrush, new PointF(r.Left, r.Top), drawFormat);
//HighlightString(g, pt, new RectangleF(r.Left, r.Top, float.MaxValue, float.MaxValue),drawFont, drawFormat);
}
else
{
g.DrawString(pt.Text, drawFont, drawBrush, r2, drawFormat);
//HighlightString(g, pt, r2, drawFont, drawFormat);
}
}
finally
{
if (drawFont != null)
drawFont.Dispose();
if (drawFormat != null)
drawFont.Dispose();
if (drawBrush != null)
drawBrush.Dispose();
}
}
private void DrawImage(PageImage pi, Graphics g, RectangleF r)
{
Stream strm = null;
System.Drawing.Image im = null;
try
{
strm = new MemoryStream(pi.ImageData);
im = System.Drawing.Image.FromStream(strm);
DrawImageSized(pi, im, g, r);
}
finally
{
if (strm != null)
strm.Close();
if (im != null)
im.Dispose();
}
}
private void DrawImageSized(PageImage pi, System.Drawing.Image im, System.Drawing.Graphics g, System.Drawing.RectangleF r)
{
float height, width; // some work variables
StyleInfo si = pi.SI;
// adjust drawing rectangle based on padding
System.Drawing.RectangleF r2 = new System.Drawing.RectangleF(r.Left + PixelsX(si.PaddingLeft),
r.Top + PixelsY(si.PaddingTop),
r.Width - PixelsX(si.PaddingLeft + si.PaddingRight),
r.Height - PixelsY(si.PaddingTop + si.PaddingBottom));
System.Drawing.Rectangle ir; // int work rectangle
switch (pi.Sizing)
{
case ImageSizingEnum.AutoSize:
// Note: GDI+ will stretch an image when you only provide
// the left/top coordinates. This seems pretty stupid since
// it results in the image being out of focus even though
// you don't want the image resized.
if (g.DpiX == im.HorizontalResolution &&
g.DpiY == im.VerticalResolution)
{
ir = new System.Drawing.Rectangle(Convert.ToInt32(r2.Left), Convert.ToInt32(r2.Top),
im.Width, im.Height);
}
else
ir = new System.Drawing.Rectangle(Convert.ToInt32(r2.Left), Convert.ToInt32(r2.Top),
Convert.ToInt32(r2.Width), Convert.ToInt32(r2.Height));
g.DrawImage(im, ir);
break;
case ImageSizingEnum.Clip:
Region saveRegion = g.Clip;
Region clipRegion = new Region(g.Clip.GetRegionData());
clipRegion.Intersect(r2);
g.Clip = clipRegion;
if (g.DpiX == im.HorizontalResolution &&
g.DpiY == im.VerticalResolution)
{
ir = new System.Drawing.Rectangle(Convert.ToInt32(r2.Left), Convert.ToInt32(r2.Top),
im.Width, im.Height);
}
else
ir = new System.Drawing.Rectangle(Convert.ToInt32(r2.Left), Convert.ToInt32(r2.Top),
Convert.ToInt32(r2.Width), Convert.ToInt32(r2.Height));
g.DrawImage(im, ir);
g.Clip = saveRegion;
break;
case ImageSizingEnum.FitProportional:
float ratioIm = (float)im.Height / (float)im.Width;
float ratioR = r2.Height / r2.Width;
height = r2.Height;
width = r2.Width;
if (ratioIm > ratioR)
{ // this means the rectangle width must be corrected
width = height * (1 / ratioIm);
}
else if (ratioIm < ratioR)
{ // this means the ractangle height must be corrected
height = width * ratioIm;
}
r2 = new RectangleF(r2.X, r2.Y, width, height);
g.DrawImage(im, r2);
break;
case ImageSizingEnum.Fit:
default:
g.DrawImage(im, r2);
break;
}
return;
}
private void DrawBackground(Graphics g, System.Drawing.RectangleF rect, StyleInfo si)
{
LinearGradientBrush linGrBrush = null;
SolidBrush sb = null;
try
{
if (si.BackgroundGradientType != BackgroundGradientTypeEnum.None &&
!si.BackgroundGradientEndColor.IsEmpty &&
!si.BackgroundColor.IsEmpty)
{
Color c = si.BackgroundColor;
Color ec = si.BackgroundGradientEndColor;
switch (si.BackgroundGradientType)
{
case BackgroundGradientTypeEnum.LeftRight:
linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Horizontal);
break;
case BackgroundGradientTypeEnum.TopBottom:
linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Vertical);
break;
case BackgroundGradientTypeEnum.Center:
linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Horizontal);
break;
case BackgroundGradientTypeEnum.DiagonalLeft:
linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.ForwardDiagonal);
break;
case BackgroundGradientTypeEnum.DiagonalRight:
linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.BackwardDiagonal);
break;
case BackgroundGradientTypeEnum.HorizontalCenter:
linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Horizontal);
break;
case BackgroundGradientTypeEnum.VerticalCenter:
linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Vertical);
break;
default:
break;
}
}
if (linGrBrush != null)
{
g.FillRectangle(linGrBrush, rect);
linGrBrush.Dispose();
}
else if (!si.BackgroundColor.IsEmpty)
{
sb = new SolidBrush(si.BackgroundColor);
g.FillRectangle(sb, rect);
sb.Dispose();
}
}
finally
{
if (linGrBrush != null)
linGrBrush.Dispose();
if (sb != null)
sb.Dispose();
}
return;
}
private void DrawBorder(PageItem pi, Graphics g, RectangleF r)
{
if (r.Height <= 0 || r.Width <= 0) // no bounding box to use
return;
StyleInfo si = pi.SI;
DrawLine(si.BColorTop, si.BStyleTop, si.BWidthTop, g, r.X, r.Y, r.Right, r.Y);
DrawLine(si.BColorRight, si.BStyleRight, si.BWidthRight, g, r.Right, r.Y, r.Right, r.Bottom);
DrawLine(si.BColorLeft, si.BStyleLeft, si.BWidthLeft, g, r.X, r.Y, r.X, r.Bottom);
DrawLine(si.BColorBottom, si.BStyleBottom, si.BWidthBottom, g, r.X, r.Bottom, r.Right, r.Bottom);
return;
}
#region TIFF image handler
private Bitmap CreateObjectBitmap()
{
float dpiX = 200F;
float dpiY = 200F;
Bitmap bm = new System.Drawing.Bitmap(
Convert.ToInt32(r.ReportDefinition.PageWidth.Size / 2540F * dpiX),
Convert.ToInt32(r.ReportDefinition.PageHeight.Size / 2540F * dpiY)
);
bm.MakeTransparent(Color.White);
bm.SetResolution(dpiX, dpiY);
return bm;
}
private Bitmap ConvertToBitonal(Bitmap original)
{
if (_RenderColor)
return original;
Bitmap source = null;
// If original bitmap is not already in 32 BPP, ARGB format, then convert
if (original.PixelFormat != PixelFormat.Format32bppArgb)
{
source = new Bitmap(original.Width, original.Height, PixelFormat.Format32bppArgb);
source.SetResolution(original.HorizontalResolution, original.VerticalResolution);
using (Graphics g = Graphics.FromImage(source))
{
g.DrawImageUnscaled(original, 0, 0);
}
}
else
{
source = original;
}
// Lock source bitmap in memory
BitmapData sourceData = source.LockBits(new System.Drawing.Rectangle(0, 0, source.Width, source.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
// Copy image data to binary array
int imageSize = sourceData.Stride * sourceData.Height;
byte[] sourceBuffer = new byte[imageSize];
Marshal.Copy(sourceData.Scan0, sourceBuffer, 0, imageSize);
// Unlock source bitmap
source.UnlockBits(sourceData);
// Create destination bitmap
Bitmap destination = new Bitmap(source.Width, source.Height, PixelFormat.Format1bppIndexed);
// Set resolution
destination.SetResolution(source.HorizontalResolution, source.VerticalResolution);
// Lock destination bitmap in memory
BitmapData destinationData = destination.LockBits(new System.Drawing.Rectangle(0, 0, destination.Width, destination.Height), ImageLockMode.WriteOnly, PixelFormat.Format1bppIndexed);
// Create destination buffer
imageSize = destinationData.Stride * destinationData.Height;
byte[] destinationBuffer = new byte[imageSize];
int sourceIndex = 0;
int destinationIndex = 0;
int pixelTotal = 0;
byte destinationValue = 0;
int pixelValue = 128;
int height = source.Height;
int width = source.Width;
int threshold = 500;
// Iterate lines
for (int y = 0; y < height; y++)
{
sourceIndex = y * sourceData.Stride;
destinationIndex = y * destinationData.Stride;
destinationValue = 0;
pixelValue = 128;
// Iterate pixels
for (int x = 0; x < width; x++)
{
// Compute pixel brightness (i.e. total of Red, Green, and Blue values)
pixelTotal = sourceBuffer[sourceIndex + 1] + sourceBuffer[sourceIndex + 2] + sourceBuffer[sourceIndex + 3];
if (pixelTotal > threshold)
{
destinationValue += (byte)pixelValue;
}
if (pixelValue == 1)
{
destinationBuffer[destinationIndex] = destinationValue;
destinationIndex++;
destinationValue = 0;
pixelValue = 128;
}
else
{
pixelValue >>= 1;
}
sourceIndex += 4;
}
if (pixelValue != 128)
{
destinationBuffer[destinationIndex] = destinationValue;
}
}
// Copy binary image data to destination bitmap
Marshal.Copy(destinationBuffer, 0, destinationData.Scan0, imageSize);
// Unlock destination bitmap
destination.UnlockBits(destinationData);
// Return
return destination;
}
private void SaveBitmap(Bitmap tif, Bitmap bm, Stream st, int pageNo)
{
if (pageNo == 1)
{
// Handling saving first page
// STEP: Prepare ImageCodecInfo for saving
ImageCodecInfo info = null;
foreach (ImageCodecInfo i in ImageCodecInfo.GetImageEncoders())
{
if (i.MimeType == "image/tiff")
{
info = i;
break;
}
}
// STEP: Prepare parameters
EncoderParameters encoderParams = new EncoderParameters(2);
encoderParams.Param[0] = new EncoderParameter(
System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.MultiFrame
);
encoderParams.Param[1] = new EncoderParameter(
System.Drawing.Imaging.Encoder.Compression,
(long)(_RenderColor? EncoderValue.CompressionLZW: EncoderValue.CompressionCCITT3)
);
// STEP: Save bitmap
tif.Save(st, info, encoderParams);
}
else
{
// STEP: Prepare parameters
EncoderParameters encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = new EncoderParameter(
System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.FrameDimensionPage
);
// STEP: Save bitmap
tif.SaveAdd(bm, encoderParams);
}
}
#endregion
public float PixelsX(float x)
{
return (x * DpiX / 72.0f);
}
public float PixelsY(float y)
{
return (y * DpiY / 72.0f);
}
// Body: main container for the report
public void BodyStart(Body b)
{
}
public void BodyEnd(Body b)
{
}
public void PageHeaderStart(PageHeader ph)
{
}
public void PageHeaderEnd(PageHeader ph)
{
}
public void PageFooterStart(PageFooter pf)
{
}
public void PageFooterEnd(PageFooter pf)
{
}
public void Textbox(Textbox tb, string t, Row row)
{
}
public void DataRegionNoRows(DataRegion d, string noRowsMsg)
{
}
// Lists
public bool ListStart(List l, Row r)
{
return true;
}
public void ListEnd(List l, Row r)
{
}
public void ListEntryBegin(List l, Row r)
{
}
public void ListEntryEnd(List l, Row r)
{
}
// Tables // Report item table
public bool TableStart(Table t, Row row)
{
return true;
}
public void TableEnd(Table t, Row row)
{
}
public void TableBodyStart(Table t, Row row)
{
}
public void TableBodyEnd(Table t, Row row)
{
}
public void TableFooterStart(Footer f, Row row)
{
}
public void TableFooterEnd(Footer f, Row row)
{
}
public void TableHeaderStart(Header h, Row row)
{
}
public void TableHeaderEnd(Header h, Row row)
{
}
public void TableRowStart(TableRow tr, Row row)
{
}
public void TableRowEnd(TableRow tr, Row row)
{
}
public void TableCellStart(TableCell t, Row row)
{
return;
}
public void TableCellEnd(TableCell t, Row row)
{
return;
}
public bool MatrixStart(Matrix m, MatrixCellEntry[,] matrix, Row r, int headerRows, int maxRows, int maxCols) // called first
{
return true;
}
public void MatrixColumns(Matrix m, MatrixColumns mc) // called just after MatrixStart
{
}
public void MatrixCellStart(Matrix m, ReportItem ri, int row, int column, Row r, float h, float w, int colSpan)
{
}
public void MatrixCellEnd(Matrix m, ReportItem ri, int row, int column, Row r)
{
}
public void MatrixRowStart(Matrix m, int row, Row r)
{
}
public void MatrixRowEnd(Matrix m, int row, Row r)
{
}
public void MatrixEnd(Matrix m, Row r) // called last
{
}
public void Chart(Chart c, Row r, ChartBase cb)
{
}
public void Image(Oranikle.Report.Engine.Image i, Row r, string mimeType, Stream ior)
{
}
public void Line(Line l, Row r)
{
return;
}
public bool RectangleStart(Oranikle.Report.Engine.Rectangle rect, Row r)
{
return true;
}
public void RectangleEnd(Oranikle.Report.Engine.Rectangle rect, Row r)
{
}
public void Subreport(Subreport s, Row r)
{
}
public void GroupingStart(Grouping g) // called at start of grouping
{
}
public void GroupingInstanceStart(Grouping g) // called at start for each grouping instance
{
}
public void GroupingInstanceEnd(Grouping g) // called at start for each grouping instance
{
}
public void GroupingEnd(Grouping g) // called at end of grouping
{
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Web;
using log4net;
using OpenSim.Framework.ServiceAuth;
namespace OpenSim.Framework.Communications
{
/// <summary>
/// Implementation of a generic REST client
/// </summary>
/// <remarks>
/// This class is a generic implementation of a REST (Representational State Transfer) web service. This
/// class is designed to execute both synchronously and asynchronously.
///
/// Internally the implementation works as a two stage asynchronous web-client.
/// When the request is initiated, RestClient will query asynchronously for for a web-response,
/// sleeping until the initial response is returned by the server. Once the initial response is retrieved
/// the second stage of asynchronous requests will be triggered, in an attempt to read of the response
/// object into a memorystream as a sequence of asynchronous reads.
///
/// The asynchronisity of RestClient is designed to move as much processing into the back-ground, allowing
/// other threads to execute, while it waits for a response from the web-service. RestClient itself can be
/// invoked by the caller in either synchronous mode or asynchronous modes.
/// </remarks>
public class RestClient : IDisposable
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// private string realuri;
#region member variables
/// <summary>
/// The base Uri of the web-service e.g. http://www.google.com
/// </summary>
private string _url;
/// <summary>
/// Path elements of the query
/// </summary>
private List<string> _pathElements = new List<string>();
/// <summary>
/// Parameter elements of the query, e.g. min=34
/// </summary>
private Dictionary<string, string> _parameterElements = new Dictionary<string, string>();
/// <summary>
/// Request method. E.g. GET, POST, PUT or DELETE
/// </summary>
private string _method;
/// <summary>
/// Temporary buffer used to store bytes temporarily as they come in from the server
/// </summary>
private byte[] _readbuf;
/// <summary>
/// MemoryStream representing the resulting resource
/// </summary>
private Stream _resource;
/// <summary>
/// WebRequest object, held as a member variable
/// </summary>
private HttpWebRequest _request;
/// <summary>
/// WebResponse object, held as a member variable, so we can close it
/// </summary>
private HttpWebResponse _response;
/// <summary>
/// This flag will help block the main synchroneous method, in case we run in synchroneous mode
/// </summary>
//public static ManualResetEvent _allDone = new ManualResetEvent(false);
/// <summary>
/// Default time out period
/// </summary>
//private const int DefaultTimeout = 10*1000; // 10 seconds timeout
/// <summary>
/// Default Buffer size of a block requested from the web-server
/// </summary>
private const int BufferSize = 4096; // Read blocks of 4 KB.
/// <summary>
/// if an exception occours during async processing, we need to save it, so it can be
/// rethrown on the primary thread;
/// </summary>
private Exception _asyncException;
#endregion member variables
#region constructors
/// <summary>
/// Instantiate a new RestClient
/// </summary>
/// <param name="url">Web-service to query, e.g. http://osgrid.org:8003</param>
public RestClient(string url)
{
_url = url;
_readbuf = new byte[BufferSize];
_resource = new MemoryStream();
_request = null;
_response = null;
_lock = new object();
}
private object _lock;
#endregion constructors
#region Dispose
private bool disposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
_resource.Dispose();
}
disposed = true;
}
#endregion Dispose
/// <summary>
/// Add a path element to the query, e.g. assets
/// </summary>
/// <param name="element">path entry</param>
public void AddResourcePath(string element)
{
if (isSlashed(element))
_pathElements.Add(element.Substring(0, element.Length - 1));
else
_pathElements.Add(element);
}
/// <summary>
/// Add a query parameter to the Url
/// </summary>
/// <param name="name">Name of the parameter, e.g. min</param>
/// <param name="value">Value of the parameter, e.g. 42</param>
public void AddQueryParameter(string name, string value)
{
try
{
_parameterElements.Add(HttpUtility.UrlEncode(name), HttpUtility.UrlEncode(value));
}
catch (ArgumentException)
{
m_log.Error("[REST]: Query parameter " + name + " is already added.");
}
catch (Exception e)
{
m_log.Error("[REST]: An exception was raised adding query parameter to dictionary. Exception: {0}",e);
}
}
/// <summary>
/// Add a query parameter to the Url
/// </summary>
/// <param name="name">Name of the parameter, e.g. min</param>
public void AddQueryParameter(string name)
{
try
{
_parameterElements.Add(HttpUtility.UrlEncode(name), null);
}
catch (ArgumentException)
{
m_log.Error("[REST]: Query parameter " + name + " is already added.");
}
catch (Exception e)
{
m_log.Error("[REST]: An exception was raised adding query parameter to dictionary. Exception: {0}",e);
}
}
/// <summary>
/// Web-Request method, e.g. GET, PUT, POST, DELETE
/// </summary>
public string RequestMethod
{
get { return _method; }
set { _method = value; }
}
/// <summary>
/// True if string contains a trailing slash '/'
/// </summary>
/// <param name="s">string to be examined</param>
/// <returns>true if slash is present</returns>
private static bool isSlashed(string s)
{
return s.Substring(s.Length - 1, 1) == "/";
}
/// <summary>
/// Build a Uri based on the initial Url, path elements and parameters
/// </summary>
/// <returns>fully constructed Uri</returns>
private Uri buildUri()
{
StringBuilder sb = new StringBuilder();
sb.Append(_url);
foreach (string e in _pathElements)
{
sb.Append("/");
sb.Append(e);
}
bool firstElement = true;
foreach (KeyValuePair<string, string> kv in _parameterElements)
{
if (firstElement)
{
sb.Append("?");
firstElement = false;
}
else
sb.Append("&");
sb.Append(kv.Key);
if (!string.IsNullOrEmpty(kv.Value))
{
sb.Append("=");
sb.Append(kv.Value);
}
}
// realuri = sb.ToString();
//m_log.InfoFormat("[REST CLIENT]: RestURL: {0}", realuri);
return new Uri(sb.ToString());
}
#region Async communications with server
/// <summary>
/// Async method, invoked when a block of data has been received from the service
/// </summary>
/// <param name="ar"></param>
private void StreamIsReadyDelegate(IAsyncResult ar)
{
try
{
Stream s = (Stream) ar.AsyncState;
int read = s.EndRead(ar);
if (read > 0)
{
_resource.Write(_readbuf, 0, read);
// IAsyncResult asynchronousResult =
// s.BeginRead(_readbuf, 0, BufferSize, new AsyncCallback(StreamIsReadyDelegate), s);
s.BeginRead(_readbuf, 0, BufferSize, new AsyncCallback(StreamIsReadyDelegate), s);
// TODO! Implement timeout, without killing the server
//ThreadPool.RegisterWaitForSingleObject(asynchronousResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true);
}
else
{
s.Close();
//_allDone.Set();
}
}
catch (Exception e)
{
//_allDone.Set();
_asyncException = e;
}
}
#endregion Async communications with server
/// <summary>
/// Perform a synchronous request
/// </summary>
public Stream Request()
{
return Request(null);
}
/// <summary>
/// Perform a synchronous request
/// </summary>
public Stream Request(IServiceAuth auth)
{
lock (_lock)
{
_request = (HttpWebRequest) WebRequest.Create(buildUri());
_request.KeepAlive = false;
_request.ContentType = "application/xml";
_request.Timeout = 200000;
_request.Method = RequestMethod;
_asyncException = null;
if (auth != null)
auth.AddAuthorization(_request.Headers);
int reqnum = WebUtil.RequestNumber++;
if (WebUtil.DebugLevel >= 3)
m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} REST {1} to {2}", reqnum, _request.Method, _request.RequestUri);
// IAsyncResult responseAsyncResult = _request.BeginGetResponse(new AsyncCallback(ResponseIsReadyDelegate), _request);
try
{
using (_response = (HttpWebResponse) _request.GetResponse())
{
using (Stream src = _response.GetResponseStream())
{
int length = src.Read(_readbuf, 0, BufferSize);
while (length > 0)
{
_resource.Write(_readbuf, 0, length);
length = src.Read(_readbuf, 0, BufferSize);
}
// TODO! Implement timeout, without killing the server
// this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
//ThreadPool.RegisterWaitForSingleObject(responseAsyncResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true);
// _allDone.WaitOne();
}
}
}
catch (WebException e)
{
using (HttpWebResponse errorResponse = e.Response as HttpWebResponse)
{
if (null != errorResponse && HttpStatusCode.NotFound == errorResponse.StatusCode)
{
// This is often benign. E.g., requesting a missing asset will return 404.
m_log.DebugFormat("[REST CLIENT] Resource not found (404): {0}", _request.Address.ToString());
}
else
{
m_log.Error(string.Format("[REST CLIENT] Error fetching resource from server: {0} ", _request.Address.ToString()), e);
}
}
return null;
}
if (_asyncException != null)
throw _asyncException;
if (_resource != null)
{
_resource.Flush();
_resource.Seek(0, SeekOrigin.Begin);
}
if (WebUtil.DebugLevel >= 5)
WebUtil.LogResponseDetail(reqnum, _resource);
return _resource;
}
}
public Stream Request(Stream src, IServiceAuth auth)
{
_request = (HttpWebRequest) WebRequest.Create(buildUri());
_request.KeepAlive = false;
_request.ContentType = "application/xml";
_request.Timeout = 900000;
_request.Method = RequestMethod;
_asyncException = null;
_request.ContentLength = src.Length;
if (auth != null)
auth.AddAuthorization(_request.Headers);
src.Seek(0, SeekOrigin.Begin);
int reqnum = WebUtil.RequestNumber++;
if (WebUtil.DebugLevel >= 3)
m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} REST {1} to {2}", reqnum, _request.Method, _request.RequestUri);
if (WebUtil.DebugLevel >= 5)
WebUtil.LogOutgoingDetail(string.Format("SEND {0}: ", reqnum), src);
Stream dst = _request.GetRequestStream();
byte[] buf = new byte[1024];
int length = src.Read(buf, 0, 1024);
while (length > 0)
{
dst.Write(buf, 0, length);
length = src.Read(buf, 0, 1024);
}
try
{
_response = (HttpWebResponse)_request.GetResponse();
}
catch (WebException e)
{
m_log.WarnFormat("[REST]: Request {0} {1} failed with status {2} and message {3}",
RequestMethod, _request.RequestUri, e.Status, e.Message);
return null;
}
catch (Exception e)
{
m_log.WarnFormat(
"[REST]: Request {0} {1} failed with exception {2} {3}",
RequestMethod, _request.RequestUri, e.Message, e.StackTrace);
return null;
}
if (WebUtil.DebugLevel >= 5)
{
using (Stream responseStream = _response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
string responseStr = reader.ReadToEnd();
WebUtil.LogResponseDetail(reqnum, responseStr);
}
}
}
_response.Close();
// IAsyncResult responseAsyncResult = _request.BeginGetResponse(new AsyncCallback(ResponseIsReadyDelegate), _request);
// TODO! Implement timeout, without killing the server
// this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
//ThreadPool.RegisterWaitForSingleObject(responseAsyncResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true);
return null;
}
#region Async Invocation
public IAsyncResult BeginRequest(AsyncCallback callback, object state)
{
/// <summary>
/// In case, we are invoked asynchroneously this object will keep track of the state
/// </summary>
AsyncResult<Stream> ar = new AsyncResult<Stream>(callback, state);
Util.FireAndForget(RequestHelper, ar, "RestClient.BeginRequest");
return ar;
}
public Stream EndRequest(IAsyncResult asyncResult)
{
AsyncResult<Stream> ar = (AsyncResult<Stream>) asyncResult;
// Wait for operation to complete, then return result or
// throw exception
return ar.EndInvoke();
}
private void RequestHelper(Object asyncResult)
{
// We know that it's really an AsyncResult<DateTime> object
AsyncResult<Stream> ar = (AsyncResult<Stream>) asyncResult;
try
{
// Perform the operation; if sucessful set the result
Stream s = Request(null);
ar.SetAsCompleted(s, false);
}
catch (Exception e)
{
// If operation fails, set the exception
ar.HandleException(e, false);
}
}
#endregion Async Invocation
}
}
| |
using UnityEngine;
using System;
using System.Collections.Generic;
public class TileManager : MonoBehaviour {
public static TileManager instance;
[Serializable]
public struct NamedSprite {
public string name;
public Sprite sprite;
}
public GameObject tilePrefab;
public Sprite[] tileSprites;
public NamedSprite[] itemSpriteList;
public Dictionary<string, Sprite> itemSprites;
public int displayWidth;
public int displayHeight;
private TileController[,] displayTiles;
private CameraController camController;
private IntVector2 tileTL = IntVector2.zero;
private IntVector2 tileBR = IntVector2.zero;
private bool firstUpdate = true;
// Use this for initialization
void Start() {
if (instance != null && instance != this) {
Destroy(this);
return;
}
instance = this;
// Make sure our tile sprites match up with our tile types.
if (Enum.GetValues(typeof(Board.TileType)).Length != tileSprites.Length) {
Debug.LogError("Tile sprites and TileTypes do not match!");
}
// Fetch the main camera's controller.
camController = Camera.main.GetComponent<CameraController>();
if (camController == null) {
Debug.LogError("TileManager could not find main camera's controller.");
}
// Load the item sprites into a dictionary for faster reference.
itemSprites = new Dictionary<string, Sprite>();
foreach (NamedSprite ns in itemSpriteList) {
Debug.Log("Adding item sprite " + ns.name);
itemSprites.Add(ns.name, ns.sprite);
}
// Build the board and register for tile events.
BuildDisplayBoard();
BoardManager.Board.RegisterOnTileEvent(OnTileEvent);
}
void Update() {
if (firstUpdate) {
firstUpdate = false;
Redraw();
}
// If the camera controller moved this last frame, let's move our tiles
// to keep centered around it.
if (camController.movement.x != 0 || camController.movement.y != 0) {
MoveTiles();
}
}
public void Redraw() {
foreach (TileController controller in displayTiles) {
controller.Render();
}
}
private void MoveTiles() {
// To start, we need to figure out where the board's top-left and
// bottom-right corners _should_ be. This is determined simply from the
// position of the camera like this:
//
// TargetTop = CameraY + HalfBoardHeight;
// TargetLeft = CameraX - HalfBoardWidth;
// TargetBottom = TargetTop - BoardHeight;
// TargetRight = TargetLeft + BoardWidth;
TileController topLeft = displayTiles[tileTL.x, tileTL.y];
TileController botRight = displayTiles[tileBR.x, tileBR.y];
Vector2 targetTL = new Vector2(
camController.transform.position.x - (displayWidth / 2f),
camController.transform.position.y + (displayHeight / 2f)
);
Vector2 targetBR = new Vector2(
targetTL.x + (float)displayWidth,
targetTL.y - (float)displayHeight
);
// Now we know where the board _should_ be, so move the rows until they
// are close to where we want them. The moving functions will also
// update the top-left and bottom-right positions as they go, hence why
// they are passed in by reference.
// Move the top or bottom rows until they are at the target locations.
// Typically only one of these will run depending on the direction the
// camera moved.
while (topLeft.transform.position.y > targetTL.y) {
MoveTopRow(ref topLeft, ref botRight);
}
while (botRight.transform.position.y < targetBR.y) {
MoveBottomRow(ref topLeft, ref botRight);
}
// Do the same for the left and right columns.
while (topLeft.transform.position.x < targetTL.x) {
MoveLeftColumn(ref topLeft, ref botRight);
}
while (botRight.transform.position.x > targetBR.x) {
MoveRightColumn(ref topLeft, ref botRight);
}
// We've moved our tiles around, now store the positions in our
// displayTiles grid of the visually top-left and bottom-right tiles.
tileTL = topLeft.displayPosition;
tileBR = botRight.displayPosition;
}
private void BuildDisplayBoard() {
// First, destroy our existing board.
if (displayTiles != null) {
DestroyDisplayTiles();
}
// Now construct the new tiles.
Debug.Log("Constructing board at " + displayWidth + "x" + displayHeight);
displayTiles = new TileController[displayWidth, displayHeight];
for (int x = 0; x < displayWidth; ++x) {
for (int y = 0; y < displayHeight; ++y) {
// Create a new tile instance.
GameObject tile = Instantiate(tilePrefab) as GameObject;
tile.name = "Tile(" + x + ", " + y + ")";
tile.transform.parent = gameObject.transform;
// Only enable if you _really_ need this!
// Debug.Log("Created " + tile.name);
// Set up the tile's controller.
TileController controller = tile.GetComponent<TileController>();
controller.displayPosition = new IntVector2(x, y);
controller.MoveTo(x, y);
displayTiles[x, y] = controller;
}
}
tileTL = new IntVector2(0, displayHeight - 1);
tileBR = new IntVector2(displayWidth - 1, 0);
// After building the board we'll need to move the board to be centered
// around the screen.
MoveTiles();
}
private void DestroyDisplayTiles() {
foreach (TileController controller in displayTiles) {
Destroy(controller.gameObject);
}
displayTiles = null;
}
private void MoveTopRow(ref TileController topLeft, ref TileController botRight) {
int topDispRowY = topLeft.displayPosition.y;
int botGridRowY = botRight.gridPosition.y;
TileController rightMost = null;
for (int x = 0; x < displayWidth; ++x) {
TileController controller = displayTiles[x, topDispRowY];
controller.MoveTo(controller.gridPosition.x, botGridRowY - 1);
if (rightMost == null || controller.IsRightOf(rightMost.gridPosition)) {
rightMost = controller;
}
}
botRight = rightMost;
topLeft = displayTiles[
topLeft.displayPosition.x,
(botRight.displayPosition.y - 1 + displayHeight) % displayHeight
];
}
private void MoveBottomRow(ref TileController topLeft, ref TileController botRight) {
int botDispRowY = botRight.displayPosition.y;
int topGridRowY = topLeft.gridPosition.y;
TileController leftMost = null;
for (int x = 0; x < displayWidth; ++x) {
TileController controller = displayTiles[x, botDispRowY];
controller.MoveTo(controller.gridPosition.x, topGridRowY + 1);
if (leftMost == null || controller.IsLeftOf(leftMost.gridPosition)) {
leftMost = controller;
}
}
topLeft = leftMost;
botRight = displayTiles[
botRight.displayPosition.x,
(topLeft.displayPosition.y + 1) % displayHeight
];
}
private void MoveLeftColumn(ref TileController topLeft, ref TileController botRight) {
int leftDispColX = topLeft.displayPosition.x;
int rightGridColX = botRight.gridPosition.x;
TileController lowest = null;
for (int y = 0; y < displayHeight; ++y) {
TileController controller = displayTiles[leftDispColX, y];
controller.MoveTo(rightGridColX + 1, controller.gridPosition.y);
if (lowest == null || controller.IsBelow(lowest.gridPosition)) {
lowest = controller;
}
}
botRight = lowest;
topLeft = displayTiles[
(topLeft.displayPosition.x + 1) % displayWidth,
topLeft.displayPosition.y
];
}
private void MoveRightColumn(ref TileController topLeft, ref TileController botRight) {
int rightDispColX = botRight.displayPosition.x;
int leftGridColX = topLeft.gridPosition.x;
TileController highest = null;
for (int y = 0; y < displayHeight; ++y) {
TileController controller = displayTiles[rightDispColX, y];
controller.MoveTo(leftGridColX - 1, controller.gridPosition.y);
if (highest == null || controller.IsAbove(highest.gridPosition)) {
highest = controller;
}
}
topLeft = highest;
botRight = displayTiles[
(botRight.displayPosition.x - 1 + displayWidth) % displayWidth,
botRight.displayPosition.y
];
}
private void OnTileEvent(Events.TileEvent e) {
// Get the controller and check that we actually found one. If the tile
// isn't being displayed currently, then GetTileController returns null.
TileController controller = GetTileController(e.tile);
if (controller != null) {
controller.OnTileEvent(e);
}
}
private bool IsDisplayed(Board.Tile tile) {
IntVector2 topLeft = displayTiles[tileTL.x, tileTL.y].gridPosition;
IntVector2 bottomRight = displayTiles[tileBR.x, tileBR.y].gridPosition;
return tile.position.IsBetween(topLeft, bottomRight);
}
private TileController GetTileController(Board.Tile tile) {
// Figure out where this tile exists within our displayed board. Assuming
// the tile is currently displayed we know its grid position will be
// right of (tile.x > TL.x) and below (tile.y < TL.y) the top-left tile.
TileController topLeft = displayTiles[tileTL.x, tileTL.y];
int xOffset = tile.position.x - topLeft.gridPosition.x; // Positive
int yOffset = tile.position.y - topLeft.gridPosition.y; // Negative
if (
xOffset < 0 || xOffset > displayWidth ||
yOffset > 0 || yOffset < -displayHeight
) {
// This tile is not being displayed, thus we don't have a tile
// controller for it at this time.
return null;
}
// Now we know our grid offset, so calculate our display offset,
// adjusting for wrapping around the display board.
int displayX = (topLeft.displayPosition.x + xOffset) % displayWidth;
int displayY = (topLeft.displayPosition.y + yOffset + displayHeight) % displayHeight;
// And viola, we have a tile controller.
return displayTiles[displayX, displayY];
}
}
| |
// SPDX-License-Identifier: MIT
// Copyright wtfsckgh@gmail.com
// Copyright iced contributors
#if ENCODER && BLOCK_ENCODER
using System;
using Iced.Intel;
using Xunit;
namespace Iced.UnitTests.Intel.EncoderTests {
public sealed class BlockEncoderTest16_br8 : BlockEncoderTest {
const int bitness = 16;
const ulong origRip = 0x8000;
const ulong newRip = 0xF000;
[Fact]
void Br8_fwd() {
var originalData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0xE2, 0x22,// loop 8026h
/*0004*/ 0xB0, 0x01,// mov al,1
/*0006*/ 0x67, 0xE2, 0x1D,// loop 8026h
/*0009*/ 0xB0, 0x02,// mov al,2
/*000B*/ 0xE1, 0x19,// loope 8026h
/*000D*/ 0xB0, 0x03,// mov al,3
/*000F*/ 0x67, 0xE1, 0x14,// loope 8026h
/*0012*/ 0xB0, 0x04,// mov al,4
/*0014*/ 0xE0, 0x10,// loopne 8026h
/*0016*/ 0xB0, 0x05,// mov al,5
/*0018*/ 0x67, 0xE0, 0x0B,// loopne 8026h
/*001B*/ 0xB0, 0x06,// mov al,6
/*001D*/ 0x67, 0xE3, 0x06,// jecxz 8026h
/*0020*/ 0xB0, 0x07,// mov al,7
/*0022*/ 0xE3, 0x02,// jcxz 8026h
/*0024*/ 0xB0, 0x08,// mov al,8
/*0026*/ 0x90,// nop
};
var newData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0xE2, 0x22,// loop 0F026h
/*0004*/ 0xB0, 0x01,// mov al,1
/*0006*/ 0x67, 0xE2, 0x1D,// loop 0F026h
/*0009*/ 0xB0, 0x02,// mov al,2
/*000B*/ 0xE1, 0x19,// loope 0F026h
/*000D*/ 0xB0, 0x03,// mov al,3
/*000F*/ 0x67, 0xE1, 0x14,// loope 0F026h
/*0012*/ 0xB0, 0x04,// mov al,4
/*0014*/ 0xE0, 0x10,// loopne 0F026h
/*0016*/ 0xB0, 0x05,// mov al,5
/*0018*/ 0x67, 0xE0, 0x0B,// loopne 0F026h
/*001B*/ 0xB0, 0x06,// mov al,6
/*001D*/ 0x67, 0xE3, 0x06,// jecxz 0F026h
/*0020*/ 0xB0, 0x07,// mov al,7
/*0022*/ 0xE3, 0x02,// jcxz 0F026h
/*0024*/ 0xB0, 0x08,// mov al,8
/*0026*/ 0x90,// nop
};
var expectedInstructionOffsets = new uint[] {
0x0000,
0x0002,
0x0004,
0x0006,
0x0009,
0x000B,
0x000D,
0x000F,
0x0012,
0x0014,
0x0016,
0x0018,
0x001B,
0x001D,
0x0020,
0x0022,
0x0024,
0x0026,
};
var expectedRelocInfos = Array.Empty<RelocInfo>();
const BlockEncoderOptions options = BlockEncoderOptions.None;
EncodeBase(bitness, origRip, originalData, newRip, newData, options, decoderOptions, expectedInstructionOffsets, expectedRelocInfos);
}
[Fact]
void Br8_bwd() {
var originalData = new byte[] {
/*0000*/ 0x90,// nop
/*0001*/ 0xB0, 0x00,// mov al,0
/*0003*/ 0xE2, 0xFB,// loop 8000h
/*0005*/ 0xB0, 0x01,// mov al,1
/*0007*/ 0x67, 0xE2, 0xF6,// loop 8000h
/*000A*/ 0xB0, 0x02,// mov al,2
/*000C*/ 0xE1, 0xF2,// loope 8000h
/*000E*/ 0xB0, 0x03,// mov al,3
/*0010*/ 0x67, 0xE1, 0xED,// loope 8000h
/*0013*/ 0xB0, 0x04,// mov al,4
/*0015*/ 0xE0, 0xE9,// loopne 8000h
/*0017*/ 0xB0, 0x05,// mov al,5
/*0019*/ 0x67, 0xE0, 0xE4,// loopne 8000h
/*001C*/ 0xB0, 0x06,// mov al,6
/*001E*/ 0x67, 0xE3, 0xDF,// jecxz 8000h
/*0021*/ 0xB0, 0x07,// mov al,7
/*0023*/ 0xE3, 0xDB,// jcxz 8000h
/*0025*/ 0xB0, 0x08,// mov al,8
};
var newData = new byte[] {
/*0000*/ 0x90,// nop
/*0001*/ 0xB0, 0x00,// mov al,0
/*0003*/ 0xE2, 0xFB,// loop 0F000h
/*0005*/ 0xB0, 0x01,// mov al,1
/*0007*/ 0x67, 0xE2, 0xF6,// loop 0F000h
/*000A*/ 0xB0, 0x02,// mov al,2
/*000C*/ 0xE1, 0xF2,// loope 0F000h
/*000E*/ 0xB0, 0x03,// mov al,3
/*0010*/ 0x67, 0xE1, 0xED,// loope 0F000h
/*0013*/ 0xB0, 0x04,// mov al,4
/*0015*/ 0xE0, 0xE9,// loopne 0F000h
/*0017*/ 0xB0, 0x05,// mov al,5
/*0019*/ 0x67, 0xE0, 0xE4,// loopne 0F000h
/*001C*/ 0xB0, 0x06,// mov al,6
/*001E*/ 0x67, 0xE3, 0xDF,// jecxz 0F000h
/*0021*/ 0xB0, 0x07,// mov al,7
/*0023*/ 0xE3, 0xDB,// jcxz 0F000h
/*0025*/ 0xB0, 0x08,// mov al,8
};
var expectedInstructionOffsets = new uint[] {
0x0000,
0x0001,
0x0003,
0x0005,
0x0007,
0x000A,
0x000C,
0x000E,
0x0010,
0x0013,
0x0015,
0x0017,
0x0019,
0x001C,
0x001E,
0x0021,
0x0023,
0x0025,
};
var expectedRelocInfos = Array.Empty<RelocInfo>();
const BlockEncoderOptions options = BlockEncoderOptions.None;
EncodeBase(bitness, origRip, originalData, newRip, newData, options, decoderOptions, expectedInstructionOffsets, expectedRelocInfos);
}
[Fact]
void Br8_fwd_os() {
var originalData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0x66, 0xE2, 0x29,// loopd 0000802Eh
/*0005*/ 0xB0, 0x01,// mov al,1
/*0007*/ 0x66, 0x67, 0xE2, 0x23,// loopd 0000802Eh
/*000B*/ 0xB0, 0x02,// mov al,2
/*000D*/ 0x66, 0xE1, 0x1E,// looped 0000802Eh
/*0010*/ 0xB0, 0x03,// mov al,3
/*0012*/ 0x66, 0x67, 0xE1, 0x18,// looped 0000802Eh
/*0016*/ 0xB0, 0x04,// mov al,4
/*0018*/ 0x66, 0xE0, 0x13,// loopned 0000802Eh
/*001B*/ 0xB0, 0x05,// mov al,5
/*001D*/ 0x66, 0x67, 0xE0, 0x0D,// loopned 0000802Eh
/*0021*/ 0xB0, 0x06,// mov al,6
/*0023*/ 0x66, 0x67, 0xE3, 0x07,// jecxz 0000802Eh
/*0027*/ 0xB0, 0x07,// mov al,7
/*0029*/ 0x66, 0xE3, 0x02,// jcxz 0000802Eh
/*002C*/ 0xB0, 0x08,// mov al,8
/*002E*/ 0x90,// nop
};
var newData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0x66, 0xE2, 0x29,// loopd 0000802Dh
/*0005*/ 0xB0, 0x01,// mov al,1
/*0007*/ 0x66, 0x67, 0xE2, 0x23,// loopd 0000802Dh
/*000B*/ 0xB0, 0x02,// mov al,2
/*000D*/ 0x66, 0xE1, 0x1E,// looped 0000802Dh
/*0010*/ 0xB0, 0x03,// mov al,3
/*0012*/ 0x66, 0x67, 0xE1, 0x18,// looped 0000802Dh
/*0016*/ 0xB0, 0x04,// mov al,4
/*0018*/ 0x66, 0xE0, 0x13,// loopned 0000802Dh
/*001B*/ 0xB0, 0x05,// mov al,5
/*001D*/ 0x66, 0x67, 0xE0, 0x0D,// loopned 0000802Dh
/*0021*/ 0xB0, 0x06,// mov al,6
/*0023*/ 0x66, 0x67, 0xE3, 0x07,// jecxz 0000802Dh
/*0027*/ 0xB0, 0x07,// mov al,7
/*0029*/ 0x66, 0xE3, 0x02,// jcxz 0000802Dh
/*002C*/ 0xB0, 0x08,// mov al,8
/*002E*/ 0x90,// nop
};
var expectedInstructionOffsets = new uint[] {
0x0000,
0x0002,
0x0005,
0x0007,
0x000B,
0x000D,
0x0010,
0x0012,
0x0016,
0x0018,
0x001B,
0x001D,
0x0021,
0x0023,
0x0027,
0x0029,
0x002C,
0x002E,
};
var expectedRelocInfos = Array.Empty<RelocInfo>();
const BlockEncoderOptions options = BlockEncoderOptions.None;
EncodeBase(bitness, origRip, originalData, origRip - 1, newData, options, decoderOptions, expectedInstructionOffsets, expectedRelocInfos);
}
[Fact]
void Br8_short_other_short() {
var originalData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0xE2, 0x22,// loop 8026h
/*0004*/ 0xB0, 0x01,// mov al,1
/*0006*/ 0x67, 0xE2, 0x1D,// loop 8026h
/*0009*/ 0xB0, 0x02,// mov al,2
/*000B*/ 0xE1, 0x19,// loope 8026h
/*000D*/ 0xB0, 0x03,// mov al,3
/*000F*/ 0x67, 0xE1, 0x14,// loope 8026h
/*0012*/ 0xB0, 0x04,// mov al,4
/*0014*/ 0xE0, 0x10,// loopne 8026h
/*0016*/ 0xB0, 0x05,// mov al,5
/*0018*/ 0x67, 0xE0, 0x0B,// loopne 8026h
/*001B*/ 0xB0, 0x06,// mov al,6
/*001D*/ 0x67, 0xE3, 0x06,// jecxz 8026h
/*0020*/ 0xB0, 0x07,// mov al,7
/*0022*/ 0xE3, 0x02,// jcxz 8026h
/*0024*/ 0xB0, 0x08,// mov al,8
};
var newData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0xE2, 0x23,// loop 8026h
/*0004*/ 0xB0, 0x01,// mov al,1
/*0006*/ 0x67, 0xE2, 0x1E,// loop 8026h
/*0009*/ 0xB0, 0x02,// mov al,2
/*000B*/ 0xE1, 0x1A,// loope 8026h
/*000D*/ 0xB0, 0x03,// mov al,3
/*000F*/ 0x67, 0xE1, 0x15,// loope 8026h
/*0012*/ 0xB0, 0x04,// mov al,4
/*0014*/ 0xE0, 0x11,// loopne 8026h
/*0016*/ 0xB0, 0x05,// mov al,5
/*0018*/ 0x67, 0xE0, 0x0C,// loopne 8026h
/*001B*/ 0xB0, 0x06,// mov al,6
/*001D*/ 0x67, 0xE3, 0x07,// jecxz 8026h
/*0020*/ 0xB0, 0x07,// mov al,7
/*0022*/ 0xE3, 0x03,// jcxz 8026h
/*0024*/ 0xB0, 0x08,// mov al,8
};
var expectedInstructionOffsets = new uint[] {
0x0000,
0x0002,
0x0004,
0x0006,
0x0009,
0x000B,
0x000D,
0x000F,
0x0012,
0x0014,
0x0016,
0x0018,
0x001B,
0x001D,
0x0020,
0x0022,
0x0024,
};
var expectedRelocInfos = Array.Empty<RelocInfo>();
const BlockEncoderOptions options = BlockEncoderOptions.None;
EncodeBase(bitness, origRip, originalData, origRip - 1, newData, options, decoderOptions, expectedInstructionOffsets, expectedRelocInfos);
}
[Fact]
void Br8_short_other_near() {
var originalData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0xE2, 0x22,// loop 8026h
/*0004*/ 0xB0, 0x01,// mov al,1
/*0006*/ 0x67, 0xE2, 0x1E,// loop 8027h
/*0009*/ 0xB0, 0x02,// mov al,2
/*000B*/ 0xE1, 0x1B,// loope 8028h
/*000D*/ 0xB0, 0x03,// mov al,3
/*000F*/ 0x67, 0xE1, 0x17,// loope 8029h
/*0012*/ 0xB0, 0x04,// mov al,4
/*0014*/ 0xE0, 0x14,// loopne 802Ah
/*0016*/ 0xB0, 0x05,// mov al,5
/*0018*/ 0x67, 0xE0, 0x10,// loopne 802Bh
/*001B*/ 0xB0, 0x06,// mov al,6
/*001D*/ 0x67, 0xE3, 0x0C,// jecxz 802Ch
/*0020*/ 0xB0, 0x07,// mov al,7
/*0022*/ 0xE3, 0x09,// jcxz 802Dh
/*0024*/ 0xB0, 0x08,// mov al,8
};
var newData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0xE2, 0x02,// loop 9006h
/*0004*/ 0xEB, 0x03,// jmp short 9009h
/*0006*/ 0xE9, 0x1D, 0xF0,// jmp near ptr 8026h
/*0009*/ 0xB0, 0x01,// mov al,1
/*000B*/ 0x67, 0xE2, 0x02,// loop 9010h
/*000E*/ 0xEB, 0x03,// jmp short 9013h
/*0010*/ 0xE9, 0x14, 0xF0,// jmp near ptr 8027h
/*0013*/ 0xB0, 0x02,// mov al,2
/*0015*/ 0xE1, 0x02,// loope 9019h
/*0017*/ 0xEB, 0x03,// jmp short 901Ch
/*0019*/ 0xE9, 0x0C, 0xF0,// jmp near ptr 8028h
/*001C*/ 0xB0, 0x03,// mov al,3
/*001E*/ 0x67, 0xE1, 0x02,// loope 9023h
/*0021*/ 0xEB, 0x03,// jmp short 9026h
/*0023*/ 0xE9, 0x03, 0xF0,// jmp near ptr 8029h
/*0026*/ 0xB0, 0x04,// mov al,4
/*0028*/ 0xE0, 0x02,// loopne 902Ch
/*002A*/ 0xEB, 0x03,// jmp short 902Fh
/*002C*/ 0xE9, 0xFB, 0xEF,// jmp near ptr 802Ah
/*002F*/ 0xB0, 0x05,// mov al,5
/*0031*/ 0x67, 0xE0, 0x02,// loopne 9036h
/*0034*/ 0xEB, 0x03,// jmp short 9039h
/*0036*/ 0xE9, 0xF2, 0xEF,// jmp near ptr 802Bh
/*0039*/ 0xB0, 0x06,// mov al,6
/*003B*/ 0x67, 0xE3, 0x02,// jecxz 9040h
/*003E*/ 0xEB, 0x03,// jmp short 9043h
/*0040*/ 0xE9, 0xE9, 0xEF,// jmp near ptr 802Ch
/*0043*/ 0xB0, 0x07,// mov al,7
/*0045*/ 0xE3, 0x02,// jcxz 9049h
/*0047*/ 0xEB, 0x03,// jmp short 904Ch
/*0049*/ 0xE9, 0xE1, 0xEF,// jmp near ptr 802Dh
/*004C*/ 0xB0, 0x08,// mov al,8
};
var expectedInstructionOffsets = new uint[] {
0x0000,
uint.MaxValue,
0x0009,
uint.MaxValue,
0x0013,
uint.MaxValue,
0x001C,
uint.MaxValue,
0x0026,
uint.MaxValue,
0x002F,
uint.MaxValue,
0x0039,
uint.MaxValue,
0x0043,
uint.MaxValue,
0x004C,
};
var expectedRelocInfos = Array.Empty<RelocInfo>();
const BlockEncoderOptions options = BlockEncoderOptions.None;
EncodeBase(bitness, origRip, originalData, origRip + 0x1000, newData, options, decoderOptions, expectedInstructionOffsets, expectedRelocInfos);
}
[Fact]
void Br8_same_br() {
var originalData = new byte[] {
/*0000*/ 0xE2, 0xFE,// loop 8000h
/*0002*/ 0xE2, 0xFC,// loop 8000h
/*0004*/ 0xE2, 0xFA,// loop 8000h
};
var newData = new byte[] {
/*0000*/ 0xE2, 0xFE,// loop 8000h
/*0002*/ 0xE2, 0xFC,// loop 8000h
/*0004*/ 0xE2, 0xFA,// loop 8000h
};
var expectedInstructionOffsets = new uint[] {
0x0000,
0x0002,
0x0004,
};
var expectedRelocInfos = Array.Empty<RelocInfo>();
const BlockEncoderOptions options = BlockEncoderOptions.None;
EncodeBase(bitness, origRip, originalData, origRip, newData, options, decoderOptions, expectedInstructionOffsets, expectedRelocInfos);
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;
namespace PragmaBin {
class Program {
public class scriptNode {
public string reference = "";
public string contents = "";
public scriptNode(string reference, string content) {
this.reference = reference;
this.contents = content;
}
}
// CHANGE THIS!!!!!!!!!!!!!
public static string scriptLocation = @"D:\PragmaBin\gm.prag";
public static string scriptReturn = null;
public static string scriptLimit = null;
public static string scriptJump = null;
public static bool scriptContinue = true;
public static BinaryReader scriptBinary;
public static List<scriptNode> scriptData = new List<scriptNode>();
public static Dictionary<string, dynamic> scriptReferences = new Dictionary<string, dynamic> {
{ "execTell", 0 }
};
public static List<string> scriptCondtions = new List<string> {
"<",
">",
"<=",
">=",
"!=",
"=="
};
static void Main(string[] args) {
string[] scriptLines = File.ReadAllLines(scriptLocation);
// Gather nodes
for(int i = 0; i < scriptLines.Length; i++) { string scriptLine = scriptLines[i];
int scriptIndex = scriptMoveTo(scriptLine, ':');
if (scriptIndex > -1) {
string scriptReference = scriptLine.Substring(0, scriptIndex++ - 1).Trim(), scriptContents = scriptLine.Substring(scriptIndex, scriptLine.Length - scriptIndex).Trim(); scriptReference = scriptReference == "" ? (i + 1).ToString() : scriptReference;
scriptData.Add(new scriptNode(scriptReference, scriptContents));
}
}
// Execute nodes
for(int i = 0; i < scriptData.Count; i++) {
if (scriptContinue == true) {
// While Loop
if (scriptLimit != null) {
if (scriptData[i].reference == scriptLimit) {
for (int j = 0; j < scriptData.Count; j++) {
if (scriptData[j].reference == scriptReturn) {
i = j;
scriptLimit = null;
}
}
}
}
// Conditional Check
if (scriptJump != null) {
for(int j = 0; j < scriptData.Count; j++) {
if (scriptData[j].reference == scriptJump) {
i = j;
scriptJump = null;
}
}
}
// Execute Node
scriptNode scriptNodeRead = scriptData[i];
scriptExecute(scriptNodeRead.reference, scriptNodeRead.contents);
}
}
Console.ReadKey();
}
public static int scriptMoveTo(string scriptLine, char scriptChar, int scriptIndex = 0) {
if (scriptLine.Trim().Length == 0) { return -1; }
while (scriptLine[scriptIndex++] != scriptChar) {
if (scriptIndex >= scriptLine.Length) {
return -1;
}
}
return scriptIndex;
}
public static dynamic scriptExecute(string scriptReference, string scriptContents) {
int scriptIndex = scriptMoveTo(scriptContents, '(') - 1;
if (scriptIndex > -1) {
string scriptFunction = scriptContents.Substring(0, scriptIndex);
string[] scriptArguments = scriptContents.Substring(scriptIndex + 1, (scriptMoveTo(scriptContents, ')') - scriptIndex) - 2).Split(',').Select(i => i.Trim()).ToArray();
scriptConstants();
scriptReferences[scriptReference] = scriptExecuteFunction(scriptReference, scriptFunction, scriptArguments);
} else {
scriptReferences[scriptReference] = scriptContents;
}
return scriptReferences[scriptReference];
}
public static dynamic scriptExecuteFunction(string scriptReference, string scriptFunction, string[] scriptArguments) {
switch (scriptFunction) {
// Comparing
case "doCompare":
if (scriptCondtional(scriptArguments[0]) == false) {
scriptJump = scriptArguments[1];
}
return false;
case "doWhile":
if (scriptCondtional(scriptArguments[0]) == true) {
scriptReturn = scriptReference;
scriptLimit = scriptArguments[1];
} else {
scriptJump = scriptArguments[1];
}
return false;
// Reading
case "readByte": return scriptBinary.ReadByte();
case "readUInt16": return scriptBinary.ReadUInt16();
case "readUInt32": return scriptBinary.ReadUInt32();
case "readUInt64": return scriptBinary.ReadUInt64();
case "readSByte": return scriptBinary.ReadSByte();
case "readInt16": return scriptBinary.ReadInt16();
case "readInt32": return scriptBinary.ReadInt32();
case "readInt64": return scriptBinary.ReadInt64();
case "readChar": return Encoding.ASCII.GetString(scriptBinary.ReadBytes(1));
case "readString": return Encoding.ASCII.GetString(scriptBinary.ReadBytes(Convert.ToByte(scriptArguments[0])));
case "readBinary":
if (File.Exists(scriptArguments[0]) == true) {
scriptBinary = new BinaryReader(File.Open(scriptArguments[0], FileMode.Open));
scriptReferences["execSize"] = scriptBinary.BaseStream.Length;
} else {
Console.WriteLine("Error: [{0}]", scriptArguments[0] + " does not exist.");
scriptContinue = false;
}
return true;
// Execution
case "execPrint": Console.WriteLine("Message: [{0}]", scriptReferences[scriptArguments[0]]); return -1;
case "execMessage": return MessageBox.Show(string.Join("\n", scriptArguments));
case "execSeek":
if (scriptArguments.Length > 1) {
SeekOrigin scriptSeek = SeekOrigin.Current;
switch (scriptArguments[1]) {
case "BEGIN": scriptSeek = SeekOrigin.Begin; break;
case "END": scriptSeek = SeekOrigin.End; break;
}
scriptBinary.BaseStream.Seek(Convert.ToInt64(scriptReferences[scriptArguments[0]]), scriptSeek);
} else {
scriptBinary.BaseStream.Seek(Convert.ToInt64(scriptReferences[scriptArguments[0]]), SeekOrigin.Current);
}
return scriptBinary.BaseStream.Position;
case "execKill":
Console.WriteLine("Execution Complete: [{0}]", string.Join("\n", scriptArguments));
scriptContinue = false;
return -1;
// Unknown Function
default: Console.WriteLine("Warning: [Unknown Function: {0} ({1})]", scriptFunction, String.Join(", ", scriptArguments)); return -1;
}
}
public static bool scriptCondtional(string scriptContents) {
for(int i = 0; i < scriptContents.Length; i++) {
for(int j = 0; j < scriptCondtions.Count; j++) {
string scriptCondition = scriptCondtions[j];
if (scriptContents.Substring(i, scriptCondition.Length) == scriptCondition) {
string scriptLeft = scriptContents.Substring(0, i).Trim(), scriptRight = scriptContents.Substring(i + scriptCondition.Length).Trim();
switch (j) {
case 0: return scriptReferences[scriptLeft] < scriptReferences[scriptRight];
case 1: return scriptReferences[scriptLeft] > scriptReferences[scriptRight];
case 2: return scriptReferences[scriptLeft] <= scriptReferences[scriptRight];
case 3: return scriptReferences[scriptLeft] >= scriptReferences[scriptRight];
case 4: return scriptReferences[scriptLeft] != scriptReferences[scriptRight];
case 5: return scriptReferences[scriptLeft] == scriptReferences[scriptRight];
}
}
}
}
return false;
}
public static void scriptConstants() {
if (scriptBinary != null) {
scriptReferences["execTell"] = scriptBinary.BaseStream.Position;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Cosmos.Build.Common;
using Cosmos.VS.Package;
using Microsoft.VisualBasic;
using DebugMode = Cosmos.Build.Common.DebugMode;
namespace Cosmos.VS.ProjectSystem.PropertyPages
{
// We put all items on ONE form because VS is such a C++ developers wet dream to manage mulitple pages
// and add new ones.
// We use our own profiles instead of Project Configrations because:
// -Couldnt find a proper way to tell VS there are no configuration independent pages. The MPF way (as well as
// 0 sized array) both don't work.
// -When we assign our own project configuration types and the solution configurations refer to now non existent
// project configurations, there are errors.
//
// BOTH of the above probably could be solved with some digging. BUT in the end we learned that project configs
// really wont do what we want. For the user to change the active config for a *single* project they would need
// to change it manually in the solution config, or maintain on solution config for every project config type.
// Maintaining so many solution configs is not only impractical but causes a whole bunch of other issues.
//
// So instead we keep our own list of profiles, and when the user selects them we write out a copy of its values
// to the active configuration (all since we are not configuration dependent) for MSBuild and other code to use.
[Guid(Guids.guidCosmosPropertyPageString)]
public partial class CosmosPage : CustomPropertyPage
{
protected class ProfileItem
{
public string Prefix;
public string Name;
public bool IsPreset;
public override string ToString()
{
return Name;
}
}
protected ProfilePresets mPresets = new ProfilePresets();
protected int mVMwareAndBochsDebugPipe;
protected int mHyperVDebugPipe;
protected bool mShowTabBochs;
protected bool mShowTabDebug;
protected bool mShowTabDeployment;
protected bool mShowTabLaunch;
protected bool mShowTabVMware;
protected bool mShowTabHyperV;
protected bool mShowTabPXE;
protected bool mShowTabUSB;
protected bool mShowTabISO;
protected bool mShowTabSlave;
protected bool FreezeEvents;
public CosmosPage()
{
InitializeComponent();
# region Profile
butnProfileClone.Click += new EventHandler(butnProfileClone_Click);
butnProfileDelete.Click += new EventHandler(butnProfileDelete_Click);
butnProfileRename.Click += new EventHandler(butnProfileRename_Click);
lboxProfile.SelectedIndexChanged += delegate (Object sender, EventArgs e)
{
var xProfile = (ProfileItem)lboxProfile.SelectedItem;
if (xProfile.Prefix != mProps.Profile)
{
// Save existing profile
mProps.SaveProfile(mProps.Profile);
// Load newly selected profile
mProps.LoadProfile(xProfile.Prefix);
mProps.Profile = xProfile.Prefix;
IsDirty = true;
UpdateUI();
}
};
#endregion
# region Deploy
lboxDeployment.SelectedIndexChanged += delegate (Object sender, EventArgs e)
{
var xValue = (DeploymentType)((EnumValue)lboxDeployment.SelectedItem).Value;
if (xValue != mProps.Deployment)
{
mProps.Deployment = xValue;
IsDirty = true;
}
};
#endregion
# region Launch
lboxLaunch.SelectedIndexChanged += delegate (Object sender, EventArgs e)
{
var xValue = (LaunchType)((EnumValue)lboxLaunch.SelectedItem).Value;
if (xValue != mProps.Launch)
{
mProps.Launch = xValue;
IsDirty = true;
// Bochs requires an ISO. Force Deployment property.
if (LaunchType.Bochs == xValue)
{
if (DeploymentType.ISO != mProps.Deployment)
{
foreach (EnumValue scannedValue in lboxDeployment.Items)
{
if (DeploymentType.ISO == (DeploymentType)scannedValue.Value)
{
lboxDeployment.SelectedItem = scannedValue;
break;
}
}
}
}
}
};
#endregion
#region Compile
comboFramework.SelectedIndexChanged += delegate (Object sender, EventArgs e)
{
if (FreezeEvents) return;
var value = (Framework)((EnumValue)comboFramework.SelectedItem).Value;
if (value != mProps.Framework)
{
mProps.Framework = value;
IsDirty = true;
}
};
comboBinFormat.SelectedIndexChanged += delegate (Object sender, EventArgs e)
{
if (FreezeEvents) return;
var value = (BinFormat)((EnumValue)comboBinFormat.SelectedItem).Value;
if (value != mProps.BinFormat)
{
mProps.BinFormat = value;
IsDirty = true;
}
};
textOutputPath.TextChanged += delegate (Object sender, EventArgs e)
{
if (FreezeEvents) return;
string value = textOutputPath.Text;
if (!string.Equals(value, mProps.OutputPath, StringComparison.InvariantCultureIgnoreCase))
{
mProps.OutputPath = textOutputPath.Text;
IsDirty = true;
}
};
#endregion
#region Assembler
checkUseInternalAssembler.CheckedChanged += delegate (Object sender, EventArgs e)
{
if (FreezeEvents) return;
bool value = checkUseInternalAssembler.Checked;
if (value != mProps.UseInternalAssembler)
{
mProps.UseInternalAssembler = value;
IsDirty = true;
}
};
#endregion
#region VMware
cmboVMwareEdition.SelectedIndexChanged += delegate (Object sender, EventArgs e)
{
if (FreezeEvents) return;
var x = (VMwareEdition)((EnumValue)cmboVMwareEdition.SelectedItem).Value;
if (x != mProps.VMwareEdition)
{
mProps.VMwareEdition = x;
IsDirty = true;
}
};
#endregion
#region PXE
comboPxeInterface.TextChanged += delegate (Object sender, EventArgs e)
{
if (FreezeEvents) return;
var x = comboPxeInterface.Text.Trim();
if (x != mProps.PxeInterface)
{
mProps.PxeInterface = x;
IsDirty = true;
}
};
cmboSlavePort.SelectedIndexChanged += delegate (Object sender, EventArgs e)
{
if (FreezeEvents) return;
var x = (string)cmboSlavePort.SelectedItem;
if (x != mProps.SlavePort)
{
mProps.SlavePort = x;
IsDirty = true;
}
};
butnPxeRefresh.Click += new EventHandler(butnPxeRefresh_Click);
#endregion
#region Debug
comboDebugMode.SelectedIndexChanged += delegate (Object sender, EventArgs e)
{
if (FreezeEvents) return;
var x = (Cosmos.Build.Common.DebugMode)((EnumValue)comboDebugMode.SelectedItem).Value;
if (x != mProps.DebugMode)
{
mProps.DebugMode = x;
IsDirty = true;
}
};
chckEnableDebugStub.CheckedChanged += delegate (object aSender, EventArgs e)
{
if (FreezeEvents) return;
panlDebugSettings.Enabled = chckEnableDebugStub.Checked;
mProps.DebugEnabled = chckEnableDebugStub.Checked;
IsDirty = true;
};
comboTraceMode.SelectedIndexChanged += delegate (Object sender, EventArgs e)
{
if (FreezeEvents) return;
var x = (TraceAssemblies)((EnumValue)comboTraceMode.SelectedItem).Value;
if (x != mProps.TraceAssemblies)
{
mProps.TraceAssemblies = x;
IsDirty = true;
}
};
checkIgnoreDebugStubAttribute.CheckedChanged += delegate (Object sender, EventArgs e)
{
if (FreezeEvents) return;
bool x = checkIgnoreDebugStubAttribute.Checked;
if (x != mProps.IgnoreDebugStubAttribute)
{
mProps.IgnoreDebugStubAttribute = x;
IsDirty = true;
}
};
cmboCosmosDebugPort.SelectedIndexChanged += delegate (Object sender, EventArgs e)
{
if (FreezeEvents) return;
var x = (string)cmboCosmosDebugPort.SelectedItem;
if (x != mProps.CosmosDebugPort)
{
mProps.CosmosDebugPort = x;
IsDirty = true;
}
};
cmboVisualStudioDebugPort.SelectedIndexChanged += delegate (Object sender, EventArgs e)
{
if (FreezeEvents) return;
var x = (string)cmboVisualStudioDebugPort.SelectedItem;
if (x != mProps.VisualStudioDebugPort)
{
mProps.VisualStudioDebugPort = x;
IsDirty = true;
}
};
checkEnableGDB.CheckedChanged += delegate (Object sender, EventArgs e)
{
if (FreezeEvents) return;
bool x = checkEnableGDB.Checked;
if (x != mProps.EnableGDB)
{
mProps.EnableGDB = x;
IsDirty = true;
}
checkStartCosmosGDB.Enabled = x;
checkStartCosmosGDB.Checked = x;
};
checkStartCosmosGDB.CheckedChanged += delegate (Object sender, EventArgs e)
{
if (FreezeEvents) return;
bool x = checkStartCosmosGDB.Checked;
if (x != mProps.StartCosmosGDB)
{
mProps.StartCosmosGDB = x;
IsDirty = true;
}
};
checkEnableBochsDebug.CheckedChanged += delegate (Object sender, EventArgs e)
{
if (FreezeEvents) return;
bool x = checkEnableBochsDebug.Checked;
if (x != mProps.EnableBochsDebug)
{
mProps.EnableBochsDebug = x;
IsDirty = true;
}
checkStartBochsDebugGui.Enabled = x;
if (x == false)
{
checkStartBochsDebugGui.Checked = x;
}
};
checkStartBochsDebugGui.CheckedChanged += delegate (object sender, EventArgs e)
{
if (FreezeEvents) return;
bool x = checkStartBochsDebugGui.Checked;
if (x != mProps.StartBochsDebugGui)
{
mProps.StartBochsDebugGui = x;
IsDirty = true;
}
};
#endregion
}
public override void ApplyChanges()
{
// Save now, because when we reload this form it will
// reload out of the saved profile and trash any changes
// in the active area.
mProps.SaveProfile(mProps.Profile);
base.ApplyChanges();
}
protected void RemoveTab(TabPage aTab)
{
if (TabControl1.TabPages.Contains(aTab))
{
TabControl1.TabPages.Remove(aTab);
}
}
protected void UpdateTabs()
{
var xTab = TabControl1.SelectedTab;
RemoveTab(tabDebug);
RemoveTab(tabDeployment);
RemoveTab(tabLaunch);
RemoveTab(tabVMware);
RemoveTab(tabHyperV);
RemoveTab(tabPXE);
RemoveTab(tabUSB);
RemoveTab(tabISO);
RemoveTab(tabSlave);
RemoveTab(tabBochs);
if (mShowTabDebug)
{
TabControl1.TabPages.Add(tabDebug);
}
if (mShowTabDeployment)
{
TabControl1.TabPages.Add(tabDeployment);
}
if (mShowTabPXE)
{
TabControl1.TabPages.Add(tabPXE);
}
if (mShowTabUSB)
{
TabControl1.TabPages.Add(tabUSB);
}
if (mShowTabISO)
{
TabControl1.TabPages.Add(tabISO);
}
if (mShowTabLaunch)
{
TabControl1.TabPages.Add(tabLaunch);
}
if (mShowTabVMware)
{
TabControl1.TabPages.Add(tabVMware);
}
if (mShowTabHyperV)
{
TabControl1.TabPages.Add(tabHyperV);
}
if (mShowTabSlave)
{
TabControl1.TabPages.Add(tabSlave);
}
if (mShowTabBochs)
{
TabControl1.TabPages.Add(tabBochs);
}
if (TabControl1.TabPages.Contains(xTab))
{
TabControl1.SelectedTab = xTab;
}
else
{
TabControl1.SelectedTab = tabProfile;
}
}
protected void UpdatePresetsUI()
{
FreezeEvents = true;
mShowTabDebug = true;
cmboCosmosDebugPort.Enabled = true;
cmboVisualStudioDebugPort.Enabled = true;
if (mProps.Profile == "ISO")
{
mShowTabDebug = false;
}
else if (mProps.Profile == "USB")
{
mShowTabDebug = false;
mShowTabUSB = true;
}
else if (mProps.Profile == "VMware")
{
mShowTabVMware = true;
chckEnableDebugStub.Checked = true;
chkEnableStackCorruptionDetection.Checked = true;
cmboCosmosDebugPort.Enabled = false;
cmboVisualStudioDebugPort.Enabled = false;
cmboVisualStudioDebugPort.SelectedIndex = mVMwareAndBochsDebugPipe;
}
else if (mProps.Profile == "HyperV")
{
mShowTabHyperV = true;
chckEnableDebugStub.Checked = true;
chkEnableStackCorruptionDetection.Checked = true;
cmboCosmosDebugPort.Enabled = false;
cmboVisualStudioDebugPort.Enabled = false;
cmboVisualStudioDebugPort.SelectedIndex = mHyperVDebugPipe;
}
else if (mProps.Profile == "PXE")
{
chckEnableDebugStub.Checked = false;
}
else if (mProps.Profile == "Bochs")
{
mShowTabBochs = true;
chckEnableDebugStub.Checked = true;
chkEnableStackCorruptionDetection.Checked = true;
cmboCosmosDebugPort.Enabled = false;
cmboVisualStudioDebugPort.Enabled = false;
cmboVisualStudioDebugPort.SelectedIndex = mVMwareAndBochsDebugPipe;
}
else if (mProps.Profile == "IntelEdison")
{
mShowTabBochs = false;
mShowTabVMware = false;
cmboVisualStudioDebugPort.Enabled = false;
}
FreezeEvents = false;
}
protected void UpdateUI()
{
UpdatePresetsUI();
var xProfile = (ProfileItem)lboxProfile.SelectedItem;
if (xProfile == null)
{
return;
}
if (mShowTabDebug == false)
{
chckEnableDebugStub.Checked = false;
}
lablCurrentProfile.Text = xProfile.Name;
lablDeployText.Text = mProps.Description;
lboxDeployment.SelectedItem = mProps.Deployment;
// Launch
lboxLaunch.SelectedItem = mProps.Launch;
lablBuildOnly.Visible = mProps.Launch == LaunchType.None;
lboxDeployment.SelectedItem = EnumValue.Find(lboxDeployment.Items, mProps.Deployment);
lboxLaunch.SelectedItem = EnumValue.Find(lboxLaunch.Items, mProps.Launch);
cmboVMwareEdition.SelectedItem = EnumValue.Find(cmboVMwareEdition.Items, mProps.VMwareEdition);
chckEnableDebugStub.Checked = mProps.DebugEnabled;
chkEnableStackCorruptionDetection.Checked = mProps.StackCorruptionDetectionEnabled;
comboStackCorruptionDetectionLevel.SelectedItem = EnumValue.Find(comboStackCorruptionDetectionLevel.Items, mProps.StackCorruptionDetectionLevel);
panlDebugSettings.Enabled = mProps.DebugEnabled;
cmboCosmosDebugPort.SelectedIndex = cmboCosmosDebugPort.Items.IndexOf(mProps.CosmosDebugPort);
if (!String.IsNullOrWhiteSpace(mProps.VisualStudioDebugPort))
{
cmboVisualStudioDebugPort.SelectedIndex =
cmboVisualStudioDebugPort.Items.IndexOf(mProps.VisualStudioDebugPort);
}
textOutputPath.Text = mProps.OutputPath;
comboFramework.SelectedItem = EnumValue.Find(comboFramework.Items, mProps.Framework);
comboBinFormat.SelectedItem = EnumValue.Find(comboBinFormat.Items, mProps.BinFormat);
checkUseInternalAssembler.Checked = mProps.UseInternalAssembler;
checkEnableGDB.Checked = mProps.EnableGDB;
checkStartCosmosGDB.Checked = mProps.StartCosmosGDB;
checkEnableBochsDebug.Checked = mProps.EnableBochsDebug;
checkStartBochsDebugGui.Checked = mProps.StartBochsDebugGui;
// Locked to COM1 for now.
//cmboCosmosDebugPort.SelectedIndex = 0;
#region Slave
cmboSlavePort.SelectedIndex = cmboSlavePort.Items.IndexOf(mProps.SlavePort);
#endregion
checkIgnoreDebugStubAttribute.Checked = mProps.IgnoreDebugStubAttribute;
comboDebugMode.SelectedItem = EnumValue.Find(comboDebugMode.Items, mProps.DebugMode);
comboTraceMode.SelectedItem = EnumValue.Find(comboTraceMode.Items, mProps.TraceAssemblies);
lablPreset.Visible = xProfile.IsPreset;
mShowTabDeployment = !xProfile.IsPreset;
mShowTabLaunch = !xProfile.IsPreset;
//
mShowTabISO = mProps.Deployment == DeploymentType.ISO;
mShowTabUSB = mProps.Deployment == DeploymentType.USB;
mShowTabPXE = mProps.Deployment == DeploymentType.PXE;
//
mShowTabVMware = mProps.Launch == LaunchType.VMware;
mShowTabHyperV = mProps.Launch == LaunchType.HyperV;
mShowTabSlave = mProps.Launch == LaunchType.Slave;
mShowTabBochs = (LaunchType.Bochs == mProps.Launch);
//
UpdateTabs();
}
protected int FillProfile(string aPrefix, string aName)
{
var xProfile = new ProfileItem { Prefix = aPrefix, Name = aName, IsPreset = true };
return lboxProfile.Items.Add(xProfile);
}
protected int FillProfile(int aID)
{
var xProfile = new ProfileItem { Prefix = "User" + aID.ToString("000"), IsPreset = false };
xProfile.Name = mProps.GetProperty(xProfile.Prefix + "_Name");
return lboxProfile.Items.Add(xProfile);
}
protected void FillProfiles()
{
lboxProfile.Items.Clear();
foreach (var xPreset in mPresets)
{
FillProfile(xPreset.Key, xPreset.Value);
}
for (int i = 1; i < 100; i++)
{
if (!string.IsNullOrEmpty(mProps.GetProperty("User" + i.ToString("000") + "_Name")))
{
FillProfile(i);
}
}
}
void butnProfileRename_Click(object sender, EventArgs e)
{
var xItem = (ProfileItem)lboxProfile.SelectedItem;
if (xItem == null)
{
// This should be impossible, but we check for it anwyays.
}
else if (xItem.IsPreset)
{
MessageBox.Show("Preset profiles cannot be renamed.");
}
else
{
string xName = Interaction.InputBox("Profile Name", "Rename Profile", mProps.Name);
if (xName != "")
{
IsDirty = true;
mProps.Name = xName;
xItem.Name = xName;
typeof(ListBox).InvokeMember(
"RefreshItems",
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod,
null,
lboxProfile,
new object[] { });
}
}
}
void butnProfileDelete_Click(object sender, EventArgs e)
{
var xItem = (ProfileItem)lboxProfile.SelectedItem;
if (xItem == null)
{
// This should be impossible, but we check for it anwyays.
}
else if (xItem.IsPreset)
{
MessageBox.Show("Preset profiles cannot be deleted.");
}
else if (MessageBox.Show("Delete profile '" + xItem.Name + "'?", "", MessageBoxButtons.YesNo)
== DialogResult.Yes)
{
IsDirty = true;
// Select a new profile first, so the selectchange logic wont barf
lboxProfile.SelectedIndex = 0;
lboxProfile.Items.Remove(xItem);
mProps.DeleteProfile(xItem.Prefix);
}
}
void butnProfileClone_Click(object sender, EventArgs e)
{
var xItem = (ProfileItem)lboxProfile.SelectedItem;
if (xItem == null)
{
// This should be impossible, but we check for it anwyays.
return;
}
int xID;
string xPrefix = null;
for (xID = 1; xID < 100; xID++)
{
xPrefix = "User" + xID.ToString("000");
if (mProps.GetProperty(xPrefix + "_Name") == "")
{
break;
}
}
if (xID == 100)
{
MessageBox.Show("No more profile space is available.");
return;
}
IsDirty = true;
mProps.Name = xItem.Prefix + " User " + xID.ToString("000");
mProps.Description = "";
mProps.SaveProfile(xPrefix);
lboxProfile.SelectedIndex = FillProfile(xID);
}
void butnPxeRefresh_Click(object sender, EventArgs e)
{
FillNetworkInterfaces();
}
protected BuildProperties mProps = new BuildProperties();
public override PropertiesBase Properties
{
get
{
return mProps;
}
}
/// <summary>
/// Load project independent properties.
/// </summary>
protected void LoadProjectProps()
{
foreach (var propertyName in mProps.ProjectIndependentProperties)
{
var propertyValue = ProjectMgr.GetProjectProperty(propertyName);
mProps.SetProperty(propertyName, propertyValue);
}
}
/// <summary>
/// Load properties for the given profile.
/// </summary>
/// <param name="aPrefix">Name of the profile for which load properties.</param>
protected void LoadProfileProps(string aPrefix)
{
string xPrefix = aPrefix + (aPrefix == "" ? "" : "_");
foreach (var xName in BuildProperties.PropNames)
{
if (!mProps.ProjectIndependentProperties.Contains(xName))
{
string xValue = ProjectConfigs[0].GetConfigurationProperty(xPrefix + xName, false);
// This is important that we dont copy empty values, so instead the defaults will be used.
if (!string.IsNullOrWhiteSpace(xValue))
{
mProps.SetProperty(xPrefix + xName, xValue);
}
}
}
}
protected void LoadProps()
{
// Load mProps from project config file.
// The reason for loading into mProps seems to be so we can track changes, and cancel if necessary.
mProps.Reset();
// Reset cache only on first one
// Get selected profile
mProps.SetProperty(
BuildPropertyNames.ProfileString,
ProjectConfigs[0].GetConfigurationProperty(BuildPropertyNames.ProfileString, true));
LoadProjectProps();
// Load selected profile props
LoadProfileProps("");
foreach (var xPreset in mPresets)
{
LoadProfileProps(xPreset.Key);
}
for (int i = 1; i < 100; i++)
{
string xPrefix = "User" + i.ToString("000");
if (!string.IsNullOrWhiteSpace(ProjectConfigs[0].GetConfigurationProperty(xPrefix + "_Name", false)))
{
LoadProfileProps(xPrefix);
}
}
}
protected override void FillProperties()
{
base.FillProperties();
LoadProps();
FillProfiles();
foreach (ProfileItem xItem in lboxProfile.Items)
{
if (xItem.Prefix == mProps.Profile)
{
lboxProfile.SelectedItem = xItem;
break;
}
}
lboxDeployment.Items.AddRange(EnumValue.GetEnumValues(typeof(DeploymentType), true));
comboFramework.Items.AddRange(EnumValue.GetEnumValues(typeof(Framework), true));
comboBinFormat.Items.AddRange(EnumValue.GetEnumValues(typeof(BinFormat), true));
lboxLaunch.Items.AddRange(EnumValue.GetEnumValues(typeof(LaunchType), true));
#region VMware
cmboVMwareEdition.Items.AddRange(EnumValue.GetEnumValues(typeof(VMwareEdition), true));
#endregion
#region Debug
cmboCosmosDebugPort.Items.Clear();
FillComPorts(cmboCosmosDebugPort.Items);
cmboVisualStudioDebugPort.Items.Clear();
FillComPorts(cmboVisualStudioDebugPort.Items);
mVMwareAndBochsDebugPipe = cmboVisualStudioDebugPort.Items.Add(@"Pipe: Cosmos\Serial");
mHyperVDebugPipe = cmboVisualStudioDebugPort.Items.Add(@"Pipe: CosmosSerial");
comboDebugMode.Items.AddRange(EnumValue.GetEnumValues(typeof(DebugMode), false));
comboTraceMode.Items.AddRange(EnumValue.GetEnumValues(typeof(TraceAssemblies), false));
comboStackCorruptionDetectionLevel.Items.AddRange(EnumValue.GetEnumValues(typeof(StackCorruptionDetectionLevel), true));
#endregion
#region PXE
FillNetworkInterfaces();
cmboSlavePort.Items.Clear();
cmboSlavePort.Items.Add("None");
FillComPorts(cmboSlavePort.Items);
#endregion
UpdateUI();
}
protected void FillComPorts(System.Collections.IList aList)
{
//TODO http://stackoverflow.com/questions/2937585/how-to-open-a-serial-port-by-friendly-name
foreach (string xPort in SerialPort.GetPortNames())
{
aList.Add("Serial: " + xPort);
}
}
protected void FillNetworkInterfaces()
{
comboPxeInterface.Items.Clear();
comboPxeInterface.Items.AddRange(GetNetworkInterfaces().ToArray());
if (mProps.PxeInterface == String.Empty)
{
if (comboPxeInterface.Items.Count > 0)
{
comboPxeInterface.Text = comboPxeInterface.Items[0].ToString();
}
else
{
comboPxeInterface.Text = "192.168.42.1";
}
}
else
{
comboPxeInterface.Text = mProps.PxeInterface;
}
}
protected List<string> GetNetworkInterfaces()
{
NetworkInterface[] nInterfaces = NetworkInterface.GetAllNetworkInterfaces();
List<string> interfaces_list = new List<string>();
foreach (NetworkInterface nInterface in nInterfaces)
{
if (nInterface.OperationalStatus == OperationalStatus.Up)
{
IPInterfaceProperties ipProperties = nInterface.GetIPProperties();
foreach (var ip in ipProperties.UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
interfaces_list.Add(ip.Address.ToString());
}
}
}
}
return interfaces_list;
}
private void OutputBrowse_Click(object sender, EventArgs e)
{
string folderPath = String.Empty;
var dialog = new FolderBrowserDialog();
dialog.ShowNewFolderButton = true;
folderPath = textOutputPath.Text;
if ((String.IsNullOrEmpty(folderPath) == false)
&& (folderPath.IndexOfAny(System.IO.Path.GetInvalidPathChars()) == -1))
{
if (System.IO.Path.IsPathRooted(folderPath) == false)
{
folderPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Project.FullName), folderPath);
}
while ((System.IO.Directory.Exists(folderPath) == false) && (String.IsNullOrEmpty(folderPath) == false))
{
int index = -1;
index =
folderPath.IndexOfAny(
new Char[] { System.IO.Path.PathSeparator, System.IO.Path.AltDirectorySeparatorChar });
if (index > -1)
{
folderPath = folderPath.Substring(0, index - 1);
}
else
{
folderPath = String.Empty;
}
}
if (String.IsNullOrEmpty(folderPath) == true)
{
folderPath = System.IO.Path.GetDirectoryName(Project.FullName);
}
}
else
{
folderPath = System.IO.Path.GetDirectoryName(Project.FullName);
}
dialog.SelectedPath = folderPath;
dialog.Description = "Select build output path";
if (dialog.ShowDialog() == DialogResult.OK)
{
textOutputPath.Text = dialog.SelectedPath;
}
}
private void chkEnableStacckCorruptionDetection_CheckedChanged(object sender, EventArgs e)
{
if (!FreezeEvents)
{
IsDirty = true;
mProps.StackCorruptionDetectionEnabled = chkEnableStackCorruptionDetection.Checked;
comboStackCorruptionDetectionLevel.Enabled = mProps.StackCorruptionDetectionEnabled;
}
}
private void stackCorruptionDetectionLevelComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (!FreezeEvents)
{
var x = (StackCorruptionDetectionLevel)((EnumValue) comboStackCorruptionDetectionLevel.SelectedItem).Value;
if (x != mProps.StackCorruptionDetectionLevel)
{
mProps.StackCorruptionDetectionLevel = x;
IsDirty = true;
}
}
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Cluster.Codecs {
public class NewLeadershipTermEventDecoder
{
public const ushort BLOCK_LENGTH = 48;
public const ushort TEMPLATE_ID = 24;
public const ushort SCHEMA_ID = 111;
public const ushort SCHEMA_VERSION = 7;
private NewLeadershipTermEventDecoder _parentMessage;
private IDirectBuffer _buffer;
protected int _offset;
protected int _limit;
protected int _actingBlockLength;
protected int _actingVersion;
public NewLeadershipTermEventDecoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public NewLeadershipTermEventDecoder Wrap(
IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion)
{
this._buffer = buffer;
this._offset = offset;
this._actingBlockLength = actingBlockLength;
this._actingVersion = actingVersion;
Limit(offset + actingBlockLength);
return this;
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int LeadershipTermIdId()
{
return 1;
}
public static int LeadershipTermIdSinceVersion()
{
return 0;
}
public static int LeadershipTermIdEncodingOffset()
{
return 0;
}
public static int LeadershipTermIdEncodingLength()
{
return 8;
}
public static string LeadershipTermIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long LeadershipTermIdNullValue()
{
return -9223372036854775808L;
}
public static long LeadershipTermIdMinValue()
{
return -9223372036854775807L;
}
public static long LeadershipTermIdMaxValue()
{
return 9223372036854775807L;
}
public long LeadershipTermId()
{
return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian);
}
public static int LogPositionId()
{
return 2;
}
public static int LogPositionSinceVersion()
{
return 0;
}
public static int LogPositionEncodingOffset()
{
return 8;
}
public static int LogPositionEncodingLength()
{
return 8;
}
public static string LogPositionMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long LogPositionNullValue()
{
return -9223372036854775808L;
}
public static long LogPositionMinValue()
{
return -9223372036854775807L;
}
public static long LogPositionMaxValue()
{
return 9223372036854775807L;
}
public long LogPosition()
{
return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian);
}
public static int TimestampId()
{
return 3;
}
public static int TimestampSinceVersion()
{
return 0;
}
public static int TimestampEncodingOffset()
{
return 16;
}
public static int TimestampEncodingLength()
{
return 8;
}
public static string TimestampMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long TimestampNullValue()
{
return -9223372036854775808L;
}
public static long TimestampMinValue()
{
return -9223372036854775807L;
}
public static long TimestampMaxValue()
{
return 9223372036854775807L;
}
public long Timestamp()
{
return _buffer.GetLong(_offset + 16, ByteOrder.LittleEndian);
}
public static int TermBaseLogPositionId()
{
return 4;
}
public static int TermBaseLogPositionSinceVersion()
{
return 0;
}
public static int TermBaseLogPositionEncodingOffset()
{
return 24;
}
public static int TermBaseLogPositionEncodingLength()
{
return 8;
}
public static string TermBaseLogPositionMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long TermBaseLogPositionNullValue()
{
return -9223372036854775808L;
}
public static long TermBaseLogPositionMinValue()
{
return -9223372036854775807L;
}
public static long TermBaseLogPositionMaxValue()
{
return 9223372036854775807L;
}
public long TermBaseLogPosition()
{
return _buffer.GetLong(_offset + 24, ByteOrder.LittleEndian);
}
public static int LeaderMemberIdId()
{
return 5;
}
public static int LeaderMemberIdSinceVersion()
{
return 0;
}
public static int LeaderMemberIdEncodingOffset()
{
return 32;
}
public static int LeaderMemberIdEncodingLength()
{
return 4;
}
public static string LeaderMemberIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int LeaderMemberIdNullValue()
{
return -2147483648;
}
public static int LeaderMemberIdMinValue()
{
return -2147483647;
}
public static int LeaderMemberIdMaxValue()
{
return 2147483647;
}
public int LeaderMemberId()
{
return _buffer.GetInt(_offset + 32, ByteOrder.LittleEndian);
}
public static int LogSessionIdId()
{
return 6;
}
public static int LogSessionIdSinceVersion()
{
return 0;
}
public static int LogSessionIdEncodingOffset()
{
return 36;
}
public static int LogSessionIdEncodingLength()
{
return 4;
}
public static string LogSessionIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int LogSessionIdNullValue()
{
return -2147483648;
}
public static int LogSessionIdMinValue()
{
return -2147483647;
}
public static int LogSessionIdMaxValue()
{
return 2147483647;
}
public int LogSessionId()
{
return _buffer.GetInt(_offset + 36, ByteOrder.LittleEndian);
}
public static int TimeUnitId()
{
return 7;
}
public static int TimeUnitSinceVersion()
{
return 4;
}
public static int TimeUnitEncodingOffset()
{
return 40;
}
public static int TimeUnitEncodingLength()
{
return 4;
}
public static string TimeUnitMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "optional";
}
return "";
}
public ClusterTimeUnit TimeUnit()
{
if (_actingVersion < 4) return ClusterTimeUnit.NULL_VALUE;
return (ClusterTimeUnit)_buffer.GetInt(_offset + 40, ByteOrder.LittleEndian);
}
public static int AppVersionId()
{
return 8;
}
public static int AppVersionSinceVersion()
{
return 4;
}
public static int AppVersionEncodingOffset()
{
return 44;
}
public static int AppVersionEncodingLength()
{
return 4;
}
public static string AppVersionMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "optional";
}
return "";
}
public static int AppVersionNullValue()
{
return 0;
}
public static int AppVersionMinValue()
{
return 1;
}
public static int AppVersionMaxValue()
{
return 16777215;
}
public int AppVersion()
{
return _buffer.GetInt(_offset + 44, ByteOrder.LittleEndian);
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
int originalLimit = Limit();
Limit(_offset + _actingBlockLength);
builder.Append("[NewLeadershipTermEvent](sbeTemplateId=");
builder.Append(TEMPLATE_ID);
builder.Append("|sbeSchemaId=");
builder.Append(SCHEMA_ID);
builder.Append("|sbeSchemaVersion=");
if (_parentMessage._actingVersion != SCHEMA_VERSION)
{
builder.Append(_parentMessage._actingVersion);
builder.Append('/');
}
builder.Append(SCHEMA_VERSION);
builder.Append("|sbeBlockLength=");
if (_actingBlockLength != BLOCK_LENGTH)
{
builder.Append(_actingBlockLength);
builder.Append('/');
}
builder.Append(BLOCK_LENGTH);
builder.Append("):");
//Token{signal=BEGIN_FIELD, name='leadershipTermId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("LeadershipTermId=");
builder.Append(LeadershipTermId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='logPosition', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("LogPosition=");
builder.Append(LogPosition());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='timestamp', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='time_t', referencedName='null', description='Epoch time since 1 Jan 1970 UTC.', id=-1, version=0, deprecated=0, encodedLength=8, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("Timestamp=");
builder.Append(Timestamp());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='termBaseLogPosition', referencedName='null', description='null', id=4, version=0, deprecated=0, encodedLength=0, offset=24, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=24, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("TermBaseLogPosition=");
builder.Append(TermBaseLogPosition());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='leaderMemberId', referencedName='null', description='null', id=5, version=0, deprecated=0, encodedLength=0, offset=32, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=32, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("LeaderMemberId=");
builder.Append(LeaderMemberId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='logSessionId', referencedName='null', description='null', id=6, version=0, deprecated=0, encodedLength=0, offset=36, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=36, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("LogSessionId=");
builder.Append(LogSessionId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='timeUnit', referencedName='null', description='null', id=7, version=4, deprecated=0, encodedLength=0, offset=40, componentTokenCount=7, encoding=Encoding{presence=OPTIONAL, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=BEGIN_ENUM, name='ClusterTimeUnit', referencedName='null', description='Type the time unit used for timestamps.', id=-1, version=4, deprecated=0, encodedLength=4, offset=40, componentTokenCount=5, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='null', timeUnit=null, semanticType='null'}}
builder.Append("TimeUnit=");
builder.Append(TimeUnit());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='appVersion', referencedName='null', description='null', id=8, version=4, deprecated=0, encodedLength=0, offset=44, componentTokenCount=3, encoding=Encoding{presence=OPTIONAL, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='version_t', referencedName='null', description='Protocol or application suite version.', id=-1, version=0, deprecated=0, encodedLength=4, offset=44, componentTokenCount=1, encoding=Encoding{presence=OPTIONAL, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=1, maxValue=16777215, nullValue=0, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("AppVersion=");
builder.Append(AppVersion());
Limit(originalLimit);
return builder;
}
}
}
| |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
/*
* $Id: Inflate.cs,v 1.2 2008-05-10 09:35:40 bouncy Exp $
*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
namespace Org.BouncyCastle.Utilities.Zlib {
internal sealed class Inflate{
private const int MAX_WBITS=15; // 32K LZ77 window
// preset dictionary flag in zlib header
private const int PRESET_DICT=0x20;
internal const int Z_NO_FLUSH=0;
internal const int Z_PARTIAL_FLUSH=1;
internal const int Z_SYNC_FLUSH=2;
internal const int Z_FULL_FLUSH=3;
internal const int Z_FINISH=4;
private const int Z_DEFLATED=8;
private const int Z_OK=0;
private const int Z_STREAM_END=1;
private const int Z_NEED_DICT=2;
private const int Z_ERRNO=-1;
private const int Z_STREAM_ERROR=-2;
private const int Z_DATA_ERROR=-3;
private const int Z_MEM_ERROR=-4;
private const int Z_BUF_ERROR=-5;
private const int Z_VERSION_ERROR=-6;
private const int METHOD=0; // waiting for method byte
private const int FLAG=1; // waiting for flag byte
private const int DICT4=2; // four dictionary check bytes to go
private const int DICT3=3; // three dictionary check bytes to go
private const int DICT2=4; // two dictionary check bytes to go
private const int DICT1=5; // one dictionary check byte to go
private const int DICT0=6; // waiting for inflateSetDictionary
private const int BLOCKS=7; // decompressing blocks
private const int CHECK4=8; // four check bytes to go
private const int CHECK3=9; // three check bytes to go
private const int CHECK2=10; // two check bytes to go
private const int CHECK1=11; // one check byte to go
private const int DONE=12; // finished check, done
private const int BAD=13; // got an error--stay here
internal int mode; // current inflate mode
// mode dependent information
internal int method; // if FLAGS, method byte
// if CHECK, check values to compare
internal long[] was=new long[1] ; // computed check value
internal long need; // stream check value
// if BAD, inflateSync's marker bytes count
internal int marker;
// mode independent information
internal int nowrap; // flag for no wrapper
internal int wbits; // log2(window size) (8..15, defaults to 15)
internal InfBlocks blocks; // current inflate_blocks state
internal int inflateReset(ZStream z){
if(z == null || z.istate == null) return Z_STREAM_ERROR;
z.total_in = z.total_out = 0;
z.msg = null;
z.istate.mode = z.istate.nowrap!=0 ? BLOCKS : METHOD;
z.istate.blocks.reset(z, null);
return Z_OK;
}
internal int inflateEnd(ZStream z){
if(blocks != null)
blocks.free(z);
blocks=null;
// ZFREE(z, z->state);
return Z_OK;
}
internal int inflateInit(ZStream z, int w){
z.msg = null;
blocks = null;
// handle undocumented nowrap option (no zlib header or check)
nowrap = 0;
if(w < 0){
w = - w;
nowrap = 1;
}
// set window size
if(w<8 ||w>15){
inflateEnd(z);
return Z_STREAM_ERROR;
}
wbits=w;
z.istate.blocks=new InfBlocks(z,
z.istate.nowrap!=0 ? null : this,
1<<w);
// reset state
inflateReset(z);
return Z_OK;
}
internal int inflate(ZStream z, int f){
int r;
int b;
if(z == null || z.istate == null || z.next_in == null)
return Z_STREAM_ERROR;
f = f == Z_FINISH ? Z_BUF_ERROR : Z_OK;
r = Z_BUF_ERROR;
while (true){
//System.out.println("mode: "+z.istate.mode);
switch (z.istate.mode){
case METHOD:
if(z.avail_in==0)return r;r=f;
z.avail_in--; z.total_in++;
if(((z.istate.method = z.next_in[z.next_in_index++])&0xf)!=Z_DEFLATED){
z.istate.mode = BAD;
z.msg="unknown compression method";
z.istate.marker = 5; // can't try inflateSync
break;
}
if((z.istate.method>>4)+8>z.istate.wbits){
z.istate.mode = BAD;
z.msg="invalid window size";
z.istate.marker = 5; // can't try inflateSync
break;
}
z.istate.mode=FLAG;
goto case FLAG;
case FLAG:
if(z.avail_in==0)return r;r=f;
z.avail_in--; z.total_in++;
b = (z.next_in[z.next_in_index++])&0xff;
if((((z.istate.method << 8)+b) % 31)!=0){
z.istate.mode = BAD;
z.msg = "incorrect header check";
z.istate.marker = 5; // can't try inflateSync
break;
}
if((b&PRESET_DICT)==0){
z.istate.mode = BLOCKS;
break;
}
z.istate.mode = DICT4;
goto case DICT4;
case DICT4:
if(z.avail_in==0)return r;r=f;
z.avail_in--; z.total_in++;
z.istate.need=((z.next_in[z.next_in_index++]&0xff)<<24)&0xff000000L;
z.istate.mode=DICT3;
goto case DICT3;
case DICT3:
if(z.avail_in==0)return r;r=f;
z.avail_in--; z.total_in++;
z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<16)&0xff0000L;
z.istate.mode=DICT2;
goto case DICT2;
case DICT2:
if(z.avail_in==0)return r;r=f;
z.avail_in--; z.total_in++;
z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<8)&0xff00L;
z.istate.mode=DICT1;
goto case DICT1;
case DICT1:
if(z.avail_in==0)return r;r=f;
z.avail_in--; z.total_in++;
z.istate.need += (z.next_in[z.next_in_index++]&0xffL);
z.adler = z.istate.need;
z.istate.mode = DICT0;
return Z_NEED_DICT;
case DICT0:
z.istate.mode = BAD;
z.msg = "need dictionary";
z.istate.marker = 0; // can try inflateSync
return Z_STREAM_ERROR;
case BLOCKS:
r = z.istate.blocks.proc(z, r);
if(r == Z_DATA_ERROR){
z.istate.mode = BAD;
z.istate.marker = 0; // can try inflateSync
break;
}
if(r == Z_OK){
r = f;
}
if(r != Z_STREAM_END){
return r;
}
r = f;
z.istate.blocks.reset(z, z.istate.was);
if(z.istate.nowrap!=0){
z.istate.mode=DONE;
break;
}
z.istate.mode=CHECK4;
goto case CHECK4;
case CHECK4:
if(z.avail_in==0)return r;r=f;
z.avail_in--; z.total_in++;
z.istate.need=((z.next_in[z.next_in_index++]&0xff)<<24)&0xff000000L;
z.istate.mode=CHECK3;
goto case CHECK3;
case CHECK3:
if(z.avail_in==0)return r;r=f;
z.avail_in--; z.total_in++;
z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<16)&0xff0000L;
z.istate.mode = CHECK2;
goto case CHECK2;
case CHECK2:
if(z.avail_in==0)return r;r=f;
z.avail_in--; z.total_in++;
z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<8)&0xff00L;
z.istate.mode = CHECK1;
goto case CHECK1;
case CHECK1:
if(z.avail_in==0)return r;r=f;
z.avail_in--; z.total_in++;
z.istate.need+=(z.next_in[z.next_in_index++]&0xffL);
if(((int)(z.istate.was[0])) != ((int)(z.istate.need))){
z.istate.mode = BAD;
z.msg = "incorrect data check";
z.istate.marker = 5; // can't try inflateSync
break;
}
z.istate.mode = DONE;
goto case DONE;
case DONE:
return Z_STREAM_END;
case BAD:
return Z_DATA_ERROR;
default:
return Z_STREAM_ERROR;
}
}
}
internal int inflateSetDictionary(ZStream z, byte[] dictionary, int dictLength){
int index=0;
int length = dictLength;
if(z==null || z.istate == null|| z.istate.mode != DICT0)
return Z_STREAM_ERROR;
if(z._adler.adler32(1L, dictionary, 0, dictLength)!=z.adler){
return Z_DATA_ERROR;
}
z.adler = z._adler.adler32(0, null, 0, 0);
if(length >= (1<<z.istate.wbits)){
length = (1<<z.istate.wbits)-1;
index=dictLength - length;
}
z.istate.blocks.set_dictionary(dictionary, index, length);
z.istate.mode = BLOCKS;
return Z_OK;
}
private static readonly byte[] mark = {(byte)0, (byte)0, (byte)0xff, (byte)0xff};
internal int inflateSync(ZStream z){
int n; // number of bytes to look at
int p; // pointer to bytes
int m; // number of marker bytes found in a row
long r, w; // temporaries to save total_in and total_out
// set up
if(z == null || z.istate == null)
return Z_STREAM_ERROR;
if(z.istate.mode != BAD){
z.istate.mode = BAD;
z.istate.marker = 0;
}
if((n=z.avail_in)==0)
return Z_BUF_ERROR;
p=z.next_in_index;
m=z.istate.marker;
// search
while (n!=0 && m < 4){
if(z.next_in[p] == mark[m]){
m++;
}
else if(z.next_in[p]!=0){
m = 0;
}
else{
m = 4 - m;
}
p++; n--;
}
// restore
z.total_in += p-z.next_in_index;
z.next_in_index = p;
z.avail_in = n;
z.istate.marker = m;
// return no joy or set up to restart on a new block
if(m != 4){
return Z_DATA_ERROR;
}
r=z.total_in; w=z.total_out;
inflateReset(z);
z.total_in=r; z.total_out = w;
z.istate.mode = BLOCKS;
return Z_OK;
}
// Returns true if inflate is currently at the end of a block generated
// by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
// implementation to provide an additional safety check. PPP uses Z_SYNC_FLUSH
// but removes the length bytes of the resulting empty stored block. When
// decompressing, PPP checks that at the end of input packet, inflate is
// waiting for these length bytes.
internal int inflateSyncPoint(ZStream z){
if(z == null || z.istate == null || z.istate.blocks == null)
return Z_STREAM_ERROR;
return z.istate.blocks.sync_point();
}
}
}
#endif
| |
using ICSharpCode.SharpZipLib.Core;
using System;
using System.IO;
using System.Text;
namespace ICSharpCode.SharpZipLib.Zip
{
/// <summary>
/// WindowsNameTransform transforms <see cref="ZipFile"/> names to windows compatible ones.
/// </summary>
public class WindowsNameTransform : INameTransform
{
/// <summary>
/// The maximum windows path name permitted.
/// </summary>
/// <remarks>This may not valid for all windows systems - CE?, etc but I cant find the equivalent in the CLR.</remarks>
private const int MaxPath = 260;
private string _baseDirectory;
private bool _trimIncomingPaths;
private char _replacementChar = '_';
private bool _allowParentTraversal;
/// <summary>
/// In this case we need Windows' invalid path characters.
/// Path.GetInvalidPathChars() only returns a subset invalid on all platforms.
/// </summary>
private static readonly char[] InvalidEntryChars = new char[] {
'"', '<', '>', '|', '\0', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005',
'\u0006', '\a', '\b', '\t', '\n', '\v', '\f', '\r', '\u000e', '\u000f',
'\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016',
'\u0017', '\u0018', '\u0019', '\u001a', '\u001b', '\u001c', '\u001d',
'\u001e', '\u001f',
// extra characters for masks, etc.
'*', '?', ':'
};
/// <summary>
/// Initialises a new instance of <see cref="WindowsNameTransform"/>
/// </summary>
/// <param name="baseDirectory"></param>
/// <param name="allowParentTraversal">Allow parent directory traversal in file paths (e.g. ../file)</param>
public WindowsNameTransform(string baseDirectory, bool allowParentTraversal = false)
{
BaseDirectory = baseDirectory ?? throw new ArgumentNullException(nameof(baseDirectory), "Directory name is invalid");
AllowParentTraversal = allowParentTraversal;
}
/// <summary>
/// Initialise a default instance of <see cref="WindowsNameTransform"/>
/// </summary>
public WindowsNameTransform()
{
// Do nothing.
}
/// <summary>
/// Gets or sets a value containing the target directory to prefix values with.
/// </summary>
public string BaseDirectory
{
get { return _baseDirectory; }
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_baseDirectory = Path.GetFullPath(value);
}
}
/// <summary>
/// Allow parent directory traversal in file paths (e.g. ../file)
/// </summary>
public bool AllowParentTraversal
{
get => _allowParentTraversal;
set => _allowParentTraversal = value;
}
/// <summary>
/// Gets or sets a value indicating wether paths on incoming values should be removed.
/// </summary>
public bool TrimIncomingPaths
{
get { return _trimIncomingPaths; }
set { _trimIncomingPaths = value; }
}
/// <summary>
/// Transform a Zip directory name to a windows directory name.
/// </summary>
/// <param name="name">The directory name to transform.</param>
/// <returns>The transformed name.</returns>
public string TransformDirectory(string name)
{
name = TransformFile(name);
if (name.Length > 0)
{
while (name.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal))
{
name = name.Remove(name.Length - 1, 1);
}
}
else
{
throw new InvalidNameException("Cannot have an empty directory name");
}
return name;
}
/// <summary>
/// Transform a Zip format file name to a windows style one.
/// </summary>
/// <param name="name">The file name to transform.</param>
/// <returns>The transformed name.</returns>
public string TransformFile(string name)
{
if (name != null)
{
name = MakeValidName(name, _replacementChar);
if (_trimIncomingPaths)
{
name = Path.GetFileName(name);
}
// This may exceed windows length restrictions.
// Combine will throw a PathTooLongException in that case.
if (_baseDirectory != null)
{
name = Path.Combine(_baseDirectory, name);
if (!_allowParentTraversal && !Path.GetFullPath(name).StartsWith(_baseDirectory, StringComparison.InvariantCultureIgnoreCase))
{
throw new InvalidNameException("Parent traversal in paths is not allowed");
}
}
}
else
{
name = string.Empty;
}
return name;
}
/// <summary>
/// Test a name to see if it is a valid name for a windows filename as extracted from a Zip archive.
/// </summary>
/// <param name="name">The name to test.</param>
/// <returns>Returns true if the name is a valid zip name; false otherwise.</returns>
/// <remarks>The filename isnt a true windows path in some fundamental ways like no absolute paths, no rooted paths etc.</remarks>
public static bool IsValidName(string name)
{
bool result =
(name != null) &&
(name.Length <= MaxPath) &&
(string.Compare(name, MakeValidName(name, '_'), StringComparison.Ordinal) == 0)
;
return result;
}
/// <summary>
/// Force a name to be valid by replacing invalid characters with a fixed value
/// </summary>
/// <param name="name">The name to make valid</param>
/// <param name="replacement">The replacement character to use for any invalid characters.</param>
/// <returns>Returns a valid name</returns>
public static string MakeValidName(string name, char replacement)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
name = WindowsPathUtils.DropPathRoot(name.Replace("/", Path.DirectorySeparatorChar.ToString()));
// Drop any leading slashes.
while ((name.Length > 0) && (name[0] == Path.DirectorySeparatorChar))
{
name = name.Remove(0, 1);
}
// Drop any trailing slashes.
while ((name.Length > 0) && (name[name.Length - 1] == Path.DirectorySeparatorChar))
{
name = name.Remove(name.Length - 1, 1);
}
// Convert consecutive \\ characters to \
int index = name.IndexOf(string.Format("{0}{0}", Path.DirectorySeparatorChar), StringComparison.Ordinal);
while (index >= 0)
{
name = name.Remove(index, 1);
index = name.IndexOf(string.Format("{0}{0}", Path.DirectorySeparatorChar), StringComparison.Ordinal);
}
// Convert any invalid characters using the replacement one.
index = name.IndexOfAny(InvalidEntryChars);
if (index >= 0)
{
var builder = new StringBuilder(name);
while (index >= 0)
{
builder[index] = replacement;
if (index >= name.Length)
{
index = -1;
}
else
{
index = name.IndexOfAny(InvalidEntryChars, index + 1);
}
}
name = builder.ToString();
}
// Check for names greater than MaxPath characters.
// TODO: Were is CLR version of MaxPath defined? Can't find it in Environment.
if (name.Length > MaxPath)
{
throw new PathTooLongException();
}
return name;
}
/// <summary>
/// Gets or set the character to replace invalid characters during transformations.
/// </summary>
public char Replacement
{
get { return _replacementChar; }
set
{
for (int i = 0; i < InvalidEntryChars.Length; ++i)
{
if (InvalidEntryChars[i] == value)
{
throw new ArgumentException("invalid path character");
}
}
if ((value == Path.DirectorySeparatorChar) || (value == Path.AltDirectorySeparatorChar))
{
throw new ArgumentException("invalid replacement character");
}
_replacementChar = 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.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Internal;
namespace System.Reflection.Metadata.Ecma335
{
public sealed class ControlFlowBuilder
{
// internal for testing:
internal readonly struct BranchInfo
{
internal readonly int ILOffset;
internal readonly LabelHandle Label;
private readonly byte _opCode;
internal ILOpCode OpCode => (ILOpCode)_opCode;
internal BranchInfo(int ilOffset, LabelHandle label, ILOpCode opCode)
{
ILOffset = ilOffset;
Label = label;
_opCode = (byte)opCode;
}
internal bool IsShortBranchDistance(ImmutableArray<int>.Builder labels, out int distance)
{
const int shortBranchSize = 2;
const int longBranchSize = 5;
int labelTargetOffset = labels[Label.Id - 1];
if (labelTargetOffset < 0)
{
Throw.InvalidOperation_LabelNotMarked(Label.Id);
}
distance = labelTargetOffset - (ILOffset + shortBranchSize);
if (unchecked((sbyte)distance) == distance)
{
return true;
}
distance = labelTargetOffset - (ILOffset + longBranchSize);
return false;
}
}
internal readonly struct ExceptionHandlerInfo
{
public readonly ExceptionRegionKind Kind;
public readonly LabelHandle TryStart, TryEnd, HandlerStart, HandlerEnd, FilterStart;
public readonly EntityHandle CatchType;
public ExceptionHandlerInfo(
ExceptionRegionKind kind,
LabelHandle tryStart,
LabelHandle tryEnd,
LabelHandle handlerStart,
LabelHandle handlerEnd,
LabelHandle filterStart,
EntityHandle catchType)
{
Kind = kind;
TryStart = tryStart;
TryEnd = tryEnd;
HandlerStart = handlerStart;
HandlerEnd = handlerEnd;
FilterStart = filterStart;
CatchType = catchType;
}
}
private readonly ImmutableArray<BranchInfo>.Builder _branches;
private readonly ImmutableArray<int>.Builder _labels;
private ImmutableArray<ExceptionHandlerInfo>.Builder _lazyExceptionHandlers;
public ControlFlowBuilder()
{
_branches = ImmutableArray.CreateBuilder<BranchInfo>();
_labels = ImmutableArray.CreateBuilder<int>();
}
internal void Clear()
{
_branches.Clear();
_labels.Clear();
_lazyExceptionHandlers?.Clear();
}
internal LabelHandle AddLabel()
{
_labels.Add(-1);
return new LabelHandle(_labels.Count);
}
internal void AddBranch(int ilOffset, LabelHandle label, ILOpCode opCode)
{
Debug.Assert(ilOffset >= 0);
Debug.Assert(_branches.Count == 0 || ilOffset > _branches.Last().ILOffset);
ValidateLabel(label, nameof(label));
_branches.Add(new BranchInfo(ilOffset, label, opCode));
}
internal void MarkLabel(int ilOffset, LabelHandle label)
{
Debug.Assert(ilOffset >= 0);
ValidateLabel(label, nameof(label));
_labels[label.Id - 1] = ilOffset;
}
private int GetLabelOffsetChecked(LabelHandle label)
{
int offset = _labels[label.Id - 1];
if (offset < 0)
{
Throw.InvalidOperation_LabelNotMarked(label.Id);
}
return offset;
}
private void ValidateLabel(LabelHandle label, string parameterName)
{
if (label.IsNil)
{
Throw.ArgumentNull(parameterName);
}
if (label.Id > _labels.Count)
{
Throw.LabelDoesntBelongToBuilder(parameterName);
}
}
/// <summary>
/// Adds finally region.
/// </summary>
/// <param name="tryStart">Label marking the first instruction of the try block.</param>
/// <param name="tryEnd">Label marking the instruction immediately following the try block.</param>
/// <param name="handlerStart">Label marking the first instruction of the handler.</param>
/// <param name="handlerEnd">Label marking the instruction immediately following the handler.</param>
/// <returns>Encoder for the next clause.</returns>
/// <exception cref="ArgumentException">A label was not defined by an instruction encoder this builder is associated with.</exception>
/// <exception cref="ArgumentNullException">A label has default value.</exception>
public void AddFinallyRegion(LabelHandle tryStart, LabelHandle tryEnd, LabelHandle handlerStart, LabelHandle handlerEnd) =>
AddExceptionRegion(ExceptionRegionKind.Finally, tryStart, tryEnd, handlerStart, handlerEnd);
/// <summary>
/// Adds fault region.
/// </summary>
/// <param name="tryStart">Label marking the first instruction of the try block.</param>
/// <param name="tryEnd">Label marking the instruction immediately following the try block.</param>
/// <param name="handlerStart">Label marking the first instruction of the handler.</param>
/// <param name="handlerEnd">Label marking the instruction immediately following the handler.</param>
/// <exception cref="ArgumentException">A label was not defined by an instruction encoder this builder is associated with.</exception>
/// <exception cref="ArgumentNullException">A label has default value.</exception>
public void AddFaultRegion(LabelHandle tryStart, LabelHandle tryEnd, LabelHandle handlerStart, LabelHandle handlerEnd) =>
AddExceptionRegion(ExceptionRegionKind.Fault, tryStart, tryEnd, handlerStart, handlerEnd);
/// <summary>
/// Adds catch region.
/// </summary>
/// <param name="tryStart">Label marking the first instruction of the try block.</param>
/// <param name="tryEnd">Label marking the instruction immediately following the try block.</param>
/// <param name="handlerStart">Label marking the first instruction of the handler.</param>
/// <param name="handlerEnd">Label marking the instruction immediately following the handler.</param>
/// <param name="catchType">The type of exception to be caught: <see cref="TypeDefinitionHandle"/>, <see cref="TypeReferenceHandle"/> or <see cref="TypeSpecificationHandle"/>.</param>
/// <exception cref="ArgumentException">A label was not defined by an instruction encoder this builder is associated with.</exception>
/// <exception cref="ArgumentException"><paramref name="catchType"/> is not a valid type handle.</exception>
/// <exception cref="ArgumentNullException">A label has default value.</exception>
public void AddCatchRegion(LabelHandle tryStart, LabelHandle tryEnd, LabelHandle handlerStart, LabelHandle handlerEnd, EntityHandle catchType)
{
if (!ExceptionRegionEncoder.IsValidCatchTypeHandle(catchType))
{
Throw.InvalidArgument_Handle(nameof(catchType));
}
AddExceptionRegion(ExceptionRegionKind.Catch, tryStart, tryEnd, handlerStart, handlerEnd, catchType: catchType);
}
/// <summary>
/// Adds catch region.
/// </summary>
/// <param name="tryStart">Label marking the first instruction of the try block.</param>
/// <param name="tryEnd">Label marking the instruction immediately following the try block.</param>
/// <param name="handlerStart">Label marking the first instruction of the handler.</param>
/// <param name="handlerEnd">Label marking the instruction immediately following the handler.</param>
/// <param name="filterStart">Label marking the first instruction of the filter block.</param>
/// <exception cref="ArgumentException">A label was not defined by an instruction encoder this builder is associated with.</exception>
/// <exception cref="ArgumentNullException">A label has default value.</exception>
public void AddFilterRegion(LabelHandle tryStart, LabelHandle tryEnd, LabelHandle handlerStart, LabelHandle handlerEnd, LabelHandle filterStart)
{
ValidateLabel(filterStart, nameof(filterStart));
AddExceptionRegion(ExceptionRegionKind.Filter, tryStart, tryEnd, handlerStart, handlerEnd, filterStart: filterStart);
}
private void AddExceptionRegion(
ExceptionRegionKind kind,
LabelHandle tryStart,
LabelHandle tryEnd,
LabelHandle handlerStart,
LabelHandle handlerEnd,
LabelHandle filterStart = default(LabelHandle),
EntityHandle catchType = default(EntityHandle))
{
ValidateLabel(tryStart, nameof(tryStart));
ValidateLabel(tryEnd, nameof(tryEnd));
ValidateLabel(handlerStart, nameof(handlerStart));
ValidateLabel(handlerEnd, nameof(handlerEnd));
if (_lazyExceptionHandlers == null)
{
_lazyExceptionHandlers = ImmutableArray.CreateBuilder<ExceptionHandlerInfo>();
}
_lazyExceptionHandlers.Add(new ExceptionHandlerInfo(kind, tryStart, tryEnd, handlerStart, handlerEnd, filterStart, catchType));
}
// internal for testing:
internal IEnumerable<BranchInfo> Branches => _branches;
// internal for testing:
internal IEnumerable<int> Labels => _labels;
internal int BranchCount => _branches.Count;
internal int ExceptionHandlerCount => _lazyExceptionHandlers?.Count ?? 0;
/// <exception cref="InvalidOperationException" />
internal void CopyCodeAndFixupBranches(BlobBuilder srcBuilder, BlobBuilder dstBuilder)
{
var branch = _branches[0];
int branchIndex = 0;
// offset within the source builder
int srcOffset = 0;
// current offset within the current source blob
int srcBlobOffset = 0;
foreach (Blob srcBlob in srcBuilder.GetBlobs())
{
Debug.Assert(
srcBlobOffset == 0 ||
srcBlobOffset == 1 && srcBlob.Buffer[0] == 0xff ||
srcBlobOffset == 4 && srcBlob.Buffer[0] == 0xff && srcBlob.Buffer[1] == 0xff && srcBlob.Buffer[2] == 0xff && srcBlob.Buffer[3] == 0xff);
while (true)
{
// copy bytes preceding the next branch, or till the end of the blob:
int chunkSize = Math.Min(branch.ILOffset - srcOffset, srcBlob.Length - srcBlobOffset);
dstBuilder.WriteBytes(srcBlob.Buffer, srcBlobOffset, chunkSize);
srcOffset += chunkSize;
srcBlobOffset += chunkSize;
// there is no branch left in the blob:
if (srcBlobOffset == srcBlob.Length)
{
srcBlobOffset = 0;
break;
}
Debug.Assert(srcBlob.Buffer[srcBlobOffset] == (byte)branch.OpCode);
int operandSize = branch.OpCode.GetBranchOperandSize();
bool isShortInstruction = operandSize == 1;
// Note: the 4B operand is contiguous since we wrote it via BlobBuilder.WriteInt32()
Debug.Assert(
srcBlobOffset + 1 == srcBlob.Length ||
(isShortInstruction ?
srcBlob.Buffer[srcBlobOffset + 1] == 0xff :
BitConverter.ToUInt32(srcBlob.Buffer, srcBlobOffset + 1) == 0xffffffff));
// write branch opcode:
dstBuilder.WriteByte(srcBlob.Buffer[srcBlobOffset]);
// write branch operand:
int branchDistance;
bool isShortDistance = branch.IsShortBranchDistance(_labels, out branchDistance);
if (isShortInstruction && !isShortDistance)
{
// We could potentially implement algortihm that automatically fixes up the branch instructions as well to accomodate bigger distances,
// however an optimal algorithm would be rather complex (something like: calculate topological ordering of crossing branch instructions
// and then use fixed point to eliminate cycles). If the caller doesn't care about optimal IL size they can use long branches whenever the
// distance is unknown upfront. If they do they probably already implement more sophisticad algorithm for IL layout optimization already.
throw new InvalidOperationException(SR.Format(SR.DistanceBetweenInstructionAndLabelTooBig, branch.OpCode, srcOffset, branchDistance));
}
if (isShortInstruction)
{
dstBuilder.WriteSByte((sbyte)branchDistance);
}
else
{
dstBuilder.WriteInt32(branchDistance);
}
srcOffset += sizeof(byte) + operandSize;
// next branch:
branchIndex++;
if (branchIndex == _branches.Count)
{
branch = new BranchInfo(int.MaxValue, default(LabelHandle), 0);
}
else
{
branch = _branches[branchIndex];
}
// the branch starts at the very end and its operand is in the next blob:
if (srcBlobOffset == srcBlob.Length - 1)
{
srcBlobOffset = operandSize;
break;
}
// skip fake branch instruction:
srcBlobOffset += sizeof(byte) + operandSize;
}
}
}
internal void SerializeExceptionTable(BlobBuilder builder)
{
if (_lazyExceptionHandlers == null || _lazyExceptionHandlers.Count == 0)
{
return;
}
var regionEncoder = ExceptionRegionEncoder.SerializeTableHeader(builder, _lazyExceptionHandlers.Count, HasSmallExceptionRegions());
foreach (var handler in _lazyExceptionHandlers)
{
// Note that labels have been validated when added to the handler list,
// they might not have been marked though.
int tryStart = GetLabelOffsetChecked(handler.TryStart);
int tryEnd = GetLabelOffsetChecked(handler.TryEnd);
int handlerStart = GetLabelOffsetChecked(handler.HandlerStart);
int handlerEnd = GetLabelOffsetChecked(handler.HandlerEnd);
if (tryStart > tryEnd)
{
Throw.InvalidOperation(SR.Format(SR.InvalidExceptionRegionBounds, tryStart, tryEnd));
}
if (handlerStart > handlerEnd)
{
Throw.InvalidOperation(SR.Format(SR.InvalidExceptionRegionBounds, handlerStart, handlerEnd));
}
int catchTokenOrOffset;
switch (handler.Kind)
{
case ExceptionRegionKind.Catch:
catchTokenOrOffset = MetadataTokens.GetToken(handler.CatchType);
break;
case ExceptionRegionKind.Filter:
catchTokenOrOffset = GetLabelOffsetChecked(handler.FilterStart);
break;
default:
catchTokenOrOffset = 0;
break;
}
regionEncoder.AddUnchecked(
handler.Kind,
tryStart,
tryEnd - tryStart,
handlerStart,
handlerEnd - handlerStart,
catchTokenOrOffset);
}
}
private bool HasSmallExceptionRegions()
{
Debug.Assert(_lazyExceptionHandlers != null);
if (!ExceptionRegionEncoder.IsSmallRegionCount(_lazyExceptionHandlers.Count))
{
return false;
}
foreach (var handler in _lazyExceptionHandlers)
{
if (!ExceptionRegionEncoder.IsSmallExceptionRegionFromBounds(GetLabelOffsetChecked(handler.TryStart), GetLabelOffsetChecked(handler.TryEnd)) ||
!ExceptionRegionEncoder.IsSmallExceptionRegionFromBounds(GetLabelOffsetChecked(handler.HandlerStart), GetLabelOffsetChecked(handler.HandlerEnd)))
{
return false;
}
}
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using RecommendationSystem.Entities;
namespace RecommendationSystem.Data
{
public static class RatingPreprocessor
{
#region Extensions
#region Users
#region Normalize
public static void Normalize(this IEnumerable<IUser> users)
{
foreach (var user in users)
{
var max = user.Ratings.Max(rating => rating.Value);
foreach (var rating in user.Ratings)
rating.Value /= max;
}
}
#endregion
#region LogNormalize
public static void LogNormalize(this IEnumerable<IUser> users)
{
foreach (var user in users)
{
var max = (float)user.Ratings.Max(rating => Math.Log(rating.Value));
foreach (var rating in user.Ratings)
rating.Value = (float)Math.Log(rating.Value) / max;
}
}
#endregion
#region ConvertRatingsToEqualFrequencyFiveScale
public static void ConvertRatingsToEqualFrequencyFiveScale(this IEnumerable<IUser> users)
{
foreach (var user in users)
{
user.Ratings = user.Ratings.OrderByDescending(rating => rating.Value).ToList();
for (var i = 0; i < user.Ratings.Count; i++)
user.Ratings[i].Value = 5 - i * 5 / user.Ratings.Count;
}
}
#endregion
#region ConvertRatingsToEqualWidthFiveScale
public static void ConvertRatingsToEqualWidthFiveScale(this IEnumerable<IUser> users)
{
foreach (var user in users)
{
var min = user.Ratings.Min(rating => rating.Value);
var width = user.Ratings.Max(rating => rating.Value) - min;
foreach (var rating in user.Ratings)
rating.Value = GetEqualWidthRating(min, width, rating.Value);
}
}
#endregion
#region ConvertRatingsToLogEqualWidthFiveScale
public static void ConvertRatingsToLogEqualWidthFiveScale(this IEnumerable<IUser> users)
{
foreach (var user in users)
{
var min = (float)user.Ratings.Min(rating => Math.Log(rating.Value));
var width = (float)user.Ratings.Max(rating => Math.Log(rating.Value)) - min;
foreach (var rating in user.Ratings)
rating.Value = GetEqualWidthRating(min, width, (float)Math.Log(rating.Value));
}
}
#endregion
#endregion
#region Ratings
#region Normalize
public static void Normalize(this List<IRating> ratings)
{
var userCount = ratings.Select(rating => rating.UserIndex).Distinct().Count();
ratings.Normalize(userCount);
}
public static void Normalize(this List<IRating> ratings, int userCount)
{
var users = GroupRatingsByUsers(ratings, userCount);
foreach (var userRatings in users)
{
var max = userRatings.Max(rating => rating.Value);
foreach (var rating in userRatings)
rating.Value /= max;
}
}
#endregion
#region LogNormalize
public static void LogNormalize(this List<IRating> ratings)
{
var userCount = ratings.Select(rating => rating.UserIndex).Distinct().Count();
ratings.Normalize(userCount);
}
public static void LogNormalize(this List<IRating> ratings, int userCount)
{
var users = GroupRatingsByUsers(ratings, userCount);
foreach (var userRatings in users)
{
var max = (float)userRatings.Max(rating => Math.Log(rating.Value));
foreach (var rating in userRatings)
rating.Value = (float)Math.Log(rating.Value) / max;
}
}
#endregion
#region ConvertToEqualFrequencyFiveScale
public static void ConvertToEqualFrequencyFiveScale(this List<IRating> ratings)
{
var userCount = ratings.Select(rating => rating.UserIndex).Distinct().Count();
ratings.ConvertToEqualFrequencyFiveScale(userCount);
}
public static void ConvertToEqualFrequencyFiveScale(this List<IRating> ratings, int userCount)
{
var users = GroupRatingsByUsers(ratings, userCount);
foreach (var userRatings in users.Select(user => user.OrderByDescending(rating => rating.Value).ToList()))
{
for (var i = 0; i < userRatings.Count; i++)
userRatings[i].Value = 5 - i * 5 / userRatings.Count;
}
}
#endregion
#region EqualWidth
public static void ConvertToEqualWidthFiveScale(this List<IRating> ratings)
{
var userCount = ratings.Select(rating => rating.UserIndex).Distinct().Count();
ratings.ConvertToEqualWidthFiveScale(userCount);
}
public static void ConvertToEqualWidthFiveScale(this List<IRating> ratings, int userCount)
{
var users = GroupRatingsByUsers(ratings, userCount);
foreach (var userRatings in users)
{
var min = userRatings.Min(rating => rating.Value);
var width = userRatings.Max(rating => rating.Value) - min;
foreach (var rating in userRatings)
rating.Value = GetEqualWidthRating(min, width, rating.Value);
}
}
#endregion
#region ConvertToLogEqualWidthFiveScale
public static void ConvertToLogEqualWidthFiveScale(this List<IRating> ratings)
{
var userCount = ratings.Select(rating => rating.UserIndex).Distinct().Count();
ratings.ConvertToLogEqualWidthFiveScale(userCount);
}
public static void ConvertToLogEqualWidthFiveScale(this List<IRating> ratings, int userCount)
{
var users = GroupRatingsByUsers(ratings, userCount);
foreach (var userRatings in users)
{
var min = (float)userRatings.Min(rating => Math.Log(rating.Value));
var width = (float)userRatings.Max(rating => Math.Log(rating.Value)) - min;
foreach (var rating in userRatings)
rating.Value = GetEqualWidthRating(min, width, (float)Math.Log(rating.Value));
}
}
#endregion
#endregion
#endregion
#region Helpers
#region GetEqualWidthRating
private static float GetEqualWidthRating(float min, float width, float rating)
{
if (rating < width / 5.0 + min)
return 1.0f;
if (rating < width * 2.0 / 5.0 + min)
return 2.0f;
if (rating < width * 3.0 / 5.0 + min)
return 3.0f;
if (rating < width * 4.0 / 5.0 + min)
return 4.0f;
return 5.0f;
}
#endregion
#region GroupRatingsByUsers
private static IEnumerable<List<IRating>> GroupRatingsByUsers(IEnumerable<IRating> ratings, int userCount)
{
var users = new List<IRating>[userCount];
for (var i = 0; i < userCount; i++)
users[i] = new List<IRating>();
foreach (var rating in ratings)
users[rating.UserIndex].Add(rating);
return users;
}
#endregion
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Orleans;
using Orleans.Hosting;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.TestingHost;
using TestExtensions;
using UnitTests.TestHelper;
using Xunit;
using Xunit.Sdk;
namespace UnitTests.General
{
public class ConsistentRingProviderTests_Silo : TestClusterPerTest
{
private const int numAdditionalSilos = 3;
private readonly TimeSpan failureTimeout = TimeSpan.FromSeconds(30);
private readonly TimeSpan endWait = TimeSpan.FromMinutes(5);
enum Fail { First, Random, Last }
public ClusterConfiguration ClusterConfiguration { get; set; }
protected override void ConfigureTestCluster(TestClusterBuilder builder)
{
builder.ConfigureLegacyConfiguration(legacy =>
{
this.ClusterConfiguration = legacy.ClusterConfiguration;
});
builder.AddSiloBuilderConfigurator<SiloConfigurator>();
}
private class SiloConfigurator : ISiloBuilderConfigurator
{
public void Configure(ISiloHostBuilder hostBuilder)
{
hostBuilder.AddMemoryGrainStorage("MemoryStore")
.AddMemoryGrainStorageAsDefault();
}
}
#region Tests
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_Basic()
{
await this.HostedCluster.StartAdditionalSilos(numAdditionalSilos);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
VerificationScenario(0);
}
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_1F_Random()
{
await FailureTest(Fail.Random, 1);
}
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_1F_Beginning()
{
await FailureTest(Fail.First, 1);
}
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_1F_End()
{
await FailureTest(Fail.Last, 1);
}
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_2F_Random()
{
await FailureTest(Fail.Random, 2);
}
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_2F_Beginning()
{
await FailureTest(Fail.First, 2);
}
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_2F_End()
{
await FailureTest(Fail.Last, 2);
}
private async Task FailureTest(Fail failCode, int numOfFailures)
{
await this.HostedCluster.StartAdditionalSilos(numAdditionalSilos);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
List<SiloHandle> failures = await getSilosToFail(failCode, numOfFailures);
foreach (SiloHandle fail in failures) // verify before failure
{
VerificationScenario(PickKey(fail.SiloAddress)); // fail.SiloAddress.GetConsistentHashCode());
}
logger.Info("FailureTest {0}, Code {1}, Stopping silos: {2}", numOfFailures, failCode, Utils.EnumerableToString(failures, handle => handle.SiloAddress.ToString()));
List<uint> keysToTest = new List<uint>();
foreach (SiloHandle fail in failures) // verify before failure
{
keysToTest.Add(PickKey(fail.SiloAddress)); //fail.SiloAddress.GetConsistentHashCode());
this.HostedCluster.StopSilo(fail);
}
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
AssertEventually(() =>
{
foreach (var key in keysToTest) // verify after failure
{
VerificationScenario(key);
}
}, failureTimeout);
}
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_1J()
{
await JoinTest(1);
}
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_2J()
{
await JoinTest(2);
}
private async Task JoinTest(int numOfJoins)
{
logger.Info("JoinTest {0}", numOfJoins);
await this.HostedCluster.StartAdditionalSilos(numAdditionalSilos - numOfJoins);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
List<SiloHandle> silos = await this.HostedCluster.StartAdditionalSilos(numOfJoins);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
foreach (SiloHandle sh in silos)
{
VerificationScenario(PickKey(sh.SiloAddress));
}
Thread.Sleep(TimeSpan.FromSeconds(15));
}
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_1F1J()
{
await this.HostedCluster.StartAdditionalSilos(numAdditionalSilos);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
List<SiloHandle> failures = await getSilosToFail(Fail.Random, 1);
uint keyToCheck = PickKey(failures[0].SiloAddress);// failures[0].SiloAddress.GetConsistentHashCode();
List<SiloHandle> joins = null;
// kill a silo and join a new one in parallel
logger.Info("Killing silo {0} and joining a silo", failures[0].SiloAddress);
var tasks = new Task[2]
{
Task.Factory.StartNew(() => this.HostedCluster.StopSilo(failures[0])),
this.HostedCluster.StartAdditionalSilos(1).ContinueWith(t => joins = t.GetAwaiter().GetResult())
};
Task.WaitAll(tasks, endWait);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
AssertEventually(() =>
{
VerificationScenario(keyToCheck); // verify failed silo's key
VerificationScenario(PickKey(joins[0].SiloAddress)); // verify newly joined silo's key
}, failureTimeout);
}
// failing the secondary in this scenario exposed the bug in DomainGrain ... so, we keep it as a separate test than Ring_1F1J
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_1Fsec1J()
{
await this.HostedCluster.StartAdditionalSilos(numAdditionalSilos);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
//List<SiloHandle> failures = getSilosToFail(Fail.Random, 1);
SiloHandle fail = this.HostedCluster.SecondarySilos.First();
uint keyToCheck = PickKey(fail.SiloAddress); //fail.SiloAddress.GetConsistentHashCode();
List<SiloHandle> joins = null;
// kill a silo and join a new one in parallel
logger.Info("Killing secondary silo {0} and joining a silo", fail.SiloAddress);
var tasks = new Task[2]
{
Task.Factory.StartNew(() => this.HostedCluster.StopSilo(fail)),
this.HostedCluster.StartAdditionalSilos(1).ContinueWith(t => joins = t.GetAwaiter().GetResult())
};
Task.WaitAll(tasks, endWait);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
AssertEventually(() =>
{
VerificationScenario(keyToCheck); // verify failed silo's key
VerificationScenario(PickKey(joins[0].SiloAddress));
}, failureTimeout);
}
#endregion
#region Utility methods
private uint PickKey(SiloAddress responsibleSilo)
{
int iteration = 10000;
var testHooks = this.Client.GetTestHooks(this.HostedCluster.Primary);
for (int i = 0; i < iteration; i++)
{
double next = random.NextDouble();
uint randomKey = (uint)((double)RangeFactory.RING_SIZE * next);
SiloAddress s = testHooks.GetConsistentRingPrimaryTargetSilo(randomKey).Result;
if (responsibleSilo.Equals(s))
return randomKey;
}
throw new Exception(String.Format("Could not pick a key that silo {0} will be responsible for. Primary.Ring = \n{1}",
responsibleSilo, testHooks.GetConsistentRingProviderDiagnosticInfo().Result));
}
private void VerificationScenario(uint testKey)
{
// setup
List<SiloAddress> silos = new List<SiloAddress>();
foreach (var siloHandle in this.HostedCluster.GetActiveSilos())
{
long hash = siloHandle.SiloAddress.GetConsistentHashCode();
int index = silos.FindLastIndex(siloAddr => siloAddr.GetConsistentHashCode() < hash) + 1;
silos.Insert(index, siloHandle.SiloAddress);
}
// verify parameter key
VerifyKey(testKey, silos);
// verify some other keys as well, apart from the parameter key
// some random keys
for (int i = 0; i < 3; i++)
{
VerifyKey((uint)random.Next(), silos);
}
// lowest key
uint lowest = (uint)(silos.First().GetConsistentHashCode() - 1);
VerifyKey(lowest, silos);
// highest key
uint highest = (uint)(silos.Last().GetConsistentHashCode() + 1);
VerifyKey(lowest, silos);
}
private void VerifyKey(uint key, List<SiloAddress> silos)
{
var testHooks = this.Client.GetTestHooks(this.HostedCluster.Primary);
SiloAddress truth = testHooks.GetConsistentRingPrimaryTargetSilo(key).Result; //expected;
//if (truth == null) // if the truth isn't passed, we compute it here
//{
// truth = silos.Find(siloAddr => (key <= siloAddr.GetConsistentHashCode()));
// if (truth == null)
// {
// truth = silos.First();
// }
//}
// lookup for 'key' should return 'truth' on all silos
foreach (var siloHandle in this.HostedCluster.GetActiveSilos()) // do this for each silo
{
SiloAddress s = testHooks.GetConsistentRingPrimaryTargetSilo((uint)key).Result;
Assert.Equal(truth, s);
}
}
private async Task<List<SiloHandle>> getSilosToFail(Fail fail, int numOfFailures)
{
List<SiloHandle> failures = new List<SiloHandle>();
int count = 0, index = 0;
// Figure out the primary directory partition and the silo hosting the ReminderTableGrain.
bool usingReminderGrain = this.ClusterConfiguration.Globals.ReminderServiceType.Equals(GlobalConfiguration.ReminderServiceProviderType.ReminderTableGrain);
IReminderTable tableGrain = this.GrainFactory.GetGrain<IReminderTableGrain>(Constants.ReminderTableGrainId);
var tableGrainId = ((GrainReference)tableGrain).GrainId;
SiloAddress reminderTableGrainPrimaryDirectoryAddress = (await TestUtils.GetDetailedGrainReport(this.HostedCluster.InternalGrainFactory, tableGrainId, this.HostedCluster.Primary)).PrimaryForGrain;
// ask a detailed report from the directory partition owner, and get the actionvation addresses
var addresses = (await TestUtils.GetDetailedGrainReport(this.HostedCluster.InternalGrainFactory, tableGrainId, this.HostedCluster.GetSiloForAddress(reminderTableGrainPrimaryDirectoryAddress))).LocalDirectoryActivationAddresses;
ActivationAddress reminderGrainActivation = addresses.FirstOrDefault();
SortedList<int, SiloHandle> ids = new SortedList<int, SiloHandle>();
foreach (var siloHandle in this.HostedCluster.GetActiveSilos())
{
SiloAddress siloAddress = siloHandle.SiloAddress;
if (siloAddress.Equals(this.HostedCluster.Primary.SiloAddress))
{
continue;
}
// Don't fail primary directory partition and the silo hosting the ReminderTableGrain.
if (usingReminderGrain)
{
if (siloAddress.Equals(reminderTableGrainPrimaryDirectoryAddress) || siloAddress.Equals(reminderGrainActivation.Silo))
{
continue;
}
}
ids.Add(siloHandle.SiloAddress.GetConsistentHashCode(), siloHandle);
}
// we should not fail the primary!
// we can't guarantee semantics of 'Fail' if it evalutes to the primary's address
switch (fail)
{
case Fail.First:
index = 0;
while (count++ < numOfFailures)
{
while (failures.Contains(ids.Values[index]))
{
index++;
}
failures.Add(ids.Values[index]);
}
break;
case Fail.Last:
index = ids.Count - 1;
while (count++ < numOfFailures)
{
while (failures.Contains(ids.Values[index]))
{
index--;
}
failures.Add(ids.Values[index]);
}
break;
case Fail.Random:
default:
while (count++ < numOfFailures)
{
SiloHandle r = ids.Values[random.Next(ids.Count)];
while (failures.Contains(r))
{
r = ids.Values[random.Next(ids.Count)];
}
failures.Add(r);
}
break;
}
return failures;
}
// for debugging only
private void printSilos(string msg)
{
SortedList<int, SiloAddress> ids = new SortedList<int, SiloAddress>(numAdditionalSilos + 2);
foreach (var siloHandle in this.HostedCluster.GetActiveSilos())
{
ids.Add(siloHandle.SiloAddress.GetConsistentHashCode(), siloHandle.SiloAddress);
}
logger.Info("{0} list of silos: ", msg);
foreach (var id in ids.Keys.ToList())
{
logger.Info("{0} -> {1}", ids[id], id);
}
}
private static void AssertEventually(Action assertion, TimeSpan timeout)
{
AssertEventually(assertion, timeout, TimeSpan.FromMilliseconds(500));
}
private static void AssertEventually(Action assertion, TimeSpan timeout, TimeSpan delayBetweenIterations)
{
var sw = Stopwatch.StartNew();
while (true)
{
try
{
assertion();
return;
}
catch (XunitException)
{
if (sw.ElapsedMilliseconds > timeout.TotalMilliseconds)
{
throw;
}
}
if (delayBetweenIterations > TimeSpan.Zero)
{
Thread.Sleep(delayBetweenIterations);
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using AView = Android.Views.View;
namespace Xamarin.Forms.Platform.Android
{
public class VisualElementPackager : IDisposable
{
readonly EventHandler<ElementEventArgs> _childAddedHandler;
readonly EventHandler<ElementEventArgs> _childRemovedHandler;
readonly EventHandler _childReorderedHandler;
List<IVisualElementRenderer> _childViews;
bool _disposed;
IVisualElementRenderer _renderer;
public VisualElementPackager(IVisualElementRenderer renderer)
{
if (renderer == null)
throw new ArgumentNullException("renderer");
_childAddedHandler = OnChildAdded;
_childRemovedHandler = OnChildRemoved;
_childReorderedHandler = OnChildrenReordered;
_renderer = renderer;
_renderer.ElementChanged += (sender, args) => SetElement(args.OldElement, args.NewElement);
}
public void Dispose()
{
if (_disposed)
return;
_disposed = true;
if (_renderer != null)
{
if (_childViews != null)
{
_childViews.Clear();
_childViews = null;
}
_renderer.Element.ChildAdded -= _childAddedHandler;
_renderer.Element.ChildRemoved -= _childRemovedHandler;
_renderer.Element.ChildrenReordered -= _childReorderedHandler;
_renderer = null;
}
}
public void Load()
{
SetElement(null, _renderer.Element);
}
void AddChild(VisualElement view, IVisualElementRenderer oldRenderer = null, RendererPool pool = null, bool sameChildren = false)
{
Performance.Start();
if (_childViews == null)
_childViews = new List<IVisualElementRenderer>();
IVisualElementRenderer renderer = oldRenderer;
if (pool != null)
renderer = pool.GetFreeRenderer(view);
if (renderer == null)
{
Performance.Start("New renderer");
renderer = Platform.CreateRenderer(view);
Performance.Stop("New renderer");
}
if (renderer == oldRenderer)
{
Platform.SetRenderer(renderer.Element, null);
renderer.SetElement(view);
}
Performance.Start("Set renderer");
Platform.SetRenderer(view, renderer);
Performance.Stop("Set renderer");
Performance.Start("Add view");
if (!sameChildren)
{
_renderer.ViewGroup.AddView(renderer.ViewGroup);
_childViews.Add(renderer);
}
Performance.Stop("Add view");
Performance.Stop();
}
void EnsureChildOrder()
{
for (var i = 0; i < _renderer.Element.LogicalChildren.Count; i++)
{
Element child = _renderer.Element.LogicalChildren[i];
var element = (VisualElement)child;
if (element != null)
{
IVisualElementRenderer r = Platform.GetRenderer(element);
_renderer.ViewGroup.BringChildToFront(r.ViewGroup);
}
}
}
void OnChildAdded(object sender, ElementEventArgs e)
{
var view = e.Element as VisualElement;
if (view != null)
AddChild(view);
if (_renderer.Element.LogicalChildren[_renderer.Element.LogicalChildren.Count - 1] != view)
EnsureChildOrder();
}
void OnChildRemoved(object sender, ElementEventArgs e)
{
Performance.Start();
var view = e.Element as VisualElement;
if (view != null)
RemoveChild(view);
Performance.Stop();
}
void OnChildrenReordered(object sender, EventArgs e)
{
EnsureChildOrder();
}
void RemoveChild(VisualElement view)
{
IVisualElementRenderer renderer = Platform.GetRenderer(view);
_childViews.Remove(renderer);
renderer.ViewGroup.RemoveFromParent();
renderer.Dispose();
}
void SetElement(VisualElement oldElement, VisualElement newElement)
{
Performance.Start();
var sameChildrenTypes = false;
ReadOnlyCollection<Element> newChildren = null, oldChildren = null;
RendererPool pool = null;
if (oldElement != null)
{
if (newElement != null)
{
sameChildrenTypes = true;
oldChildren = oldElement.LogicalChildren;
newChildren = newElement.LogicalChildren;
if (oldChildren.Count == newChildren.Count)
{
for (var i = 0; i < oldChildren.Count; i++)
{
if (oldChildren[i].GetType() != newChildren[i].GetType())
{
sameChildrenTypes = false;
break;
}
}
}
else
sameChildrenTypes = false;
}
oldElement.ChildAdded -= _childAddedHandler;
oldElement.ChildRemoved -= _childRemovedHandler;
oldElement.ChildrenReordered -= _childReorderedHandler;
if (!sameChildrenTypes)
{
_childViews = new List<IVisualElementRenderer>();
pool = new RendererPool(_renderer, oldElement);
pool.ClearChildrenRenderers();
}
}
if (newElement != null)
{
Performance.Start("Setup");
newElement.ChildAdded += _childAddedHandler;
newElement.ChildRemoved += _childRemovedHandler;
newElement.ChildrenReordered += _childReorderedHandler;
newChildren = newChildren ?? newElement.LogicalChildren;
for (var i = 0; i < newChildren.Count; i++)
{
IVisualElementRenderer oldRenderer = null;
if (oldChildren != null && sameChildrenTypes)
oldRenderer = _childViews[i];
AddChild((VisualElement)newChildren[i], oldRenderer, pool, sameChildrenTypes);
}
#if DEBUG
//if (renderer.Element.LogicalChildren.Any() && renderer.ViewGroup.ChildCount != renderer.Element.LogicalChildren.Count)
// throw new InvalidOperationException ("SetElement did not create the correct number of children");
#endif
Performance.Stop("Setup");
}
Performance.Stop();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
namespace System.Xml
{
internal partial class ReadContentAsBinaryHelper
{
// Private enums
enum State
{
None,
InReadContent,
InReadElementContent,
}
// Fields
XmlReader reader;
State state;
int valueOffset;
bool isEnd;
bool canReadValueChunk;
char[] valueChunk;
int valueChunkLength;
IncrementalReadDecoder decoder;
Base64Decoder base64Decoder;
BinHexDecoder binHexDecoder;
// Constants
const int ChunkSize = 256;
// Constructor
internal ReadContentAsBinaryHelper(XmlReader reader)
{
this.reader = reader;
this.canReadValueChunk = reader.CanReadValueChunk;
if (canReadValueChunk)
{
valueChunk = new char[ChunkSize];
}
}
// Static methods
internal static ReadContentAsBinaryHelper CreateOrReset(ReadContentAsBinaryHelper helper, XmlReader reader)
{
if (helper == null)
{
return new ReadContentAsBinaryHelper(reader);
}
else
{
helper.Reset();
return helper;
}
}
// Internal methods
internal int ReadContentAsBase64(byte[] buffer, int index, int count)
{
// check arguments
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count");
}
if (index < 0)
{
throw new ArgumentOutOfRangeException("index");
}
if (buffer.Length - index < count)
{
throw new ArgumentOutOfRangeException("count");
}
switch (state)
{
case State.None:
if (!reader.CanReadContentAs())
{
throw reader.CreateReadContentAsException("ReadContentAsBase64");
}
if (!Init())
{
return 0;
}
break;
case State.InReadContent:
// if we have a correct decoder, go read
if (decoder == base64Decoder)
{
// read more binary data
return ReadContentAsBinary(buffer, index, count);
}
break;
case State.InReadElementContent:
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
default:
Debug.Fail("Unmatched state in switch");
return 0;
}
Debug.Assert(state == State.InReadContent);
// setup base64 decoder
InitBase64Decoder();
// read more binary data
return ReadContentAsBinary(buffer, index, count);
}
internal int ReadContentAsBinHex(byte[] buffer, int index, int count)
{
// check arguments
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count");
}
if (index < 0)
{
throw new ArgumentOutOfRangeException("index");
}
if (buffer.Length - index < count)
{
throw new ArgumentOutOfRangeException("count");
}
switch (state)
{
case State.None:
if (!reader.CanReadContentAs())
{
throw reader.CreateReadContentAsException("ReadContentAsBinHex");
}
if (!Init())
{
return 0;
}
break;
case State.InReadContent:
// if we have a correct decoder, go read
if (decoder == binHexDecoder)
{
// read more binary data
return ReadContentAsBinary(buffer, index, count);
}
break;
case State.InReadElementContent:
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
default:
Debug.Fail("Unmatched state in switch");
return 0;
}
Debug.Assert(state == State.InReadContent);
// setup binhex decoder
InitBinHexDecoder();
// read more binary data
return ReadContentAsBinary(buffer, index, count);
}
internal int ReadElementContentAsBase64(byte[] buffer, int index, int count)
{
// check arguments
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count");
}
if (index < 0)
{
throw new ArgumentOutOfRangeException("index");
}
if (buffer.Length - index < count)
{
throw new ArgumentOutOfRangeException("count");
}
switch (state)
{
case State.None:
if (reader.NodeType != XmlNodeType.Element)
{
throw reader.CreateReadElementContentAsException("ReadElementContentAsBase64");
}
if (!InitOnElement())
{
return 0;
}
break;
case State.InReadContent:
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
case State.InReadElementContent:
// if we have a correct decoder, go read
if (decoder == base64Decoder)
{
// read more binary data
return ReadElementContentAsBinary(buffer, index, count);
}
break;
default:
Debug.Fail("Unmatched state in switch");
return 0;
}
Debug.Assert(state == State.InReadElementContent);
// setup base64 decoder
InitBase64Decoder();
// read more binary data
return ReadElementContentAsBinary(buffer, index, count);
}
internal int ReadElementContentAsBinHex(byte[] buffer, int index, int count)
{
// check arguments
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count");
}
if (index < 0)
{
throw new ArgumentOutOfRangeException("index");
}
if (buffer.Length - index < count)
{
throw new ArgumentOutOfRangeException("count");
}
switch (state)
{
case State.None:
if (reader.NodeType != XmlNodeType.Element)
{
throw reader.CreateReadElementContentAsException("ReadElementContentAsBinHex");
}
if (!InitOnElement())
{
return 0;
}
break;
case State.InReadContent:
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
case State.InReadElementContent:
// if we have a correct decoder, go read
if (decoder == binHexDecoder)
{
// read more binary data
return ReadElementContentAsBinary(buffer, index, count);
}
break;
default:
Debug.Fail("Unmatched state in switch");
return 0;
}
Debug.Assert(state == State.InReadElementContent);
// setup binhex decoder
InitBinHexDecoder();
// read more binary data
return ReadElementContentAsBinary(buffer, index, count);
}
internal void Finish()
{
if (state != State.None)
{
while (MoveToNextContentNode(true))
;
if (state == State.InReadElementContent)
{
if (reader.NodeType != XmlNodeType.EndElement)
{
throw new XPath.XPathException(SR.Xml_InvalidNodeType, reader.NodeType.ToString(), reader as IXmlLineInfo);
}
// move off the EndElement
reader.Read();
}
}
Reset();
}
internal void Reset()
{
state = State.None;
isEnd = false;
valueOffset = 0;
}
// Private methods
private bool Init()
{
// make sure we are on a content node
if (!MoveToNextContentNode(false))
{
return false;
}
state = State.InReadContent;
isEnd = false;
return true;
}
private bool InitOnElement()
{
Debug.Assert(reader.NodeType == XmlNodeType.Element);
bool isEmpty = reader.IsEmptyElement;
// move to content or off the empty element
reader.Read();
if (isEmpty)
{
return false;
}
// make sure we are on a content node
if (!MoveToNextContentNode(false))
{
if (reader.NodeType != XmlNodeType.EndElement)
{
throw new XPath.XPathException(SR.Xml_InvalidNodeType, reader.NodeType.ToString(), reader as IXmlLineInfo);
}
// move off end element
reader.Read();
return false;
}
state = State.InReadElementContent;
isEnd = false;
return true;
}
private void InitBase64Decoder()
{
if (base64Decoder == null)
{
base64Decoder = new Base64Decoder();
}
else
{
base64Decoder.Reset();
}
decoder = base64Decoder;
}
private void InitBinHexDecoder()
{
if (binHexDecoder == null)
{
binHexDecoder = new BinHexDecoder();
}
else
{
binHexDecoder.Reset();
}
decoder = binHexDecoder;
}
private int ReadContentAsBinary(byte[] buffer, int index, int count)
{
Debug.Assert(decoder != null);
if (isEnd)
{
Reset();
return 0;
}
decoder.SetNextOutputBuffer(buffer, index, count);
for (; ;)
{
// use streaming ReadValueChunk if the reader supports it
if (canReadValueChunk)
{
for (; ;)
{
if (valueOffset < valueChunkLength)
{
int decodedCharsCount = decoder.Decode(valueChunk, valueOffset, valueChunkLength - valueOffset);
valueOffset += decodedCharsCount;
}
if (decoder.IsFull)
{
return decoder.DecodedCount;
}
Debug.Assert(valueOffset == valueChunkLength);
if ((valueChunkLength = reader.ReadValueChunk(valueChunk, 0, ChunkSize)) == 0)
{
break;
}
valueOffset = 0;
}
}
else
{
// read what is reader.Value
string value = reader.Value;
int decodedCharsCount = decoder.Decode(value, valueOffset, value.Length - valueOffset);
valueOffset += decodedCharsCount;
if (decoder.IsFull)
{
return decoder.DecodedCount;
}
}
valueOffset = 0;
// move to next textual node in the element content; throw on sub elements
if (!MoveToNextContentNode(true))
{
isEnd = true;
return decoder.DecodedCount;
}
}
}
private int ReadElementContentAsBinary(byte[] buffer, int index, int count)
{
if (count == 0)
{
return 0;
}
// read binary
int decoded = ReadContentAsBinary(buffer, index, count);
if (decoded > 0)
{
return decoded;
}
// if 0 bytes returned check if we are on a closing EndElement, throw exception if not
if (reader.NodeType != XmlNodeType.EndElement)
{
throw new XPath.XPathException(SR.Xml_InvalidNodeType, reader.NodeType.ToString(), reader as IXmlLineInfo);
}
// move off the EndElement
reader.Read();
state = State.None;
return 0;
}
bool MoveToNextContentNode(bool moveIfOnContentNode)
{
do
{
switch (reader.NodeType)
{
case XmlNodeType.Attribute:
return !moveIfOnContentNode;
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.CDATA:
if (!moveIfOnContentNode)
{
return true;
}
break;
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.Comment:
case XmlNodeType.EndEntity:
// skip comments, pis and end entity nodes
break;
case XmlNodeType.EntityReference:
if (reader.CanResolveEntity)
{
reader.ResolveEntity();
break;
}
goto default;
default:
return false;
}
moveIfOnContentNode = false;
} while (reader.Read());
return false;
}
}
}
| |
using System;
using System.Net;
using System.Net.Mail;
using System.Security.Principal;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using AnglicanGeek.MarkdownMailer;
using Elmah;
using Microsoft.WindowsAzure.ServiceRuntime;
using Ninject;
using Ninject.Web.Common;
using Ninject.Modules;
using NuGetGallery.Configuration;
using NuGetGallery.Infrastructure;
using System.Diagnostics;
using NuGetGallery.Auditing;
namespace NuGetGallery
{
public class ContainerBindings : NinjectModule
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:CyclomaticComplexity", Justification = "This code is more maintainable in the same function.")]
public override void Load()
{
var configuration = new ConfigurationService();
Bind<ConfigurationService>()
.ToMethod(context => configuration);
Bind<IAppConfiguration>()
.ToMethod(context => configuration.Current);
Bind<PoliteCaptcha.IConfigurationSource>()
.ToMethod(context => configuration);
Bind<Lucene.Net.Store.Directory>()
.ToMethod(_ => LuceneCommon.GetDirectory(configuration.Current.LuceneIndexLocation))
.InSingletonScope();
Bind<ISearchService>()
.To<LuceneSearchService>()
.InRequestScope();
if (!String.IsNullOrEmpty(configuration.Current.AzureStorageConnectionString))
{
Bind<ErrorLog>()
.ToMethod(_ => new TableErrorLog(configuration.Current.AzureStorageConnectionString))
.InSingletonScope();
}
else
{
Bind<ErrorLog>()
.ToMethod(_ => new SqlErrorLog(configuration.Current.SqlConnectionString))
.InSingletonScope();
}
Bind<ICacheService>()
.To<HttpContextCacheService>()
.InRequestScope();
Bind<IContentService>()
.To<ContentService>()
.InSingletonScope();
Bind<IEntitiesContext>()
.ToMethod(context => new EntitiesContext(configuration.Current.SqlConnectionString, readOnly: configuration.Current.ReadOnlyMode))
.InRequestScope();
Bind<IEntityRepository<User>>()
.To<EntityRepository<User>>()
.InRequestScope();
Bind<IEntityRepository<CuratedFeed>>()
.To<EntityRepository<CuratedFeed>>()
.InRequestScope();
Bind<IEntityRepository<CuratedPackage>>()
.To<EntityRepository<CuratedPackage>>()
.InRequestScope();
Bind<IEntityRepository<CuratedPackageVersion>>()
.To<EntityRepository<CuratedPackageVersion>>()
.InRequestScope();
Bind<IEntityRepository<PackageRegistration>>()
.To<EntityRepository<PackageRegistration>>()
.InRequestScope();
Bind<IEntityRepository<Package>>()
.To<EntityRepository<Package>>()
.InRequestScope();
Bind<IEntityRepository<PackageDependency>>()
.To<EntityRepository<PackageDependency>>()
.InRequestScope();
Bind<IEntityRepository<PackageStatistics>>()
.To<EntityRepository<PackageStatistics>>()
.InRequestScope();
Bind<IEntityRepository<Credential>>()
.To<EntityRepository<Credential>>()
.InRequestScope();
Bind<ICuratedFeedService>()
.To<CuratedFeedService>()
.InRequestScope();
Bind<IUserService>()
.To<UserService>()
.InRequestScope();
Bind<IPackageService>()
.To<PackageService>()
.InRequestScope();
Bind<EditPackageService>().ToSelf();
Bind<IFormsAuthenticationService>()
.To<FormsAuthenticationService>()
.InSingletonScope();
Bind<IControllerFactory>()
.To<NuGetControllerFactory>()
.InRequestScope();
Bind<IIndexingService>()
.To<LuceneIndexingService>()
.InRequestScope();
Bind<INuGetExeDownloaderService>()
.To<NuGetExeDownloaderService>()
.InRequestScope();
var mailSenderThunk = new Lazy<IMailSender>(
() =>
{
var settings = Kernel.Get<ConfigurationService>();
if (settings.Current.SmtpUri != null && settings.Current.SmtpUri.IsAbsoluteUri)
{
var smtpUri = new SmtpUri(settings.Current.SmtpUri);
var mailSenderConfiguration = new MailSenderConfiguration
{
DeliveryMethod = SmtpDeliveryMethod.Network,
Host = smtpUri.Host,
Port = smtpUri.Port,
EnableSsl = smtpUri.Secure
};
if (!String.IsNullOrWhiteSpace(smtpUri.UserName))
{
mailSenderConfiguration.UseDefaultCredentials = false;
mailSenderConfiguration.Credentials = new NetworkCredential(
smtpUri.UserName,
smtpUri.Password);
}
return new MailSender(mailSenderConfiguration);
}
else
{
var mailSenderConfiguration = new MailSenderConfiguration
{
DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory,
PickupDirectoryLocation = HostingEnvironment.MapPath("~/App_Data/Mail")
};
return new MailSender(mailSenderConfiguration);
}
});
Bind<IMailSender>()
.ToMethod(context => mailSenderThunk.Value);
Bind<IMessageService>()
.To<MessageService>();
Bind<IPrincipal>().ToMethod(context => HttpContext.Current.User);
switch (configuration.Current.StorageType)
{
case StorageType.FileSystem:
case StorageType.NotSpecified:
ConfigureForLocalFileSystem();
break;
case StorageType.AzureStorage:
ConfigureForAzureStorage(configuration);
break;
}
Bind<IFileSystemService>()
.To<FileSystemService>()
.InSingletonScope();
Bind<IPackageFileService>()
.To<PackageFileService>();
Bind<IEntityRepository<PackageOwnerRequest>>()
.To<EntityRepository<PackageOwnerRequest>>()
.InRequestScope();
Bind<IUploadFileService>()
.To<UploadFileService>();
// todo: bind all package curators by convention
Bind<IAutomaticPackageCurator>()
.To<WebMatrixPackageCurator>();
Bind<IAutomaticPackageCurator>()
.To<Windows8PackageCurator>();
Bind<IAutomaticPackageCurator>()
.To<RequiredDependencyPackageCurator>();
// todo: bind all commands by convention
Bind<IAutomaticallyCuratePackageCommand>()
.To<AutomaticallyCuratePackageCommand>()
.InRequestScope();
Bind<IAggregateStatsService>()
.To<AggregateStatsService>()
.InRequestScope();
Bind<IPackageIdsQuery>()
.To<PackageIdsQuery>()
.InRequestScope();
Bind<IPackageVersionsQuery>()
.To<PackageVersionsQuery>()
.InRequestScope();
}
private void ConfigureForLocalFileSystem()
{
Bind<IFileStorageService>()
.To<FileSystemFileStorageService>()
.InSingletonScope();
// Ninject is doing some weird things with constructor selection without these.
// Anyone requesting an IReportService or IStatisticsService should be prepared
// to receive null anyway.
Bind<IReportService>().ToConstant(NullReportService.Instance);
Bind<IStatisticsService>().ToConstant(NullStatisticsService.Instance);
Bind<AuditingService>().ToConstant(AuditingService.None);
}
private void ConfigureForAzureStorage(ConfigurationService configuration)
{
Bind<ICloudBlobClient>()
.ToMethod(
_ => new CloudBlobClientWrapper(configuration.Current.AzureStorageConnectionString))
.InSingletonScope();
Bind<IFileStorageService>()
.To<CloudBlobFileStorageService>()
.InSingletonScope();
// when running on Windows Azure, pull the statistics from the warehouse via storage
Bind<IReportService>()
.ToMethod(context => new CloudReportService(configuration.Current.AzureStorageConnectionString))
.InSingletonScope();
Bind<IStatisticsService>()
.To<JsonStatisticsService>()
.InSingletonScope();
string instanceId;
try
{
instanceId = RoleEnvironment.CurrentRoleInstance.Id;
}
catch (Exception)
{
instanceId = Environment.MachineName;
}
var localIP = AuditActor.GetLocalIP().Result;
Bind<AuditingService>()
.ToMethod(_ => new CloudAuditingService(
instanceId, localIP, configuration.Current.AzureStorageConnectionString, CloudAuditingService.AspNetActorThunk))
.InSingletonScope();
}
}
}
| |
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace BoletoNet
{
public abstract class BarCodeBase
{
#region Variables
private string _code;
private int _height;
private int _digits;
private int _thin;
private int _full;
protected int xPos = 0;
protected int yPos = 0;
private string _contenttype;
protected Brush Black = Brushes.Black;
protected Brush White = Brushes.White;
#endregion
#region Property
/// <summary>
/// The Barcode.
/// </summary>
public string Code
{
get
{
try
{
return _code;
}
catch
{
return "";
}
}
set
{
try
{
_code = value;
}
catch
{
_code = null;
}
}
}
/// <summary>
/// The width of the thin bar (pixels).
/// </summary>
public int Width
{
get
{
try
{
return _thin;
}
catch
{
return 1;
}
}
set
{
try
{
var temp = value;
_thin = temp;
//_half = temp * 2;
_full = temp * 3;
}
catch
{
var temp = 1;
_thin = temp;
//_half = temp * 2;
_full = temp * 3;
}
}
}
/// <summary>
/// The Height of barcode (pixels).
/// </summary>
public int Height
{
get
{
try
{
return _height;
}
catch
{
return 15;
}
}
set
{
try
{
_height = value;
}
catch
{
_height = 1;
}
}
}
/// <summary>
/// Number of digits of the barcode.
/// </summary>
public int Digits
{
get
{
try
{
return _digits;
}
catch
{
return 0;
}
}
set
{
try
{
_digits = value;
}
catch
{
_digits = 0;
}
}
}
/// <summary>
/// Content type of code. Default: image/jpeg
/// </summary>
public string ContentType
{
get
{
try
{
if (_contenttype == null)
return "image/jpeg";
return _contenttype;
}
catch
{
return "image/jpeg";
}
}
set
{
try
{
_contenttype = value;
}
catch
{
_contenttype = "image/jpeg";
}
}
}
protected int Thin
{
get
{
try
{
return _thin;
}
catch
{
return 1;
}
}
}
protected int Full
{
get
{
try
{
return _full;
}
catch
{
return 3;
}
}
}
#endregion
protected virtual byte[] ToByte(Bitmap bitmap)
{
var mstream = new MemoryStream();
var myImageCodecInfo = GetEncoderInfo(ContentType);
var myEncoderParameter0 = new EncoderParameter(Encoder.Quality, (long)100);
var myEncoderParameters = new EncoderParameters(1) {Param = {[0] = myEncoderParameter0}};
bitmap.Save(mstream, myImageCodecInfo, myEncoderParameters);
return mstream.GetBuffer();
}
private static ImageCodecInfo GetEncoderInfo(string mimeType)
{
int j;
var encoders = ImageCodecInfo.GetImageEncoders();
for (j = 0; j < encoders.Length; ++j)
{
if (encoders[j].MimeType == mimeType)
return encoders[j];
}
return null;
}
protected virtual void DrawPattern(ref Graphics g, string pattern)
{
for (var i = 0; i < pattern.Length; i++)
{
var tempWidth = pattern[i] == '0' ? _thin : _full;
g.FillRectangle(i % 2 == 0 ? Black : White, xPos, yPos, tempWidth, _height);
xPos += tempWidth;
}
}
}
}
| |
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class TurnController : MonoBehaviour {
public int currentTurnNumber = 0;
public UB_SavedCharacter currentPlayer;
public UB_GamePlayEncounter currentEncounter;
public GameplayController gameplayController;
public PF_GamePlay.TurnStates CurrentTurn = PF_GamePlay.TurnStates.Null;
void OnEnable()
{
GameplayController.OnGameplayEvent += OnGameplayEventReceived;
}
void OnDisable()
{
GameplayController.OnGameplayEvent -= OnGameplayEventReceived;
}
public UB_GamePlayEncounter GetNextEncounter(bool isFirstEncounter = false)
{
if(PF_GamePlay.encounters != null && PF_GamePlay.encounters.Count > 0)
{
// pop off top and move to PF_Gameplay QuestTracker
// But not ON THE FIRST ENCOUNTER
if(PF_GamePlay.QuestProgress.CompletedEncounters.Count != 0 || !isFirstEncounter)
{
//LogCompletedEncounterStats();
UB_GamePlayEncounter topOfStack = new UB_GamePlayEncounter();
topOfStack = PF_GamePlay.encounters.First();
PF_GamePlay.QuestProgress.CompletedEncounters.Add(topOfStack);
PF_GamePlay.encounters.Remove(PF_GamePlay.encounters.First());
if(PF_GamePlay.encounters.Count == 0)
{
return null;
}
else
{
var next = PF_GamePlay.encounters.First();
next.Data.Vitals.SetMaxVitals();
next.Data.SetSpellDetails();
if(next.Data.EncounterType == EncounterTypes.BossCreep)
{
GameplayController.RaiseGameplayEvent(GlobalStrings.BOSS_BATTLE_EVENT, PF_GamePlay.GameplayEventTypes.StartBossBattle);
}
return next;
}
}
else
{
var next = PF_GamePlay.encounters.First();
next.Data.Vitals.SetMaxVitals();
next.Data.SetSpellDetails();
if(next.Data.EncounterType == EncounterTypes.BossCreep)
{
GameplayController.RaiseGameplayEvent(GlobalStrings.BOSS_BATTLE_EVENT, PF_GamePlay.GameplayEventTypes.StartBossBattle);
}
return next;
}
}
// end of the list or something!?
return null;
}
public void StartTurn()
{
if(this.currentEncounter.Data.EncounterType == EncounterTypes.Hero || this.currentEncounter.Data.EncounterType == EncounterTypes.Store)
{
this.CurrentTurn = PF_GamePlay.TurnStates.Player;
//this.gameplayController.playerController.EncounterBar.EnableEncounterOptions(this.currentEncounter.Data.EncounterType, this.currentEncounter.DisplayName);
//this.gameplayController.playerController.TransitionEncounterBarIn();
}
else
{
//compare speed to see who goes first
// if the enemy's speed is 150% more than the player's the enemy ambushes the player and gets a free attack
if(this.currentEncounter.Data.EncounterType.ToString().Contains(GlobalStrings.ENCOUNTER_CREEP) && (float)this.currentPlayer.PlayerVitals.Speed * 1.5f < (float)this.currentEncounter.Data.Vitals.Speed)
{
this.CurrentTurn = PF_GamePlay.TurnStates.Enemy;
//GameplayController.RaiseGameplayEvent("Enemy Turn Begins", PF_GamePlay.GameplayEventTypes.EnemyTurnBegins);
gameplayController.EnemyAttackPlayer(true);
//this.gameplayController.playerController.EncounterBar.EnableEncounterOptions(this.currentEncounter.Data.EncounterType, this.currentEncounter.DisplayName, true);
//this.gameplayController.playerController.TransitionEncounterBarIn();
}
else
{
this.CurrentTurn = PF_GamePlay.TurnStates.Player;
//this.gameplayController.playerController.EncounterBar.EnableEncounterOptions(this.currentEncounter.Data.EncounterType, this.currentEncounter.DisplayName);
//this.gameplayController.playerController.TransitionEncounterBarIn();
}
}
}
public void ToggleTurn(PF_GamePlay.TurnStates forceTurn = PF_GamePlay.TurnStates.Null)
{
if(forceTurn != PF_GamePlay.TurnStates.Null)
{
if(forceTurn == PF_GamePlay.TurnStates.Player)
{
this.CurrentTurn = PF_GamePlay.TurnStates.Player;
GameplayController.RaiseGameplayEvent(GlobalStrings.PLAYER_TURN_BEGIN_EVENT, PF_GamePlay.GameplayEventTypes.PlayerTurnBegins);
}
else if(forceTurn == PF_GamePlay.TurnStates.Enemy)
{
this.CurrentTurn = PF_GamePlay.TurnStates.Enemy;
GameplayController.RaiseGameplayEvent(GlobalStrings.ENEMY_TURN_BEGIN_EVENT, PF_GamePlay.GameplayEventTypes.EnemyTurnBegins);
}
return;
}
if(this.CurrentTurn == PF_GamePlay.TurnStates.Player)
{
this.CurrentTurn = PF_GamePlay.TurnStates.Enemy;
GameplayController.RaiseGameplayEvent(GlobalStrings.ENEMY_TURN_BEGIN_EVENT, PF_GamePlay.GameplayEventTypes.EnemyTurnBegins);
}
else if(this.CurrentTurn == PF_GamePlay.TurnStates.Enemy)
{
this.CurrentTurn = PF_GamePlay.TurnStates.Player;
GameplayController.RaiseGameplayEvent(GlobalStrings.PLAYER_TURN_BEGIN_EVENT, PF_GamePlay.GameplayEventTypes.PlayerTurnBegins);
}
}
public void CompleteEncounter(bool useEvade = false)
{
// was evasion / flee used?
if(useEvade)
{
//TODO evasion check to see if evasion passes
CycleNextEncounter();
return;
}
// Did the player complete this encounter?
if(this.currentEncounter.Data.EncounterType == EncounterTypes.Store || this.currentEncounter.Data.EncounterType == EncounterTypes.Hero)
{
this.currentEncounter.playerCompleted = true;
}
else if(this.currentEncounter.Data.EncounterType.ToString().Contains(GlobalStrings.ENCOUNTER_CREEP))
{
if(this.currentEncounter.Data.Vitals.Health <= 0)
{
// enemy died
this.currentEncounter.playerCompleted = true;
if(this.currentEncounter.Data.EncounterType == EncounterTypes.BossCreep)
{
Dictionary<string, object> eventData = new Dictionary<string, object>()
{
{ "Boss_Name", this.currentEncounter.DisplayName },
{ "Current_Quest", PF_GamePlay.ActiveQuest.levelName },
{ "Character_ID", PF_PlayerData.activeCharacter.characterDetails.CharacterId }
};
PF_Bridge.LogCustomEvent(PF_Bridge.CustomEventTypes.Client_BossKill, eventData);
}
}
else if(this.currentPlayer.PlayerVitals.Health <= 0)
{
// player died
this.currentEncounter.playerCompleted = false;
}
}
if(this.currentEncounter.playerCompleted)
{
LogCompletedEncounterStats();
if(this.currentEncounter.isEndOfAct)
{
CompleteAct();
return;
}
//TODO make this work for complex goals
// else if(this.gameplayController.AreQuestGoalsComplete())
// {
// GameplayController.RaiseGameplayEvent("Quest Complete", PF_GamePlay.GameplayEventTypes.EndQuest);
// }
CycleNextEncounter();
}
else
{
//trigger game over
GameplayController.RaiseGameplayEvent(GlobalStrings.PLAYER_DIED_EVENT, PF_GamePlay.GameplayEventTypes.PlayerDied);
Debug.Log ("Player Died...");
PF_GamePlay.QuestProgress.Deaths++;
Dictionary<string, object> eventData = new Dictionary<string, object>()
{
{ "Killed_By", this.currentEncounter.DisplayName },
{ "Enemy_Health", this.currentEncounter.Data.Vitals.Health },
{ "Current_Quest", PF_GamePlay.ActiveQuest.levelName },
{ "Character_ID", PF_PlayerData.activeCharacter.characterDetails.CharacterId }
};
PF_Bridge.LogCustomEvent(PF_Bridge.CustomEventTypes.Client_PlayerDied, eventData);
return;
}
}
void LogCompletedEncounterStats()
{
var progress = PF_GamePlay.QuestProgress;
var encounter = this.currentEncounter;
if(encounter.playerCompleted)
{
if(this.currentEncounter.Data.EncounterType.ToString().Contains(GlobalStrings.ENCOUNTER_CREEP))
{
progress.CreepEncounters++;
}
else if(this.currentEncounter.Data.EncounterType == EncounterTypes.Hero)
{
progress.HeroRescues++;
}
progress.GoldCollected += Random.Range(encounter.Data.Rewards.GoldMin, encounter.Data.Rewards.GoldMax);
progress.XpCollected += Random.Range(encounter.Data.Rewards.XpMin, encounter.Data.Rewards.XpMax);
if(encounter.Data.Rewards.ItemsDropped.Count > 0)
{
progress.ItemsFound.AddRange(encounter.Data.Rewards.ItemsDropped);
}
}
this.gameplayController.playerController.UpdateQuestStats();
}
public void CycleNextEncounter()
{
this.currentEncounter = GetNextEncounter();
if(this.currentEncounter != null)
{
UnityAction callback = () =>
{
UnityAction afterTransition = () =>
{
if(this.currentEncounter.Data.EncounterType.ToString().Contains(GlobalStrings.ENCOUNTER_CREEP) && this.currentPlayer.PlayerVitals.Speed * 1.5f < this.currentEncounter.Data.Vitals.Speed)
{
this.CurrentTurn = PF_GamePlay.TurnStates.Enemy;
gameplayController.EnemyAttackPlayer(true);
this.gameplayController.playerController.EncounterBar.EnableEncounterOptions(this.currentEncounter.Data.EncounterType, this.currentEncounter.DisplayName, true);
}
else
{
this.CurrentTurn = PF_GamePlay.TurnStates.Player;
//this.gameplayController.playerController.EncounterBar.EnableEncounterOptions(this.currentEncounter.Data.EncounterType, this.currentEncounter.DisplayName);
this.gameplayController.playerController.TransitionActionBarIn();
}
GameplayController.RaiseGameplayEvent(GlobalStrings.NEXT_ENCOUNTER_EVENT, PF_GamePlay.GameplayEventTypes.IntroEncounter);
};
this.gameplayController.enemyController.currentEncounter.UpdateCurrentEncounter(this.currentEncounter);
this.gameplayController.enemyController.nextController.UpdateNextEncounters();
this.gameplayController.enemyController.TransitionCurrentEncounterIn(afterTransition);
};
this.gameplayController.enemyController.TransitionCurrentEncounterOut(callback);
}
}
void OnGameplayEventReceived(string message, PF_GamePlay.GameplayEventTypes type )
{
if(type == PF_GamePlay.GameplayEventTypes.IntroQuest)
{
AdvanceAct();
this.currentEncounter = GetNextEncounter(true);
this.gameplayController.enemyController.currentEncounter.UpdateCurrentEncounter(this.currentEncounter);
this.gameplayController.enemyController.nextController.UpdateNextEncounters();
this.currentTurnNumber = 1;
//this.currentEncounter = PF_GamePlay.encounters.First();
this.currentPlayer = PF_PlayerData.activeCharacter;
}
if(type == PF_GamePlay.GameplayEventTypes.StartQuest)
{
StartTurn();
}
if(type == PF_GamePlay.GameplayEventTypes.OutroEncounter)
{
CompleteEncounter();
return;
}
if(type == PF_GamePlay.GameplayEventTypes.EnemyTurnEnds || type == PF_GamePlay.GameplayEventTypes.PlayerTurnEnds)
{
if(message.Contains(GlobalStrings.PLAYER_RESPAWN_EVENT))
{
gameplayController.playerController.UpdateQuestStats();
StartCoroutine(gameplayController.playerController.LifeBar.UpdateBar(gameplayController.playerController.LifeBar.maxValue));
}
else
{
ToggleTurn();
}
}
}
public void Evade()
{
//this.currentEncounter.playerCompleted
if(this.currentEncounter.isEndOfAct)
{
Debug.Log("End of the Road M8..."); // cant skip the last encounter
}
else
{
CompleteEncounter(true);
this.gameplayController.DecrementPlayerCDs();
}
}
public void Rescue()
{
this.currentEncounter.playerCompleted = true;
Dictionary<string, object> eventData = new Dictionary<string, object>()
{
{ "Current_Quest", PF_GamePlay.ActiveQuest.levelName },
{ "Rescued", this.currentEncounter.DisplayName },
{ "Character_ID", PF_PlayerData.activeCharacter.characterDetails.CharacterId }
};
PF_Bridge.LogCustomEvent(PF_Bridge.CustomEventTypes.Client_UnicornFreed, eventData);
CompleteEncounter(false);
}
public void CompleteAct()
{
if(PF_GamePlay.QuestProgress != null)
{
//this.gameplayController.directionController;
PF_GamePlay.QuestProgress.CurrentAct.Value.IsActCompleted = true;
if(PF_GamePlay.encounters.Count > 1)
{
// more acts to go
GameplayController.RaiseGameplayEvent(GlobalStrings.ACT_COMPLETE_EVENT, PF_GamePlay.GameplayEventTypes.OutroAct);
}
else
{
// no more acts, complete quest
PF_GamePlay.QuestProgress.isQuestWon = true;
UB_GamePlayEncounter topOfStack = new UB_GamePlayEncounter();
topOfStack = PF_GamePlay.encounters.First();
PF_GamePlay.QuestProgress.CompletedEncounters.Add(topOfStack);
PF_GamePlay.encounters.Remove(PF_GamePlay.encounters.First());
//CycleNextEncounter();
GameplayController.RaiseGameplayEvent(GlobalStrings.QUEST_COMPLETE_EVENT, PF_GamePlay.GameplayEventTypes.OutroQuest);
}
}
}
public void AdvanceAct()
{
if(PF_GamePlay.ActiveQuest.levelData.Acts.Count > 0)
{
if(PF_GamePlay.QuestProgress.CurrentAct.Equals(new KeyValuePair<string, UB_LevelAct>()))
{
// FIRST ACT
PF_GamePlay.QuestProgress.CurrentAct = PF_GamePlay.ActiveQuest.levelData.Acts.First();
PF_GamePlay.QuestProgress.ActIndex = 0;
}
else
{
//Following Acts
int indexToCheck = PF_GamePlay.QuestProgress.ActIndex+1;
if(PF_GamePlay.ActiveQuest.levelData.Acts.Count > indexToCheck)
{
PF_GamePlay.QuestProgress.CurrentAct = PF_GamePlay.ActiveQuest.levelData.Acts.ElementAt(indexToCheck);
PF_GamePlay.QuestProgress.ActIndex = indexToCheck;
CycleNextEncounter();
}
}
}
}
}
| |
#region License
//
// Author: Nate Kohari <nkohari@gmail.com>
// Copyright (c) 2007-2008, Enkari, Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
#region Using Directives
using System;
using System.IO;
using Ninject.Core.Infrastructure;
using Ninject.Core.Logging.Formatters;
#endregion
namespace Ninject.Core.Logging
{
/// <summary>
/// Writes log messages to a text writer.
/// </summary>
public class TextWriterLogger : LoggerBase
{
/*----------------------------------------------------------------------------------------*/
#region Fields
private readonly TextWriter _writer;
private readonly IMessageFormatter _formatter;
#endregion
/*----------------------------------------------------------------------------------------*/
#region Properties
/// <summary>
/// Gets a value indicating whether messages with Debug severity should be logged.
/// </summary>
public override bool IsDebugEnabled
{
get { return true; }
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets a value indicating whether messages with Info severity should be logged.
/// </summary>
public override bool IsInfoEnabled
{
get { return true; }
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets a value indicating whether messages with Warn severity should be logged.
/// </summary>
public override bool IsWarnEnabled
{
get { return true; }
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets a value indicating whether messages with Error severity should be logged.
/// </summary>
public override bool IsErrorEnabled
{
get { return true; }
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Gets a value indicating whether messages with Fatal severity should be logged.
/// </summary>
public override bool IsFatalEnabled
{
get { return true; }
}
#endregion
/*----------------------------------------------------------------------------------------*/
#region Disposal
/// <summary>
/// Releases all resources currently held by the object.
/// </summary>
/// <param name="disposing"><see langword="True"/> if managed objects should be disposed, otherwise <see langword="false"/>.</param>
protected override void Dispose(bool disposing)
{
if (disposing && !IsDisposed)
{
DisposeMember(_writer);
DisposeMember(_formatter);
}
base.Dispose(disposing);
}
#endregion
/*----------------------------------------------------------------------------------------*/
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="TextWriterLogger"/> class.
/// </summary>
/// <param name="type">The type associated with the logger.</param>
/// <param name="writer">The writer to write to.</param>
public TextWriterLogger(Type type, TextWriter writer)
: this(type, writer, new StandardMessageFormatter())
{
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Initializes a new instance of the <see cref="TextWriterLogger"/> class.
/// </summary>
/// <param name="type">The type associated with the logger.</param>
/// <param name="writer">The writer to write to.</param>
/// <param name="formatter">The formatter to use to format log messages.</param>
public TextWriterLogger(Type type, TextWriter writer, IMessageFormatter formatter)
: base(type)
{
Ensure.ArgumentNotNull(writer, "writer");
Ensure.ArgumentNotNull(formatter, "formatter");
_writer = writer;
_formatter = formatter;
}
#endregion
/*----------------------------------------------------------------------------------------*/
#region Public Methods
/// <summary>
/// Logs the specified message with Debug severity.
/// </summary>
/// <param name="format">The message or format template.</param>
/// <param name="args">Any arguments required for the format template.</param>
public override void Debug(string format, params object[] args)
{
WriteMessage(LogSeverity.Debug, format, args);
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Logs the specified exception with Debug severity.
/// </summary>
/// <param name="exception">The exception to log.</param>
/// <param name="format">The message or format template.</param>
/// <param name="args">Any arguments required for the format template.</param>
public override void Debug(Exception exception, string format, params object[] args)
{
WriteMessage(LogSeverity.Debug, exception, format, args);
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Logs the specified message with Info severity.
/// </summary>
/// <param name="format">The message or format template.</param>
/// <param name="args">Any arguments required for the format template.</param>
public override void Info(string format, params object[] args)
{
WriteMessage(LogSeverity.Info, format, args);
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Logs the specified exception with Info severity.
/// </summary>
/// <param name="exception">The exception to log.</param>
/// <param name="format">The message or format template.</param>
/// <param name="args">Any arguments required for the format template.</param>
public override void Info(Exception exception, string format, params object[] args)
{
WriteMessage(LogSeverity.Info, exception, format, args);
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Logs the specified message with Warn severity.
/// </summary>
/// <param name="format">The message or format template.</param>
/// <param name="args">Any arguments required for the format template.</param>
public override void Warn(string format, params object[] args)
{
WriteMessage(LogSeverity.Warn, format, args);
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Logs the specified exception with Warn severity.
/// </summary>
/// <param name="exception">The exception to log.</param>
/// <param name="format">The message or format template.</param>
/// <param name="args">Any arguments required for the format template.</param>
public override void Warn(Exception exception, string format, params object[] args)
{
WriteMessage(LogSeverity.Warn, exception, format, args);
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Logs the specified message with Error severity.
/// </summary>
/// <param name="format">The message or format template.</param>
/// <param name="args">Any arguments required for the format template.</param>
public override void Error(string format, params object[] args)
{
WriteMessage(LogSeverity.Error, format, args);
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Logs the specified exception with Error severity.
/// </summary>
/// <param name="exception">The exception to log.</param>
/// <param name="format">The message or format template.</param>
/// <param name="args">Any arguments required for the format template.</param>
public override void Error(Exception exception, string format, params object[] args)
{
WriteMessage(LogSeverity.Error, exception, format, args);
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Logs the specified message with Fatal severity.
/// </summary>
/// <param name="format">The message or format template.</param>
/// <param name="args">Any arguments required for the format template.</param>
public override void Fatal(string format, params object[] args)
{
WriteMessage(LogSeverity.Fatal, format, args);
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Logs the specified exception with Fatal severity.
/// </summary>
/// <param name="exception">The exception to log.</param>
/// <param name="format">The message or format template.</param>
/// <param name="args">Any arguments required for the format template.</param>
public override void Fatal(Exception exception, string format, params object[] args)
{
WriteMessage(LogSeverity.Fatal, exception, format, args);
}
#endregion
/*----------------------------------------------------------------------------------------*/
#region Protected Methods
/// <summary>
/// Writes the specified message to the stream.
/// </summary>
/// <param name="severity">The severity of the message.</param>
/// <param name="format">The message format.</param>
/// <param name="args">Arguments to the message format.</param>
protected virtual void WriteMessage(LogSeverity severity, string format, params object[] args)
{
string message;
if (args.Length > 0)
message = String.Format(format, args);
else
message = format;
_writer.WriteLine(_formatter.Format(this, severity, message));
}
/*----------------------------------------------------------------------------------------*/
/// <summary>
/// Writes the specified message to the stream.
/// </summary>
/// <param name="severity">The severity of the message.</param>
/// <param name="exception">The exception to log.</param>
/// <param name="format">The message format.</param>
/// <param name="args">Arguments to the message format.</param>
protected virtual void WriteMessage(LogSeverity severity, Exception exception, string format, params object[] args)
{
string message;
if (args.Length > 0)
message = String.Format(format, args);
else
message = format;
_writer.WriteLine(_formatter.Format(this, severity, message));
}
#endregion
/*----------------------------------------------------------------------------------------*/
}
}
| |
// <copyright file="BucketPropertyTests.cs" company="Basho Technologies, Inc.">
// Copyright 2011 - OJ Reeves & Jeremiah Peschka
// Copyright 2014 - Basho Technologies, Inc.
//
// This file is provided to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
// </copyright>
namespace RiakClientTests.Live.BucketPropertyTests
{
using System;
using System.Collections.Generic;
using NUnit.Framework;
using RiakClient;
using RiakClient.Models;
using RiakClient.Models.CommitHook;
using RiakClient.Util;
[TestFixture, IntegrationTest]
public class WhenDealingWithBucketProperties : LiveRiakConnectionTestBase
{
private readonly Random _random = new Random();
private string bucket;
[SetUp]
public void TestSetUp()
{
bucket = Guid.NewGuid().ToString();
}
[Test]
public void GettingExtendedPropertiesOnABucketWithoutExtendedPropertiesSetDoesntThrowAnException()
{
var getResult = Client.GetBucketProperties(bucket);
getResult.IsSuccess.ShouldBeTrue(getResult.ErrorMessage);
}
[Test]
public void SettingPropertiesOnNewBucketWorksCorrectly()
{
RiakBucketProperties props = new RiakBucketProperties()
.SetNVal((NVal)4)
.SetLegacySearch(true)
.SetW((Quorum)"all")
.SetR((Quorum)"quorum");
var setResult = Client.SetBucketProperties(bucket, props);
setResult.IsSuccess.ShouldBeTrue(setResult.ErrorMessage);
Func<RiakResult<RiakBucketProperties>> getFunc = () =>
{
var getResult = Client.GetBucketProperties(bucket);
getResult.IsSuccess.ShouldBeTrue(getResult.ErrorMessage);
return getResult;
};
Func<RiakResult<RiakBucketProperties>, bool> successFunc = (r) =>
{
bool rv = false;
RiakBucketProperties p = r.Value;
if (p.NVal == 4)
{
rv = true;
props = p;
}
return rv;
};
getFunc.WaitUntil(successFunc);
props.NVal.ShouldNotBeNull();
((int)props.NVal).ShouldEqual(4);
props.LegacySearch.ShouldNotEqual(null);
props.LegacySearch.Value.ShouldBeTrue();
props.W.ShouldEqual(Quorum.WellKnown.All);
props.R.ShouldEqual(Quorum.WellKnown.Quorum);
}
[Test]
public void GettingWithExtendedFlagReturnsExtraProperties()
{
var result = Client.GetBucketProperties(bucket);
result.IsSuccess.ShouldBeTrue(result.ErrorMessage);
result.Value.AllowMultiple.HasValue.ShouldBeTrue();
result.Value.NVal.ShouldNotBeNull();
result.Value.LastWriteWins.HasValue.ShouldBeTrue();
result.Value.R.ShouldNotEqual(null);
result.Value.Rw.ShouldNotEqual(null);
result.Value.Dw.ShouldNotEqual(null);
result.Value.W.ShouldNotEqual(null);
}
[Test]
public void CommitHooksAreStoredAndLoadedProperly()
{
// when we load, the commit hook lists should be null
RiakResult<RiakBucketProperties> result = Client.GetBucketProperties(bucket);
result.IsSuccess.ShouldBeTrue(result.ErrorMessage);
RiakBucketProperties props = result.Value;
props.PreCommitHooks.ShouldBeNull();
props.PostCommitHooks.ShouldBeNull();
// we then store something in each
props.AddPreCommitHook(new RiakJavascriptCommitHook("Foo.doBar"))
.AddPreCommitHook(new RiakErlangCommitHook("my_mod", "do_fun"))
.AddPostCommitHook(new RiakErlangCommitHook("my_other_mod", "do_more"));
var propResult = Client.SetBucketProperties(bucket, props);
propResult.IsSuccess.ShouldBeTrue(propResult.ErrorMessage);
// load them out again and make sure they got loaded up
Func<RiakResult<RiakBucketProperties>> getFunc = () =>
{
result = Client.GetBucketProperties(bucket);
result.IsSuccess.ShouldBeTrue(result.ErrorMessage);
return result;
};
Func<RiakResult<RiakBucketProperties>, bool> successFunc = (r) =>
{
bool rv = false;
RiakBucketProperties p = r.Value;
if (EnumerableUtil.NotNullOrEmpty(p.PreCommitHooks) &&
EnumerableUtil.NotNullOrEmpty(p.PostCommitHooks))
{
rv = true;
props = p;
}
return rv;
};
getFunc.WaitUntil(successFunc);
props.PreCommitHooks.ShouldNotBeNull();
props.PreCommitHooks.Count.ShouldEqual(2);
props.PostCommitHooks.ShouldNotBeNull();
props.PostCommitHooks.Count.ShouldEqual(1);
}
[Test]
public void CommitHooksAreStoredAndLoadedProperlyInBatch()
{
Client.Batch(batch =>
{
// make sure we're all clear first
var result = batch.GetBucketProperties(bucket);
result.IsSuccess.ShouldBeTrue(result.ErrorMessage);
var props = result.Value;
props.ClearPostCommitHooks().ClearPreCommitHooks();
var propResult = batch.SetBucketProperties(bucket, props);
propResult.IsSuccess.ShouldBeTrue(propResult.ErrorMessage);
// when we load, the commit hook lists should be null
result = batch.GetBucketProperties(bucket);
result.IsSuccess.ShouldBeTrue(result.ErrorMessage);
props = result.Value;
props.PreCommitHooks.ShouldBeNull();
props.PostCommitHooks.ShouldBeNull();
// we then store something in each
props.AddPreCommitHook(new RiakJavascriptCommitHook("Foo.doBar"))
.AddPreCommitHook(new RiakErlangCommitHook("my_mod", "do_fun"))
.AddPostCommitHook(new RiakErlangCommitHook("my_other_mod", "do_more"));
propResult = batch.SetBucketProperties(bucket, props);
propResult.IsSuccess.ShouldBeTrue(propResult.ErrorMessage);
// load them out again and make sure they got loaded up
result = batch.GetBucketProperties(bucket);
result.IsSuccess.ShouldBeTrue(result.ErrorMessage);
props = result.Value;
props.PreCommitHooks.ShouldNotBeNull();
props.PreCommitHooks.Count.ShouldEqual(2);
props.PostCommitHooks.ShouldNotBeNull();
props.PostCommitHooks.Count.ShouldEqual(1);
});
}
[Test]
public void CommitHooksAreStoredAndLoadedProperlyInAsyncBatch()
{
var completed = false;
var task = Client.Async.Batch(batch =>
{
// make sure we're all clear first
var result = batch.GetBucketProperties(bucket);
result.IsSuccess.ShouldBeTrue(result.ErrorMessage);
var props = result.Value;
props.ClearPostCommitHooks().ClearPreCommitHooks();
var propResult = batch.SetBucketProperties(bucket, props);
propResult.IsSuccess.ShouldBeTrue(propResult.ErrorMessage);
// when we load, the commit hook lists should be null
result = batch.GetBucketProperties(bucket);
result.IsSuccess.ShouldBeTrue(result.ErrorMessage);
props = result.Value;
props.PreCommitHooks.ShouldBeNull();
props.PostCommitHooks.ShouldBeNull();
// we then store something in each
props.AddPreCommitHook(new RiakJavascriptCommitHook("Foo.doBar"))
.AddPreCommitHook(new RiakErlangCommitHook("my_mod", "do_fun"))
.AddPostCommitHook(new RiakErlangCommitHook("my_other_mod", "do_more"));
propResult = batch.SetBucketProperties(bucket, props);
propResult.IsSuccess.ShouldBeTrue(propResult.ErrorMessage);
// load them out again and make sure they got loaded up
result = batch.GetBucketProperties(bucket);
result.IsSuccess.ShouldBeTrue(result.ErrorMessage);
props = result.Value;
props.PreCommitHooks.ShouldNotBeNull();
props.PreCommitHooks.Count.ShouldEqual(2);
props.PostCommitHooks.ShouldNotBeNull();
props.PostCommitHooks.Count.ShouldEqual(1);
completed = true;
});
task.Wait();
completed.ShouldBeTrue();
}
[Test]
public void ResettingBucketPropertiesWorksCorrectly()
{
var props = new RiakBucketProperties()
.SetAllowMultiple(true)
.SetDw(10)
.SetW(5)
.SetLastWriteWins(true);
var setPropsResult = Client.SetBucketProperties(bucket, props);
setPropsResult.IsSuccess.ShouldBeTrue(setPropsResult.ErrorMessage);
Func<RiakResult<RiakBucketProperties>> getFunc = () =>
{
var getResult = Client.GetBucketProperties(bucket);
getResult.IsSuccess.ShouldBeTrue(getResult.ErrorMessage);
return getResult;
};
Func<RiakResult<RiakBucketProperties>, bool> successFunc = (r) =>
{
bool rv = false;
if (r.Value.AllowMultiple == props.AllowMultiple &&
r.Value.LastWriteWins == props.LastWriteWins)
{
rv = true;
}
return rv;
};
getFunc.WaitUntil(successFunc);
var resetResult = Client.ResetBucketProperties(bucket);
resetResult.IsSuccess.ShouldBeTrue(resetResult.ErrorMessage);
RiakBucketProperties resetProps = null;
successFunc = (r) =>
{
bool rv = false;
if (r.Value.AllowMultiple != props.AllowMultiple &&
r.Value.LastWriteWins != props.LastWriteWins)
{
rv = true;
resetProps = r.Value;
}
return rv;
};
getFunc.WaitUntil(successFunc);
resetProps.AllowMultiple.ShouldNotEqual(props.AllowMultiple);
resetProps.Dw.ShouldNotEqual(props.Dw);
resetProps.W.ShouldNotEqual(props.W);
resetProps.LastWriteWins.ShouldNotEqual(props.LastWriteWins);
}
[Test]
public void TestNewBucketGivesReplFlagBack()
{
var bucket = "replicants" + _random.Next();
var getInitialPropsResponse = Client.GetBucketProperties(bucket);
new List<RiakConstants.RiakEnterprise.ReplicationMode> {
RiakConstants.RiakEnterprise.ReplicationMode.True,
RiakConstants.RiakEnterprise.ReplicationMode.False
}.ShouldContain(getInitialPropsResponse.Value.ReplicationMode);
}
[Test]
public void TestBucketTypesPropertyWorks()
{
var setsBucketTypeBucketPropsResult = Client.GetBucketProperties(BucketTypeNames.Sets, "Schmoopy");
setsBucketTypeBucketPropsResult.Value.DataType.ShouldEqual("set");
var plainBucketTypeBucketPropsResult = Client.GetBucketProperties("plain", "Schmoopy");
plainBucketTypeBucketPropsResult.Value.DataType.ShouldBeNull();
}
[Test]
public void TestConsistentPropertyOnRegularBucketType()
{
var regProps = Client.GetBucketProperties("plain", "bucket");
regProps.IsSuccess.ShouldBeTrue();
regProps.Value.Consistent.Value.ShouldBeFalse();
}
[Test]
public void TestConsistentPropertyIsNullOnNewProps()
{
var props = new RiakBucketProperties();
props.Consistent.HasValue.ShouldBeFalse();
}
[Test]
public void TestConsistentPropertyOnSCBucketType()
{
var regProps = Client.GetBucketProperties("consistent", "bucket");
regProps.IsSuccess.ShouldBeTrue();
regProps.Value.Consistent.Value.ShouldBeTrue();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics;
using BLToolkit.Reflection;
using BLToolkit.Reflection.Emit;
namespace BLToolkit.TypeBuilder.Builders
{
[DebuggerStepThrough]
public class BuildContext
{
public BuildContext(Type type)
{
_type = type;
}
private TypeHelper _type;
public TypeHelper Type
{
get { return _type; }
//set { _type = value; }
}
private AssemblyBuilderHelper _assemblyBuilder;
public AssemblyBuilderHelper AssemblyBuilder
{
get { return _assemblyBuilder; }
set { _assemblyBuilder = value; }
}
private TypeBuilderHelper _typeBuilder;
public TypeBuilderHelper TypeBuilder
{
get { return _typeBuilder; }
set { _typeBuilder = value; }
}
private readonly Hashtable _items = new Hashtable(100);
public IDictionary Items
{
get { return _items; }
}
class PropertyInfoComparer : IComparer
{
public int Compare(object x, object y)
{
PropertyInfo px = (PropertyInfo)x;
PropertyInfo py = (PropertyInfo)y;
return px.Name.CompareTo(py.Name);
}
}
private static readonly PropertyInfoComparer _piComparer = new PropertyInfoComparer();
private SortedList _fields;
public IDictionary Fields
{
get
{
if (_fields == null)
_fields = new SortedList(_piComparer, 10);
return _fields;
}
}
private IDictionary<TypeHelper, IAbstractTypeBuilder> _interfaceMap;
public IDictionary<TypeHelper, IAbstractTypeBuilder> InterfaceMap
{
get
{
if (_interfaceMap == null)
_interfaceMap = new Dictionary<TypeHelper, IAbstractTypeBuilder>();
return _interfaceMap;
}
}
private TypeHelper _currentInterface;
public TypeHelper CurrentInterface
{
get { return _currentInterface; }
set { _currentInterface = value; }
}
private MethodBuilderHelper _methodBuilder;
public MethodBuilderHelper MethodBuilder
{
get { return _methodBuilder; }
set { _methodBuilder = value; }
}
private LocalBuilder _returnValue;
public LocalBuilder ReturnValue
{
get { return _returnValue; }
set { _returnValue = value; }
}
private LocalBuilder _exception;
public LocalBuilder Exception
{
get { return _exception; }
set { _exception = value; }
}
private Label _returnLabel;
public Label ReturnLabel
{
get { return _returnLabel; }
set { _returnLabel = value; }
}
#region BuildElement
private BuildElement _element;
public BuildElement BuildElement
{
get { return _element; }
set { _element = value; }
}
public bool IsAbstractGetter
{
get { return BuildElement == BuildElement.AbstractGetter; }
}
public bool IsAbstractSetter
{
get { return BuildElement == BuildElement.AbstractSetter; }
}
public bool IsAbstractProperty
{
get { return IsAbstractGetter || IsAbstractSetter; }
}
public bool IsAbstractMethod
{
get { return BuildElement == BuildElement.AbstractMethod; }
}
public bool IsVirtualGetter
{
get { return BuildElement == BuildElement.VirtualGetter; }
}
public bool IsVirtualSetter
{
get { return BuildElement == BuildElement.VirtualSetter; }
}
public bool IsVirtualProperty
{
get { return IsVirtualGetter|| IsVirtualSetter; }
}
public bool IsVirtualMethod
{
get { return BuildElement == BuildElement.VirtualMethod; }
}
public bool IsGetter
{
get { return IsAbstractGetter || IsVirtualGetter; }
}
public bool IsSetter
{
get { return IsAbstractSetter || IsVirtualSetter; }
}
public bool IsProperty
{
get { return IsGetter || IsSetter; }
}
public bool IsMethod
{
get { return IsAbstractMethod || IsVirtualMethod; }
}
public bool IsMethodOrProperty
{
get { return IsMethod || IsProperty; }
}
#endregion
#region BuildStep
private BuildStep _step;
public BuildStep Step
{
get { return _step; }
set { _step = value; }
}
public bool IsBeginStep { get { return Step == BuildStep.Begin; } }
public bool IsBeforeStep { get { return Step == BuildStep.Before; } }
public bool IsBuildStep { get { return Step == BuildStep.Build; } }
public bool IsAfterStep { get { return Step == BuildStep.After; } }
public bool IsCatchStep { get { return Step == BuildStep.Catch; } }
public bool IsFinallyStep { get { return Step == BuildStep.Finally; } }
public bool IsEndStep { get { return Step == BuildStep.End; } }
public bool IsBeforeOrBuildStep
{
get { return Step == BuildStep.Before || Step == BuildStep.Build; }
}
#endregion
private AbstractTypeBuilderList _typeBuilders;
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public AbstractTypeBuilderList TypeBuilders
{
get { return _typeBuilders; }
set { _typeBuilders = value; }
}
private PropertyInfo _currentProperty;
public PropertyInfo CurrentProperty
{
get { return _currentProperty; }
set { _currentProperty = value; }
}
private MethodInfo _currentMethod;
public MethodInfo CurrentMethod
{
get { return _currentMethod; }
set { _currentMethod = value; }
}
#region Internal Methods
public FieldBuilder GetField(string fieldName)
{
return (FieldBuilder)Items["$BLToolkit.Field." + fieldName];
}
public FieldBuilder CreateField(string fieldName, Type type, FieldAttributes attributes)
{
FieldBuilder field = TypeBuilder.DefineField(fieldName, type, attributes);
field.SetCustomAttribute(MethodBuilder.Type.Assembly.BLToolkitAttribute);
Items.Add("$BLToolkit.Field." + fieldName, field);
return field;
}
public FieldBuilder CreatePrivateField(string fieldName, Type type)
{
return CreateField(fieldName, type, FieldAttributes.Private);
}
public FieldBuilder CreatePrivateField(PropertyInfo propertyInfo, string fieldName, Type type)
{
FieldBuilder field = CreateField(fieldName, type, FieldAttributes.Public); // BVChanges: .Private -> .Public
if (propertyInfo != null)
Fields[propertyInfo] = field;
return field;
}
public FieldBuilder CreatePrivateStaticField(string fieldName, Type type)
{
return CreateField(fieldName, type, FieldAttributes.Private | FieldAttributes.Static);
}
public MethodBuilderHelper GetFieldInstanceEnsurer(string fieldName)
{
return (MethodBuilderHelper)Items["$BLToolkit.FieldInstanceEnsurer." + fieldName];
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Maw.Domain.Blogs;
using Maw.Domain.Email;
using Maw.Domain.Identity;
using Maw.Domain.Utilities;
using MawAuth.ViewModels.Admin;
using MawAuth.ViewModels.Email;
using Mvc.RenderViewToString;
using Maw.Security;
namespace MawAuth.Controllers
{
[Authorize(MawPolicy.AdminSite)]
[Route("admin")]
public class AdminController
: Controller
{
readonly ILogger _log;
readonly IUserRepository _repo;
readonly UserManager<MawUser> _userMgr;
readonly RoleManager<MawRole> _roleMgr;
readonly IBlogService _blogSvc;
readonly IEmailService _emailSvc;
readonly RazorViewToStringRenderer _razorRenderer;
readonly IPasswordValidator<MawUser> _pwdValidator;
public AdminController(ILogger<AdminController> log,
IUserRepository userRepository,
UserManager<MawUser> userManager,
RoleManager<MawRole> roleManager,
IBlogService blogService,
IEmailService emailService,
RazorViewToStringRenderer razorRenderer,
IPasswordValidator<MawUser> passwordValidator)
{
_log = log ?? throw new ArgumentNullException(nameof(log));
_repo = userRepository ?? throw new ArgumentNullException(nameof(userRepository));
_userMgr = userManager ?? throw new ArgumentNullException(nameof(userManager));
_roleMgr = roleManager ?? throw new ArgumentNullException(nameof(roleManager));
_blogSvc = blogService ?? throw new ArgumentNullException(nameof(blogService));
_emailSvc = emailService ?? throw new ArgumentNullException(nameof(emailService));
_razorRenderer = razorRenderer ?? throw new ArgumentNullException(nameof(razorRenderer));
_pwdValidator = passwordValidator ?? throw new ArgumentNullException(nameof(passwordValidator));
}
[HttpGet("")]
public IActionResult Index()
{
return View();
}
[HttpGet("manage-users")]
public async Task<IActionResult> ManageUsers()
{
var result = await _repo.GetUsersToManageAsync().ConfigureAwait(false);
var model = result.Select(x => new ManageUserModel
{
Username = x.Username,
FirstName = x.FirstName,
LastName = x.LastName,
Email = x.Email,
LastLoginDate = x.LastLoginDate
});
return View(model);
}
[HttpGet("manage-roles")]
public async Task<IActionResult> ManageRoles()
{
return View(await _repo.GetAllRoleNamesAsync().ConfigureAwait(false));
}
[HttpGet("create-user")]
public IActionResult CreateUser()
{
return View(new CreateUserModel());
}
[HttpPost("create-user")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateUser(CreateUserModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (ModelState.IsValid)
{
var user = new MawUser
{
Username = model.Username,
FirstName = model.FirstName,
LastName = model.LastName,
Email = model.Email
};
var password = await GeneratePassword().ConfigureAwait(false);
model.Result = IdentityResult.Failed();
try
{
model.Result = await _userMgr.CreateAsync(user, password).ConfigureAwait(false);
if (model.Result == IdentityResult.Success)
{
var emailModel = new CreateUserEmailModel
{
Title = "User Account Created",
Username = model.Username,
FirstName = model.FirstName,
Password = password
};
var body = await _razorRenderer.RenderViewToStringAsync("~/Views/Email/CreateUser.cshtml", emailModel).ConfigureAwait(false);
await _emailSvc.SendHtmlAsync(model.Email, _emailSvc.FromAddress, "Account Created for mikeandwan.us", body).ConfigureAwait(false);
}
}
catch (Exception ex)
{
_log.LogError(ex, "error creating user");
model.Result = IdentityResult.Failed(new IdentityError { Description = ex.Message });
}
}
else
{
model.Result = IdentityResult.Failed();
LogValidationErrors();
}
return View(model);
}
[HttpGet("delete-user/{id}")]
public IActionResult DeleteUser(string id)
{
if (string.IsNullOrEmpty(id))
{
RedirectToAction(nameof(Index));
}
var model = new DeleteUserModel
{
Username = id
};
return View(model);
}
[HttpPost("delete-user/{id}")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteUser(DeleteUserModel model, IFormCollection collection)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (ModelState.IsValid)
{
if (collection.Any(x => string.Equals(x.Key, "delete", StringComparison.OrdinalIgnoreCase)))
{
var user = await _userMgr.FindByNameAsync(model.Username).ConfigureAwait(false);
try
{
model.Result = await _userMgr.DeleteAsync(user).ConfigureAwait(false);
return RedirectToAction(nameof(ManageUsers));
}
catch (Exception ex)
{
_log.LogError(ex, "there was an error deleting the user");
}
}
else
{
return RedirectToAction(nameof(ManageUsers));
}
}
else
{
model.Result = IdentityResult.Failed();
LogValidationErrors();
}
return View(model);
}
[HttpGet("create-role")]
public IActionResult CreateRole()
{
return View(new CreateRoleModel());
}
[HttpPost("create-role")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateRole(CreateRoleModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (ModelState.IsValid)
{
var role = new MawRole
{
Name = model.Name,
Description = model.Description
};
model.Result = await _roleMgr.CreateAsync(role).ConfigureAwait(false);
}
else
{
model.Result = IdentityResult.Failed();
LogValidationErrors();
}
return View(model);
}
[HttpGet("delete-role/{id}")]
public IActionResult DeleteRole(string id)
{
if (string.IsNullOrEmpty(id))
{
return RedirectToAction(nameof(Index));
}
var model = new DeleteRoleModel
{
Role = id
};
return View(model);
}
[HttpPost("delete-role/{id}")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteRole(DeleteRoleModel model, IFormCollection collection)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (ModelState.IsValid)
{
if (collection.Any(x => string.Equals(x.Key, "delete", StringComparison.OrdinalIgnoreCase)))
{
var r = await _roleMgr.FindByNameAsync(model.Role).ConfigureAwait(false);
model.Result = await _roleMgr.DeleteAsync(r).ConfigureAwait(false);
return RedirectToAction(nameof(ManageRoles));
}
else
{
return RedirectToAction(nameof(ManageRoles));
}
}
else
{
model.Result = IdentityResult.Failed();
LogValidationErrors();
}
return View(model);
}
[HttpGet("edit-profile/{id}")]
public async Task<IActionResult> EditProfile(string id)
{
if (string.IsNullOrEmpty(id))
{
return RedirectToAction(nameof(Index));
}
var user = await _userMgr.FindByNameAsync(id).ConfigureAwait(false);
if(user == null)
{
return RedirectToAction(nameof(Index));
}
var model = new EditProfileModel
{
Username = user.Username,
FirstName = user.FirstName,
LastName = user.LastName,
Email = user.Email
};
return View(model);
}
[HttpPost("edit-profile/{id}")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EditProfile(EditProfileModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (ModelState.IsValid)
{
var user = await _userMgr.FindByNameAsync(model.Username).ConfigureAwait(false);
if (string.IsNullOrEmpty(user.SecurityStamp))
{
await _userMgr.UpdateSecurityStampAsync(user).ConfigureAwait(false);
}
user.Email = model.Email;
user.FirstName = model.FirstName;
user.LastName = model.LastName;
model.Result = await _userMgr.UpdateAsync(user).ConfigureAwait(false);
}
else
{
model.Result = IdentityResult.Failed();
LogValidationErrors();
}
return View(model);
}
[HttpGet("manage-roles-for-user/{id}")]
public async Task<IActionResult> ManageRolesForUser(string id)
{
if (string.IsNullOrEmpty(id))
{
return RedirectToAction(nameof(Index));
}
var user = await _userMgr.FindByNameAsync(id).ConfigureAwait(false);
var userRoles = await _userMgr.GetRolesAsync(user).ConfigureAwait(false);
var model = new ManageRolesForUserModel {
Username = id
};
model.AllRoles.AddRange(await _repo.GetAllRoleNamesAsync().ConfigureAwait(false));
model.GrantedRoles.AddRange(userRoles);
return View(model);
}
[HttpPost("manage-roles-for-user/{id}")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ManageRolesForUser(IFormCollection collection)
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
string username = collection["Username"];
var model = new ManageRolesForUserModel
{
Username = username
};
model.AllRoles.AddRange(await _repo.GetAllRoleNamesAsync().ConfigureAwait(false));
var user = await _userMgr.FindByNameAsync(username).ConfigureAwait(false);
var currRoles = await _userMgr.GetRolesAsync(user).ConfigureAwait(false);
var newRoleList = new List<string>();
if (!string.IsNullOrEmpty(collection["role"]))
{
newRoleList.AddRange(collection["role"]);
}
var toRemove = currRoles.Where(cm => !newRoleList.Any(nm => string.Equals(cm, nm, StringComparison.OrdinalIgnoreCase)));
var toAdd = newRoleList.Where(nm => !currRoles.Any(cm => string.Equals(cm, nm, StringComparison.OrdinalIgnoreCase)));
var errs = new List<IdentityError>();
_log.LogInformation("new roles: {Roles}", string.Join(", ", newRoleList));
foreach (var role in toRemove)
{
var result = await _userMgr.RemoveFromRoleAsync(user, role).ConfigureAwait(false);
if (!result.Succeeded)
{
errs.AddRange(result.Errors);
}
}
foreach (var role in toAdd)
{
var result = await _userMgr.AddToRoleAsync(user, role).ConfigureAwait(false);
if (!result.Succeeded)
{
errs.AddRange(result.Errors);
}
}
if (errs.Any())
{
model.Result = IdentityResult.Failed(errs.ToArray());
}
else
{
model.Result = IdentityResult.Success;
}
// after the changes, get the new membership info (we are now
user = await _userMgr.FindByNameAsync(username).ConfigureAwait(false);
currRoles = await _userMgr.GetRolesAsync(user).ConfigureAwait(false);
model.GrantedRoles.AddRange(currRoles);
return View(model);
}
[HttpGet("edit-role-members/{id}")]
public async Task<IActionResult> EditRoleMembers(string id)
{
if (string.IsNullOrEmpty(id))
{
RedirectToAction(nameof(Index));
}
var model = new EditRoleMembersModel
{
Role = id
};
model.Members = (await _userMgr.GetUsersInRoleAsync(model.Role).ConfigureAwait(false)).Select(x => x.Username);
model.AllUsers = await _repo.GetAllUsernamesAsync().ConfigureAwait(false);
return View(model);
}
[HttpPost("edit-role-members/{id}")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EditRoleMembers(EditRoleMembersModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
// this follows the same logic as ManageRolesForUser, so see that for more info
if (ModelState.IsValid)
{
var currentMembers = await _userMgr.GetUsersInRoleAsync(model.Role).ConfigureAwait(false);
model.AllUsers = await _repo.GetAllUsernamesAsync().ConfigureAwait(false);
var toRemove = currentMembers.Where(cm => !model.NewMembers.Any(nm => string.Equals(cm.Username, nm, StringComparison.OrdinalIgnoreCase)));
var toAdd = model.NewMembers.Where(nm => !currentMembers.Any(cm => string.Equals(cm.Username, nm, StringComparison.OrdinalIgnoreCase)));
var errs = new List<IdentityError>();
foreach (var newMember in toAdd)
{
var newUser = await _userMgr.FindByNameAsync(newMember).ConfigureAwait(false);
var result = await _userMgr.AddToRoleAsync(newUser, model.Role).ConfigureAwait(false);
if (!result.Succeeded)
{
errs.AddRange(result.Errors);
}
}
foreach (var oldMember in toRemove)
{
_log.LogInformation("Removing user {Username} from role {Role}", oldMember.Username, model.Role);
var result = await _userMgr.RemoveFromRoleAsync(oldMember, model.Role).ConfigureAwait(false);
if (!result.Succeeded)
{
errs.AddRange(result.Errors);
}
}
if (errs.Any())
{
model.Result = IdentityResult.Failed(errs.ToArray());
}
else
{
model.Result = IdentityResult.Success;
}
}
else
{
model.Result = IdentityResult.Failed();
LogValidationErrors();
}
model.Members = (await _userMgr.GetUsersInRoleAsync(model.Role).ConfigureAwait(false)).Select(x => x.Username);
return View(model);
}
protected void LogValidationErrors()
{
var errs = ModelState.Values.SelectMany(v => v.Errors);
foreach (var err in errs)
{
_log.LogWarning("Validation error: {ValidationError}", err.ErrorMessage);
}
}
async Task<string> GeneratePassword()
{
// limit to 100 tries
for (int i = 0; i < 100; i++)
{
var password = CryptoUtils.GeneratePassword(12);
var isValid = await _pwdValidator.ValidateAsync(_userMgr, null, password).ConfigureAwait(false);
if (isValid == IdentityResult.Success)
{
return password;
}
}
throw new InvalidOperationException();
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// DualTextureEffect.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
#endregion
namespace StockEffects
{
/// <summary>
/// Built-in effect that supports two-layer multitexturing.
/// </summary>
public class DualTextureEffect : Effect, IEffectMatrices, IEffectFog
{
#region Effect Parameters
EffectParameter textureParam;
EffectParameter texture2Param;
EffectParameter diffuseColorParam;
EffectParameter fogColorParam;
EffectParameter fogVectorParam;
EffectParameter worldViewProjParam;
EffectParameter shaderIndexParam;
#endregion
#region Fields
bool fogEnabled;
bool vertexColorEnabled;
Matrix world = Matrix.Identity;
Matrix view = Matrix.Identity;
Matrix projection = Matrix.Identity;
Matrix worldView;
Vector3 diffuseColor = Vector3.One;
float alpha = 1;
float fogStart = 0;
float fogEnd = 1;
EffectDirtyFlags dirtyFlags = EffectDirtyFlags.All;
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the world matrix.
/// </summary>
public Matrix World
{
get { return world; }
set
{
world = value;
dirtyFlags |= EffectDirtyFlags.WorldViewProj | EffectDirtyFlags.Fog;
}
}
/// <summary>
/// Gets or sets the view matrix.
/// </summary>
public Matrix View
{
get { return view; }
set
{
view = value;
dirtyFlags |= EffectDirtyFlags.WorldViewProj | EffectDirtyFlags.Fog;
}
}
/// <summary>
/// Gets or sets the projection matrix.
/// </summary>
public Matrix Projection
{
get { return projection; }
set
{
projection = value;
dirtyFlags |= EffectDirtyFlags.WorldViewProj;
}
}
/// <summary>
/// Gets or sets the material diffuse color (range 0 to 1).
/// </summary>
public Vector3 DiffuseColor
{
get { return diffuseColor; }
set
{
diffuseColor = value;
dirtyFlags |= EffectDirtyFlags.MaterialColor;
}
}
/// <summary>
/// Gets or sets the material alpha.
/// </summary>
public float Alpha
{
get { return alpha; }
set
{
alpha = value;
dirtyFlags |= EffectDirtyFlags.MaterialColor;
}
}
/// <summary>
/// Gets or sets the fog enable flag.
/// </summary>
public bool FogEnabled
{
get { return fogEnabled; }
set
{
if (fogEnabled != value)
{
fogEnabled = value;
dirtyFlags |= EffectDirtyFlags.ShaderIndex | EffectDirtyFlags.FogEnable;
}
}
}
/// <summary>
/// Gets or sets the fog start distance.
/// </summary>
public float FogStart
{
get { return fogStart; }
set
{
fogStart = value;
dirtyFlags |= EffectDirtyFlags.Fog;
}
}
/// <summary>
/// Gets or sets the fog end distance.
/// </summary>
public float FogEnd
{
get { return fogEnd; }
set
{
fogEnd = value;
dirtyFlags |= EffectDirtyFlags.Fog;
}
}
/// <summary>
/// Gets or sets the fog color.
/// </summary>
public Vector3 FogColor
{
get { return fogColorParam.GetValueVector3(); }
set { fogColorParam.SetValue(value); }
}
/// <summary>
/// Gets or sets the current base texture.
/// </summary>
public Texture2D Texture
{
get { return textureParam.GetValueTexture2D(); }
set { textureParam.SetValue(value); }
}
/// <summary>
/// Gets or sets the current overlay texture.
/// </summary>
public Texture2D Texture2
{
get { return texture2Param.GetValueTexture2D(); }
set { texture2Param.SetValue(value); }
}
/// <summary>
/// Gets or sets whether vertex color is enabled.
/// </summary>
public bool VertexColorEnabled
{
get { return vertexColorEnabled; }
set
{
if (vertexColorEnabled != value)
{
vertexColorEnabled = value;
dirtyFlags |= EffectDirtyFlags.ShaderIndex;
}
}
}
#endregion
#region Methods
/// <summary>
/// Creates a new DualTextureEffect with default parameter settings.
/// </summary>
public DualTextureEffect(GraphicsDevice device)
: base(device, Resources.DualTextureEffect)
{
CacheEffectParameters();
}
/// <summary>
/// Creates a new DualTextureEffect by cloning parameter settings from an existing instance.
/// </summary>
protected DualTextureEffect(DualTextureEffect cloneSource)
: base(cloneSource)
{
CacheEffectParameters();
fogEnabled = cloneSource.fogEnabled;
vertexColorEnabled = cloneSource.vertexColorEnabled;
world = cloneSource.world;
view = cloneSource.view;
projection = cloneSource.projection;
diffuseColor = cloneSource.diffuseColor;
alpha = cloneSource.alpha;
fogStart = cloneSource.fogStart;
fogEnd = cloneSource.fogEnd;
}
/// <summary>
/// Creates a clone of the current DualTextureEffect instance.
/// </summary>
public override Effect Clone()
{
return new DualTextureEffect(this);
}
/// <summary>
/// Looks up shortcut references to our effect parameters.
/// </summary>
void CacheEffectParameters()
{
textureParam = Parameters["Texture"];
texture2Param = Parameters["Texture2"];
diffuseColorParam = Parameters["DiffuseColor"];
fogColorParam = Parameters["FogColor"];
fogVectorParam = Parameters["FogVector"];
worldViewProjParam = Parameters["WorldViewProj"];
shaderIndexParam = Parameters["ShaderIndex"];
}
/// <summary>
/// Lazily computes derived parameter values immediately before applying the effect.
/// </summary>
protected override void OnApply()
{
// Recompute the world+view+projection matrix or fog vector?
dirtyFlags = EffectHelpers.SetWorldViewProjAndFog(dirtyFlags, ref world, ref view, ref projection, ref worldView, fogEnabled, fogStart, fogEnd, worldViewProjParam, fogVectorParam);
// Recompute the diffuse/alpha material color parameter?
if ((dirtyFlags & EffectDirtyFlags.MaterialColor) != 0)
{
diffuseColorParam.SetValue(new Vector4(diffuseColor * alpha, alpha));
dirtyFlags &= ~EffectDirtyFlags.MaterialColor;
}
// Recompute the shader index?
if ((dirtyFlags & EffectDirtyFlags.ShaderIndex) != 0)
{
int shaderIndex = 0;
if (!fogEnabled)
shaderIndex += 1;
if (vertexColorEnabled)
shaderIndex += 2;
shaderIndexParam.SetValue(shaderIndex);
dirtyFlags &= ~EffectDirtyFlags.ShaderIndex;
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Microsoft.CSharp.RuntimeBinder;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class DynamicExpressionTests
{
public static IEnumerable<object[]> SizesAndSuffixes =>
Enumerable.Range(0, 6).Select(i => new object[] { i, i > 0 & i < 5 ? i.ToString() : "N" });
private static Type[] Types = { typeof(int), typeof(object), typeof(DateTime), typeof(DynamicExpressionTests) };
public static IEnumerable<object[]> SizesAndTypes
=> Enumerable.Range(1, 6).SelectMany(i => Types, (i, t) => new object[] { i, t });
[Theory, MemberData(nameof(SizesAndSuffixes))]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Internal framework reflection not supported on UapAot.")]
public void AritySpecialisedUsedWhenPossible(int size, string nameSuffix)
{
CallSiteBinder binder = Binder.GetMember(
CSharpBinderFlags.None, "Member", GetType(),
new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) });
Type delType = Expression.GetFuncType(
Enumerable.Repeat(typeof(object), size + 1).Prepend(typeof(CallSite)).ToArray());
DynamicExpression exp = DynamicExpression.MakeDynamic(
delType, binder, Enumerable.Range(0, size).Select(_ => Expression.Constant(null)));
Assert.Equal("DynamicExpression" + nameSuffix, exp.GetType().Name);
exp = Expression.MakeDynamic(
delType, binder, Enumerable.Range(0, size).Select(_ => Expression.Constant(null)));
Assert.Equal("DynamicExpression" + nameSuffix, exp.GetType().Name);
if (size != 0)
{
exp = Expression.Dynamic(
binder, typeof(object), Enumerable.Range(0, size).Select(_ => Expression.Constant(null)));
Assert.Equal("DynamicExpression" + nameSuffix, exp.GetType().Name);
}
}
[Theory, MemberData(nameof(SizesAndSuffixes))]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Internal framework reflection not supported on UapAot.")]
public void TypedAritySpecialisedUsedWhenPossible(int size, string nameSuffix)
{
CallSiteBinder binder = Binder.GetMember(
CSharpBinderFlags.None, "Member", GetType(),
new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) });
Type delType = Expression.GetFuncType(
Enumerable.Repeat(typeof(object), size).Append(typeof(string)).Prepend(typeof(CallSite)).ToArray());
DynamicExpression exp = DynamicExpression.MakeDynamic(
delType, binder, Enumerable.Range(0, size).Select(_ => Expression.Constant(null)));
Assert.Equal("TypedDynamicExpression" + nameSuffix, exp.GetType().Name);
exp = Expression.MakeDynamic(
delType, binder, Enumerable.Range(0, size).Select(_ => Expression.Constant(null)));
Assert.Equal("TypedDynamicExpression" + nameSuffix, exp.GetType().Name);
if (size != 0)
{
exp = Expression.Dynamic(
binder, typeof(string), Enumerable.Range(0, size).Select(_ => Expression.Constant(null)));
Assert.Equal("TypedDynamicExpression" + nameSuffix, exp.GetType().Name);
}
}
[Theory, MemberData(nameof(SizesAndTypes))]
public void TypeProperty(int size, Type type)
{
CallSiteBinder binder = Binder.GetMember(
CSharpBinderFlags.None, "Member", GetType(),
new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) });
DynamicExpression exp = Expression.Dynamic(
binder, type, Enumerable.Range(0, size).Select(_ => Expression.Constant(0)));
Assert.Equal(type, exp.Type);
Assert.Equal(ExpressionType.Dynamic, exp.NodeType);
}
[Theory, MemberData(nameof(SizesAndTypes))]
public void Reduce(int size, Type type)
{
CallSiteBinder binder = Binder.GetMember(
CSharpBinderFlags.None, "Member", GetType(),
new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) });
DynamicExpression exp = Expression.Dynamic(
binder, type, Enumerable.Range(0, size).Select(_ => Expression.Constant(0)));
Assert.True(exp.CanReduce);
InvocationExpression reduced = (InvocationExpression)exp.ReduceAndCheck();
Assert.Equal(exp.Arguments, reduced.Arguments.Skip(1));
}
[Theory, MemberData(nameof(SizesAndTypes))]
public void GetArguments(int size, Type type)
{
CallSiteBinder binder = Binder.GetMember(
CSharpBinderFlags.None, "Member", GetType(),
new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) });
ConstantExpression[] arguments = Enumerable.Range(0, size).Select(_ => Expression.Constant(0)).ToArray();
DynamicExpression exp = Expression.Dynamic(binder, type, arguments);
Assert.Equal(arguments, exp.Arguments);
}
[Theory, MemberData(nameof(SizesAndTypes))]
public void ArgumentProvider(int size, Type type)
{
CallSiteBinder binder = Binder.GetMember(
CSharpBinderFlags.None, "Member", GetType(),
new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) });
ConstantExpression[] arguments = Enumerable.Range(0, size).Select(_ => Expression.Constant(0)).ToArray();
IArgumentProvider ap = Expression.Dynamic(binder, type, arguments);
Assert.Equal(size, ap.ArgumentCount);
for (int i = 0; i != size; ++i)
{
Assert.Same(arguments[i], ap.GetArgument(i));
}
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => ap.GetArgument(-1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => ap.GetArgument(size));
}
[Fact]
public void UpdateToSameReturnsSame0()
{
CallSiteBinder binder = Binder.GetMember(
CSharpBinderFlags.None, "Member", GetType(),
new[] {CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)});
DynamicExpression exp = Expression.MakeDynamic(typeof(Func<CallSite, object>), binder);
Assert.Same(exp, exp.Update(null));
Assert.Same(exp, exp.Update(Array.Empty<Expression>()));
Assert.Same(exp, exp.Update(Enumerable.Repeat<Expression>(null, 0)));
Assert.Same(exp, exp.Update(exp.Arguments));
}
[Fact]
public void UpdateToSameReturnsSame1()
{
CallSiteBinder binder = Binder.GetMember(
CSharpBinderFlags.None, "Member", GetType(),
new[] {CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)});
Expression arg = Expression.Constant(null);
DynamicExpression exp = Expression.MakeDynamic(typeof(Func<CallSite, object, object>), binder, arg);
Assert.Same(exp, exp.Update(new[] {arg}));
Assert.Same(exp, exp.Update(Enumerable.Repeat(arg, 1)));
Assert.Same(exp, exp.Update(exp.Arguments));
}
[Fact]
public void UpdateToSameReturnsSame2()
{
CallSiteBinder binder = Binder.GetMember(
CSharpBinderFlags.None, "Member", GetType(),
new[] {CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)});
Expression arg0 = Expression.Constant(null);
Expression arg1 = Expression.Constant(null);
DynamicExpression exp = Expression.MakeDynamic(
typeof(Func<CallSite, object, object, object>), binder, arg0, arg1);
Assert.Same(exp, exp.Update(new[] {arg0, arg1}));
Assert.Same(exp, exp.Update(exp.Arguments));
}
[Fact]
public void UpdateToSameReturnsSame3()
{
CallSiteBinder binder = Binder.GetMember(
CSharpBinderFlags.None, "Member", GetType(),
new[] {CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)});
Expression arg0 = Expression.Constant(null);
Expression arg1 = Expression.Constant(null);
Expression arg2 = Expression.Constant(null);
DynamicExpression exp = Expression.MakeDynamic(
typeof(Func<CallSite, object, object, object, object>), binder, arg0, arg1, arg2);
Assert.Same(exp, exp.Update(new[] {arg0, arg1, arg2}));
Assert.Same(exp, exp.Update(exp.Arguments));
}
[Fact]
public void UpdateToSameReturnsSame4()
{
CallSiteBinder binder = Binder.GetMember(
CSharpBinderFlags.None, "Member", GetType(),
new[] {CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)});
Expression arg0 = Expression.Constant(null);
Expression arg1 = Expression.Constant(null);
Expression arg2 = Expression.Constant(null);
Expression arg3 = Expression.Constant(null);
DynamicExpression exp = Expression.MakeDynamic(
typeof(Func<CallSite, object, object, object, object, object>), binder, arg0, arg1, arg2, arg3);
Assert.Same(exp, exp.Update(new[] {arg0, arg1, arg2, arg3}));
Assert.Same(exp, exp.Update(exp.Arguments));
}
[Fact]
public void UpdateToSameReturnsSame5()
{
CallSiteBinder binder = Binder.GetMember(
CSharpBinderFlags.None, "Member", GetType(),
new[] {CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)});
Expression arg0 = Expression.Constant(null);
Expression arg1 = Expression.Constant(null);
Expression arg2 = Expression.Constant(null);
Expression arg3 = Expression.Constant(null);
Expression arg4 = Expression.Constant(null);
DynamicExpression exp = Expression.MakeDynamic(
typeof(Func<CallSite, object, object, object, object, object, object>), binder, arg0, arg1, arg2, arg3,
arg4);
Assert.Same(exp, exp.Update(new[] {arg0, arg1, arg2, arg3, arg4}));
Assert.Same(exp, exp.Update(exp.Arguments));
}
[Fact]
public void UpdateToSameReturnsSameTyped0()
{
CallSiteBinder binder = Binder.GetMember(
CSharpBinderFlags.None, "Member", GetType(),
new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) });
DynamicExpression exp = Expression.MakeDynamic(typeof(Func<CallSite, string>), binder);
Assert.Same(exp, exp.Update(null));
Assert.Same(exp, exp.Update(Array.Empty<Expression>()));
Assert.Same(exp, exp.Update(Enumerable.Repeat<Expression>(null, 0)));
Assert.Same(exp, exp.Update(exp.Arguments));
}
[Fact]
public void UpdateToSameReturnsSameTyped1()
{
CallSiteBinder binder = Binder.GetMember(
CSharpBinderFlags.None, "Member", GetType(),
new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) });
Expression arg = Expression.Constant(null);
DynamicExpression exp = Expression.MakeDynamic(typeof(Func<CallSite, object, string>), binder, arg);
Assert.Same(exp, exp.Update(new[] { arg }));
Assert.Same(exp, exp.Update(Enumerable.Repeat(arg, 1)));
Assert.Same(exp, exp.Update(exp.Arguments));
}
[Fact]
public void UpdateToSameReturnsSameTyped2()
{
CallSiteBinder binder = Binder.GetMember(
CSharpBinderFlags.None, "Member", GetType(),
new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) });
Expression arg0 = Expression.Constant(null);
Expression arg1 = Expression.Constant(null);
DynamicExpression exp = Expression.MakeDynamic(
typeof(Func<CallSite, object, object, string>), binder, arg0, arg1);
Assert.Same(exp, exp.Update(new[] { arg0, arg1 }));
Assert.Same(exp, exp.Update(exp.Arguments));
}
[Fact]
public void UpdateToSameReturnsSameTyped3()
{
CallSiteBinder binder = Binder.GetMember(
CSharpBinderFlags.None, "Member", GetType(),
new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) });
Expression arg0 = Expression.Constant(null);
Expression arg1 = Expression.Constant(null);
Expression arg2 = Expression.Constant(null);
DynamicExpression exp = Expression.MakeDynamic(
typeof(Func<CallSite, object, object, object, string>), binder, arg0, arg1, arg2);
Assert.Same(exp, exp.Update(new[] { arg0, arg1, arg2 }));
Assert.Same(exp, exp.Update(exp.Arguments));
}
[Fact]
public void UpdateToSameReturnsSameTyped4()
{
CallSiteBinder binder = Binder.GetMember(
CSharpBinderFlags.None, "Member", GetType(),
new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) });
Expression arg0 = Expression.Constant(null);
Expression arg1 = Expression.Constant(null);
Expression arg2 = Expression.Constant(null);
Expression arg3 = Expression.Constant(null);
DynamicExpression exp = Expression.MakeDynamic(
typeof(Func<CallSite, object, object, object, object, string>), binder, arg0, arg1, arg2, arg3);
Assert.Same(exp, exp.Update(new[] { arg0, arg1, arg2, arg3 }));
Assert.Same(exp, exp.Update(exp.Arguments));
}
[Fact]
public void UpdateToSameReturnsSameTyped5()
{
CallSiteBinder binder = Binder.GetMember(
CSharpBinderFlags.None, "Member", GetType(),
new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) });
Expression arg0 = Expression.Constant(null);
Expression arg1 = Expression.Constant(null);
Expression arg2 = Expression.Constant(null);
Expression arg3 = Expression.Constant(null);
Expression arg4 = Expression.Constant(null);
DynamicExpression exp = Expression.MakeDynamic(
typeof(Func<CallSite, object, object, object, object, object, string>), binder, arg0, arg1, arg2, arg3,
arg4);
Assert.Same(exp, exp.Update(new[] { arg0, arg1, arg2, arg3, arg4 }));
Assert.Same(exp, exp.Update(exp.Arguments));
}
[Fact]
public void UpdateToDifferentReturnsDifferent0()
{
CallSiteBinder binder = Binder.GetMember(
CSharpBinderFlags.None, "Member", GetType(),
new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) });
DynamicExpression exp = Expression.MakeDynamic(typeof(Func<CallSite, object>), binder);
// Wrong number of arguments continues to attempt to create new expression, which fails.
AssertExtensions.Throws<ArgumentException>("method", () => exp.Update(new [] {Expression.Constant(null)}));
}
[Fact]
public void UpdateToDifferentReturnsDifferent1()
{
CallSiteBinder binder = Binder.GetMember(
CSharpBinderFlags.None, "Member", GetType(),
new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) });
Expression arg = Expression.Constant(null);
DynamicExpression exp = Expression.MakeDynamic(typeof(Func<CallSite, object, object>), binder, arg);
Assert.NotSame(exp, exp.Update(new[] { Expression.Constant(null) }));
// Wrong number of arguments continues to attempt to create new expression, which fails.
AssertExtensions.Throws<ArgumentException>("method", () => exp.Update(null));
AssertExtensions.Throws<ArgumentException>("method", () => exp.Update(new[] { arg, arg }));
}
[Fact]
public void UpdateToDifferentReturnsDifferent2()
{
CallSiteBinder binder = Binder.GetMember(
CSharpBinderFlags.None, "Member", GetType(),
new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) });
Expression arg0 = Expression.Constant(null);
Expression arg1 = Expression.Constant(null);
DynamicExpression exp = Expression.MakeDynamic(
typeof(Func<CallSite, object, object, object>), binder, arg0, arg1);
Assert.NotSame(exp, exp.Update(new[] { arg0, arg0 }));
Assert.NotSame(exp, exp.Update(new[] { arg1, arg0 }));
// Wrong number of arguments continues to attempt to create new expression, which fails.
AssertExtensions.Throws<ArgumentException>("method", () => exp.Update(null));
AssertExtensions.Throws<ArgumentException>("method", () => exp.Update(new Expression[0]));
}
[Fact]
public void UpdateToDifferentReturnsDifferent3()
{
CallSiteBinder binder = Binder.GetMember(
CSharpBinderFlags.None, "Member", GetType(),
new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) });
Expression arg0 = Expression.Constant(null);
Expression arg1 = Expression.Constant(null);
Expression arg2 = Expression.Constant(null);
DynamicExpression exp = Expression.MakeDynamic(
typeof(Func<CallSite, object, object, object, object>), binder, arg0, arg1, arg2);
Assert.NotSame(exp, exp.Update(new[] { arg1, arg1, arg2 }));
Assert.NotSame(exp, exp.Update(new[] { arg0, arg0, arg2 }));
Assert.NotSame(exp, exp.Update(new[] { arg0, arg1, arg0 }));
// Wrong number of arguments continues to attempt to create new expression, which fails.
AssertExtensions.Throws<ArgumentException>("method", () => exp.Update(null));
AssertExtensions.Throws<ArgumentException>("method", () => exp.Update(new Expression[0]));
}
[Fact]
public void UpdateToDifferentReturnsDifferent4()
{
CallSiteBinder binder = Binder.GetMember(
CSharpBinderFlags.None, "Member", GetType(),
new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) });
Expression arg0 = Expression.Constant(null);
Expression arg1 = Expression.Constant(null);
Expression arg2 = Expression.Constant(null);
Expression arg3 = Expression.Constant(null);
DynamicExpression exp = Expression.MakeDynamic(
typeof(Func<CallSite, object, object, object, object, object>), binder, arg0, arg1, arg2, arg3);
Assert.NotSame(exp, exp.Update(new[] { arg1, arg1, arg2, arg3 }));
Assert.NotSame(exp, exp.Update(new[] { arg0, arg0, arg2, arg3 }));
Assert.NotSame(exp, exp.Update(new[] { arg0, arg1, arg0, arg3 }));
Assert.NotSame(exp, exp.Update(new[] { arg0, arg1, arg2, arg0 }));
// Wrong number of arguments continues to attempt to create new expression, which fails.
AssertExtensions.Throws<ArgumentException>("method", () => exp.Update(null));
AssertExtensions.Throws<ArgumentException>("method", () => exp.Update(new Expression[0]));
}
[Fact]
public void UpdateToDifferentReturnsDifferent5()
{
CallSiteBinder binder = Binder.GetMember(
CSharpBinderFlags.None, "Member", GetType(),
new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) });
Expression arg0 = Expression.Constant(null);
Expression arg1 = Expression.Constant(null);
Expression arg2 = Expression.Constant(null);
Expression arg3 = Expression.Constant(null);
Expression arg4 = Expression.Constant(null);
DynamicExpression exp = Expression.MakeDynamic(
typeof(Func<CallSite, object, object, object, object, object, object>), binder, arg0, arg1, arg2, arg3,
arg4);
Assert.NotSame(exp, exp.Update(new[] { arg1, arg1, arg2, arg3, arg4 }));
Assert.NotSame(exp, exp.Update(new[] { arg0, arg0, arg2, arg3, arg4 }));
Assert.NotSame(exp, exp.Update(new[] { arg0, arg1, arg0, arg3, arg4 }));
Assert.NotSame(exp, exp.Update(new[] { arg0, arg1, arg2, arg0, arg4 }));
Assert.NotSame(exp, exp.Update(new[] { arg0, arg1, arg2, arg3, arg0 }));
// Wrong number of arguments continues to attempt to create new expression, which fails.
AssertExtensions.Throws<ArgumentException>("method", () => exp.Update(null));
AssertExtensions.Throws<ArgumentException>("method", () => exp.Update(new Expression[0]));
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: POGOProtos.Data.Capture.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace POGOProtos.Data.Capture {
/// <summary>Holder for reflection information generated from POGOProtos.Data.Capture.proto</summary>
public static partial class POGOProtosDataCaptureReflection {
#region Descriptor
/// <summary>File descriptor for POGOProtos.Data.Capture.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static POGOProtosDataCaptureReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Ch1QT0dPUHJvdG9zLkRhdGEuQ2FwdHVyZS5wcm90bxIXUE9HT1Byb3Rvcy5E",
"YXRhLkNhcHR1cmUaFlBPR09Qcm90b3MuRW51bXMucHJvdG8aH1BPR09Qcm90",
"b3MuSW52ZW50b3J5Lkl0ZW0ucHJvdG8icgoMQ2FwdHVyZUF3YXJkEjUKDWFj",
"dGl2aXR5X3R5cGUYASADKA4yHi5QT0dPUHJvdG9zLkVudW1zLkFjdGl2aXR5",
"VHlwZRIKCgJ4cBgCIAMoBRINCgVjYW5keRgDIAMoBRIQCghzdGFyZHVzdBgE",
"IAMoBSKVAQoSQ2FwdHVyZVByb2JhYmlsaXR5EjwKDXBva2ViYWxsX3R5cGUY",
"ASADKA4yIS5QT0dPUHJvdG9zLkludmVudG9yeS5JdGVtLkl0ZW1JZEICEAES",
"HwoTY2FwdHVyZV9wcm9iYWJpbGl0eRgCIAMoAkICEAESIAoYcmV0aWNsZV9k",
"aWZmaWN1bHR5X3NjYWxlGAwgASgBUABQAWIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::POGOProtos.Enums.POGOProtosEnumsReflection.Descriptor, global::POGOProtos.Inventory.Item.POGOProtosInventoryItemReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Data.Capture.CaptureAward), global::POGOProtos.Data.Capture.CaptureAward.Parser, new[]{ "ActivityType", "Xp", "Candy", "Stardust" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Data.Capture.CaptureProbability), global::POGOProtos.Data.Capture.CaptureProbability.Parser, new[]{ "PokeballType", "CaptureProbability_", "ReticleDifficultyScale" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class CaptureAward : pb::IMessage<CaptureAward> {
private static readonly pb::MessageParser<CaptureAward> _parser = new pb::MessageParser<CaptureAward>(() => new CaptureAward());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<CaptureAward> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Data.Capture.POGOProtosDataCaptureReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CaptureAward() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CaptureAward(CaptureAward other) : this() {
activityType_ = other.activityType_.Clone();
xp_ = other.xp_.Clone();
candy_ = other.candy_.Clone();
stardust_ = other.stardust_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CaptureAward Clone() {
return new CaptureAward(this);
}
/// <summary>Field number for the "activity_type" field.</summary>
public const int ActivityTypeFieldNumber = 1;
private static readonly pb::FieldCodec<global::POGOProtos.Enums.ActivityType> _repeated_activityType_codec
= pb::FieldCodec.ForEnum(10, x => (int) x, x => (global::POGOProtos.Enums.ActivityType) x);
private readonly pbc::RepeatedField<global::POGOProtos.Enums.ActivityType> activityType_ = new pbc::RepeatedField<global::POGOProtos.Enums.ActivityType>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::POGOProtos.Enums.ActivityType> ActivityType {
get { return activityType_; }
}
/// <summary>Field number for the "xp" field.</summary>
public const int XpFieldNumber = 2;
private static readonly pb::FieldCodec<int> _repeated_xp_codec
= pb::FieldCodec.ForInt32(18);
private readonly pbc::RepeatedField<int> xp_ = new pbc::RepeatedField<int>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<int> Xp {
get { return xp_; }
}
/// <summary>Field number for the "candy" field.</summary>
public const int CandyFieldNumber = 3;
private static readonly pb::FieldCodec<int> _repeated_candy_codec
= pb::FieldCodec.ForInt32(26);
private readonly pbc::RepeatedField<int> candy_ = new pbc::RepeatedField<int>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<int> Candy {
get { return candy_; }
}
/// <summary>Field number for the "stardust" field.</summary>
public const int StardustFieldNumber = 4;
private static readonly pb::FieldCodec<int> _repeated_stardust_codec
= pb::FieldCodec.ForInt32(34);
private readonly pbc::RepeatedField<int> stardust_ = new pbc::RepeatedField<int>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<int> Stardust {
get { return stardust_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as CaptureAward);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(CaptureAward other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!activityType_.Equals(other.activityType_)) return false;
if(!xp_.Equals(other.xp_)) return false;
if(!candy_.Equals(other.candy_)) return false;
if(!stardust_.Equals(other.stardust_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= activityType_.GetHashCode();
hash ^= xp_.GetHashCode();
hash ^= candy_.GetHashCode();
hash ^= stardust_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
activityType_.WriteTo(output, _repeated_activityType_codec);
xp_.WriteTo(output, _repeated_xp_codec);
candy_.WriteTo(output, _repeated_candy_codec);
stardust_.WriteTo(output, _repeated_stardust_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += activityType_.CalculateSize(_repeated_activityType_codec);
size += xp_.CalculateSize(_repeated_xp_codec);
size += candy_.CalculateSize(_repeated_candy_codec);
size += stardust_.CalculateSize(_repeated_stardust_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(CaptureAward other) {
if (other == null) {
return;
}
activityType_.Add(other.activityType_);
xp_.Add(other.xp_);
candy_.Add(other.candy_);
stardust_.Add(other.stardust_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10:
case 8: {
activityType_.AddEntriesFrom(input, _repeated_activityType_codec);
break;
}
case 18:
case 16: {
xp_.AddEntriesFrom(input, _repeated_xp_codec);
break;
}
case 26:
case 24: {
candy_.AddEntriesFrom(input, _repeated_candy_codec);
break;
}
case 34:
case 32: {
stardust_.AddEntriesFrom(input, _repeated_stardust_codec);
break;
}
}
}
}
}
public sealed partial class CaptureProbability : pb::IMessage<CaptureProbability> {
private static readonly pb::MessageParser<CaptureProbability> _parser = new pb::MessageParser<CaptureProbability>(() => new CaptureProbability());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<CaptureProbability> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Data.Capture.POGOProtosDataCaptureReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CaptureProbability() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CaptureProbability(CaptureProbability other) : this() {
pokeballType_ = other.pokeballType_.Clone();
captureProbability_ = other.captureProbability_.Clone();
reticleDifficultyScale_ = other.reticleDifficultyScale_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CaptureProbability Clone() {
return new CaptureProbability(this);
}
/// <summary>Field number for the "pokeball_type" field.</summary>
public const int PokeballTypeFieldNumber = 1;
private static readonly pb::FieldCodec<global::POGOProtos.Inventory.Item.ItemId> _repeated_pokeballType_codec
= pb::FieldCodec.ForEnum(10, x => (int) x, x => (global::POGOProtos.Inventory.Item.ItemId) x);
private readonly pbc::RepeatedField<global::POGOProtos.Inventory.Item.ItemId> pokeballType_ = new pbc::RepeatedField<global::POGOProtos.Inventory.Item.ItemId>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::POGOProtos.Inventory.Item.ItemId> PokeballType {
get { return pokeballType_; }
}
/// <summary>Field number for the "capture_probability" field.</summary>
public const int CaptureProbability_FieldNumber = 2;
private static readonly pb::FieldCodec<float> _repeated_captureProbability_codec
= pb::FieldCodec.ForFloat(18);
private readonly pbc::RepeatedField<float> captureProbability_ = new pbc::RepeatedField<float>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<float> CaptureProbability_ {
get { return captureProbability_; }
}
/// <summary>Field number for the "reticle_difficulty_scale" field.</summary>
public const int ReticleDifficultyScaleFieldNumber = 12;
private double reticleDifficultyScale_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double ReticleDifficultyScale {
get { return reticleDifficultyScale_; }
set {
reticleDifficultyScale_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as CaptureProbability);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(CaptureProbability other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!pokeballType_.Equals(other.pokeballType_)) return false;
if(!captureProbability_.Equals(other.captureProbability_)) return false;
if (ReticleDifficultyScale != other.ReticleDifficultyScale) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= pokeballType_.GetHashCode();
hash ^= captureProbability_.GetHashCode();
if (ReticleDifficultyScale != 0D) hash ^= ReticleDifficultyScale.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
pokeballType_.WriteTo(output, _repeated_pokeballType_codec);
captureProbability_.WriteTo(output, _repeated_captureProbability_codec);
if (ReticleDifficultyScale != 0D) {
output.WriteRawTag(97);
output.WriteDouble(ReticleDifficultyScale);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += pokeballType_.CalculateSize(_repeated_pokeballType_codec);
size += captureProbability_.CalculateSize(_repeated_captureProbability_codec);
if (ReticleDifficultyScale != 0D) {
size += 1 + 8;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(CaptureProbability other) {
if (other == null) {
return;
}
pokeballType_.Add(other.pokeballType_);
captureProbability_.Add(other.captureProbability_);
if (other.ReticleDifficultyScale != 0D) {
ReticleDifficultyScale = other.ReticleDifficultyScale;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10:
case 8: {
pokeballType_.AddEntriesFrom(input, _repeated_pokeballType_codec);
break;
}
case 18:
case 21: {
captureProbability_.AddEntriesFrom(input, _repeated_captureProbability_codec);
break;
}
case 97: {
ReticleDifficultyScale = input.ReadDouble();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
#if !UNITY_WSA && !UNITY_WP8
using System;
using UnityEngine;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading;
using PlayFab.SharedModels;
#if !DISABLE_PLAYFABCLIENT_API
using PlayFab.ClientModels;
#endif
namespace PlayFab.Internal
{
public class PlayFabWebRequest : ITransportPlugin
{
/// <summary>
/// Disable encryption certificate validation within PlayFabWebRequest using this request.
/// This is not generally recommended.
/// As of early 2018:
/// None of the built-in Unity mechanisms validate the certificate, using .Net 3.5 equivalent runtime
/// It is also not currently feasible to provide a single cross platform solution that will correctly validate a certificate.
/// The Risk:
/// All Unity HTTPS mechanisms are vulnerable to Man-In-The-Middle attacks.
/// The only more-secure option is to define a custom CustomCertValidationHook, specifically tailored to the platforms you support,
/// which validate the cert based on a list of trusted certificate providers. This list of providers must be able to update itself, as the
/// base certificates for those providers will also expire and need updating on a regular basis.
/// </summary>
public static void SkipCertificateValidation()
{
var rcvc = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications); //(sender, cert, chain, ssl) => true
ServicePointManager.ServerCertificateValidationCallback = rcvc;
certValidationSet = true;
}
/// <summary>
/// Provide PlayFabWebRequest with a custom ServerCertificateValidationCallback which can be used to validate the PlayFab encryption certificate.
/// Please do not:
/// - Hard code the current PlayFab certificate information - The PlayFab certificate updates itself on a regular schedule, and your game will fail and require a republish to fix
/// - Hard code a list of static certificate authorities - Any single exported list of certificate authorities will become out of date, and have the same problem when the CA cert expires
/// Real solution:
/// - A mechanism where a valid certificate authority list can be securely downloaded and updated without republishing the client when existing certificates expire.
/// </summary>
public static System.Net.Security.RemoteCertificateValidationCallback CustomCertValidationHook
{
set
{
ServicePointManager.ServerCertificateValidationCallback = value;
certValidationSet = true;
}
}
private static readonly Queue<Action> ResultQueueTransferThread = new Queue<Action>();
private static readonly Queue<Action> ResultQueueMainThread = new Queue<Action>();
private static readonly List<CallRequestContainer> ActiveRequests = new List<CallRequestContainer>();
private static bool certValidationSet = false;
private static Thread _requestQueueThread;
private static readonly object _ThreadLock = new object();
private static readonly TimeSpan ThreadKillTimeout = TimeSpan.FromSeconds(60);
private static DateTime _threadKillTime = DateTime.UtcNow + ThreadKillTimeout; // Kill the thread after 1 minute of inactivity
private static bool _isApplicationPlaying;
private static int _activeCallCount;
private static string _unityVersion;
private bool _isInitialized = false;
public bool IsInitialized { get { return _isInitialized; } }
public void Initialize()
{
SetupCertificates();
_isApplicationPlaying = true;
_unityVersion = Application.unityVersion;
_isInitialized = true;
}
public void OnDestroy()
{
_isApplicationPlaying = false;
lock (ResultQueueTransferThread)
{
ResultQueueTransferThread.Clear();
}
lock (ActiveRequests)
{
ActiveRequests.Clear();
}
lock (_ThreadLock)
{
_requestQueueThread = null;
}
}
private void SetupCertificates()
{
// These are performance Optimizations for HttpWebRequests.
ServicePointManager.DefaultConnectionLimit = 10;
ServicePointManager.Expect100Continue = false;
if (!certValidationSet)
{
Debug.LogWarning("PlayFab API calls will likely fail because you have not set up a HttpWebRequest certificate validation mechanism");
Debug.LogWarning("Please set a validation callback into PlayFab.Internal.PlayFabWebRequest.CustomCertValidationHook, or set PlayFab.Internal.PlayFabWebRequest.SkipCertificateValidation()");
}
}
/// <summary>
/// This disables certificate validation, if it's been activated by a customer via SkipCertificateValidation()
/// </summary>
private static bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true;
}
public void SimpleGetCall(string fullUrl, Action<byte[]> successCallback, Action<string> errorCallback)
{
// This needs to be improved to use a decent thread-pool, but it can be improved invisibly later
var newThread = new Thread(() => SimpleHttpsWorker("GET", fullUrl, null, successCallback, errorCallback));
newThread.Start();
}
public void SimplePutCall(string fullUrl, byte[] payload, Action<byte[]> successCallback, Action<string> errorCallback)
{
// This needs to be improved to use a decent thread-pool, but it can be improved invisibly later
var newThread = new Thread(() => SimpleHttpsWorker("PUT", fullUrl, payload, successCallback, errorCallback));
newThread.Start();
}
public void SimplePostCall(string fullUrl, byte[] payload, Action<byte[]> successCallback, Action<string> errorCallback)
{
// This needs to be improved to use a decent thread-pool, but it can be improved invisibly later
var newThread = new Thread(() => SimpleHttpsWorker("POST", fullUrl, payload, successCallback, errorCallback));
newThread.Start();
}
private void SimpleHttpsWorker(string httpMethod, string fullUrl, byte[] payload, Action<byte[]> successCallback, Action<string> errorCallback)
{
// This should also use a pooled HttpWebRequest object, but that too can be improved invisibly later
var httpRequest = (HttpWebRequest)WebRequest.Create(fullUrl);
httpRequest.UserAgent = "UnityEngine-Unity; Version: " + _unityVersion;
httpRequest.Method = httpMethod;
httpRequest.KeepAlive = PlayFabSettings.RequestKeepAlive;
httpRequest.Timeout = PlayFabSettings.RequestTimeout;
httpRequest.AllowWriteStreamBuffering = false;
httpRequest.ReadWriteTimeout = PlayFabSettings.RequestTimeout;
if (payload != null)
{
httpRequest.ContentLength = payload.LongLength;
using (var stream = httpRequest.GetRequestStream())
{
stream.Write(payload, 0, payload.Length);
}
}
try
{
var response = httpRequest.GetResponse();
byte[] output = null;
using (var responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
output = new byte[response.ContentLength];
responseStream.Read(output, 0, output.Length);
}
}
successCallback(output);
}
catch (WebException webException)
{
try
{
using (var responseStream = webException.Response.GetResponseStream())
{
if (responseStream != null)
using (var stream = new StreamReader(responseStream))
errorCallback(stream.ReadToEnd());
}
}
catch (Exception e)
{
Debug.LogException(e);
}
}
catch (Exception e)
{
Debug.LogException(e);
}
}
public void MakeApiCall(object reqContainerObj)
{
CallRequestContainer reqContainer = (CallRequestContainer)reqContainerObj;
reqContainer.HttpState = HttpRequestState.Idle;
lock (ActiveRequests)
{
ActiveRequests.Insert(0, reqContainer);
}
ActivateThreadWorker();
}
private static void ActivateThreadWorker()
{
lock (_ThreadLock)
{
if (_requestQueueThread != null)
{
return;
}
_requestQueueThread = new Thread(WorkerThreadMainLoop);
_requestQueueThread.Start();
}
}
private static void WorkerThreadMainLoop()
{
try
{
bool active;
lock (_ThreadLock)
{
// Kill the thread after 1 minute of inactivity
_threadKillTime = DateTime.UtcNow + ThreadKillTimeout;
}
List<CallRequestContainer> localActiveRequests = new List<CallRequestContainer>();
do
{
//process active requests
lock (ActiveRequests)
{
localActiveRequests.AddRange(ActiveRequests);
ActiveRequests.Clear();
_activeCallCount = localActiveRequests.Count;
}
var activeCalls = localActiveRequests.Count;
for (var i = activeCalls - 1; i >= 0; i--) // We must iterate backwards, because we remove at index i in some cases
{
switch (localActiveRequests[i].HttpState)
{
case HttpRequestState.Error:
localActiveRequests.RemoveAt(i); break;
case HttpRequestState.Idle:
Post(localActiveRequests[i]); break;
case HttpRequestState.Sent:
if (localActiveRequests[i].HttpRequest.HaveResponse) // Else we'll try again next tick
ProcessHttpResponse(localActiveRequests[i]);
break;
case HttpRequestState.Received:
ProcessJsonResponse(localActiveRequests[i]);
localActiveRequests.RemoveAt(i);
break;
}
}
#region Expire Thread.
// Check if we've been inactive
lock (_ThreadLock)
{
var now = DateTime.UtcNow;
if (activeCalls > 0 && _isApplicationPlaying)
{
// Still active, reset the _threadKillTime
_threadKillTime = now + ThreadKillTimeout;
}
// Kill the thread after 1 minute of inactivity
active = now <= _threadKillTime;
if (!active)
{
_requestQueueThread = null;
}
// This thread will be stopped, so null this now, inside lock (_threadLock)
}
#endregion
Thread.Sleep(1);
} while (active);
}
catch (Exception e)
{
Debug.LogException(e);
_requestQueueThread = null;
}
}
private static void Post(CallRequestContainer reqContainer)
{
try
{
reqContainer.HttpRequest = (HttpWebRequest)WebRequest.Create(reqContainer.FullUrl);
reqContainer.HttpRequest.UserAgent = "UnityEngine-Unity; Version: " + _unityVersion;
reqContainer.HttpRequest.SendChunked = false;
// Prevents hitting a proxy if no proxy is available. TODO: Add support for proxy's.
reqContainer.HttpRequest.Proxy = null;
foreach (var pair in reqContainer.RequestHeaders)
reqContainer.HttpRequest.Headers.Add(pair.Key, pair.Value);
reqContainer.HttpRequest.ContentType = "application/json";
reqContainer.HttpRequest.Method = "POST";
reqContainer.HttpRequest.KeepAlive = PlayFabSettings.RequestKeepAlive;
reqContainer.HttpRequest.Timeout = PlayFabSettings.RequestTimeout;
reqContainer.HttpRequest.AllowWriteStreamBuffering = false;
reqContainer.HttpRequest.Proxy = null;
reqContainer.HttpRequest.ContentLength = reqContainer.Payload.LongLength;
reqContainer.HttpRequest.ReadWriteTimeout = PlayFabSettings.RequestTimeout;
//Debug.Log("Get Stream");
// Get Request Stream and send data in the body.
using (var stream = reqContainer.HttpRequest.GetRequestStream())
{
//Debug.Log("Post Stream");
stream.Write(reqContainer.Payload, 0, reqContainer.Payload.Length);
//Debug.Log("After Post stream");
}
reqContainer.HttpState = HttpRequestState.Sent;
}
catch (WebException e)
{
reqContainer.JsonResponse = ResponseToString(e.Response) ?? e.Status + ": WebException making http request to: " + reqContainer.FullUrl;
var enhancedError = new WebException(reqContainer.JsonResponse, e);
Debug.LogException(enhancedError);
QueueRequestError(reqContainer);
}
catch (Exception e)
{
reqContainer.JsonResponse = "Unhandled exception in Post : " + reqContainer.FullUrl;
var enhancedError = new Exception(reqContainer.JsonResponse, e);
Debug.LogException(enhancedError);
QueueRequestError(reqContainer);
}
}
private static void ProcessHttpResponse(CallRequestContainer reqContainer)
{
try
{
#if PLAYFAB_REQUEST_TIMING
reqContainer.Timing.WorkerRequestMs = (int)reqContainer.Stopwatch.ElapsedMilliseconds;
#endif
// Get and check the response
var httpResponse = (HttpWebResponse)reqContainer.HttpRequest.GetResponse();
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
reqContainer.JsonResponse = ResponseToString(httpResponse);
}
if (httpResponse.StatusCode != HttpStatusCode.OK || string.IsNullOrEmpty(reqContainer.JsonResponse))
{
reqContainer.JsonResponse = reqContainer.JsonResponse ?? "No response from server";
QueueRequestError(reqContainer);
return;
}
else
{
// Response Recieved Successfully, now process.
}
reqContainer.HttpState = HttpRequestState.Received;
}
catch (Exception e)
{
var msg = "Unhandled exception in ProcessHttpResponse : " + reqContainer.FullUrl;
reqContainer.JsonResponse = reqContainer.JsonResponse ?? msg;
var enhancedError = new Exception(msg, e);
Debug.LogException(enhancedError);
QueueRequestError(reqContainer);
}
}
/// <summary>
/// Set the reqContainer into an error state, and queue it to invoke the ErrorCallback for that request
/// </summary>
private static void QueueRequestError(CallRequestContainer reqContainer)
{
reqContainer.Error = PlayFabHttp.GeneratePlayFabError(reqContainer.ApiEndpoint, reqContainer.JsonResponse, reqContainer.CustomData); // Decode the server-json error
reqContainer.HttpState = HttpRequestState.Error;
lock (ResultQueueTransferThread)
{
//Queue The result callbacks to run on the main thread.
ResultQueueTransferThread.Enqueue(() =>
{
PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, reqContainer.Error);
if (reqContainer.ErrorCallback != null)
reqContainer.ErrorCallback(reqContainer.Error);
});
}
}
private static void ProcessJsonResponse(CallRequestContainer reqContainer)
{
try
{
var serializer = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer);
var httpResult = serializer.DeserializeObject<HttpResponseObject>(reqContainer.JsonResponse);
#if PLAYFAB_REQUEST_TIMING
reqContainer.Timing.WorkerRequestMs = (int)reqContainer.Stopwatch.ElapsedMilliseconds;
#endif
//This would happen if playfab returned a 500 internal server error or a bad json response.
if (httpResult == null || httpResult.code != 200)
{
QueueRequestError(reqContainer);
return;
}
reqContainer.JsonResponse = serializer.SerializeObject(httpResult.data);
reqContainer.DeserializeResultJson(); // Assigns Result with a properly typed object
reqContainer.ApiResult.Request = reqContainer.ApiRequest;
reqContainer.ApiResult.CustomData = reqContainer.CustomData;
if(_isApplicationPlaying)
{
PlayFabHttp.instance.OnPlayFabApiResult(reqContainer);
}
#if !DISABLE_PLAYFABCLIENT_API
lock (ResultQueueTransferThread)
{
ResultQueueTransferThread.Enqueue(() => { PlayFabDeviceUtil.OnPlayFabLogin(reqContainer.ApiResult, reqContainer.settings, reqContainer.instanceApi); });
}
#endif
lock (ResultQueueTransferThread)
{
//Queue The result callbacks to run on the main thread.
ResultQueueTransferThread.Enqueue(() =>
{
#if PLAYFAB_REQUEST_TIMING
reqContainer.Stopwatch.Stop();
reqContainer.Timing.MainThreadRequestMs = (int)reqContainer.Stopwatch.ElapsedMilliseconds;
PlayFabHttp.SendRequestTiming(reqContainer.Timing);
#endif
try
{
PlayFabHttp.SendEvent(reqContainer.ApiEndpoint, reqContainer.ApiRequest, reqContainer.ApiResult, ApiProcessingEventType.Post);
reqContainer.InvokeSuccessCallback();
}
catch (Exception e)
{
Debug.LogException(e); // Log the user's callback exception back to them without halting PlayFabHttp
}
});
}
}
catch (Exception e)
{
var msg = "Unhandled exception in ProcessJsonResponse : " + reqContainer.FullUrl;
reqContainer.JsonResponse = reqContainer.JsonResponse ?? msg;
var enhancedError = new Exception(msg, e);
Debug.LogException(enhancedError);
QueueRequestError(reqContainer);
}
}
public void Update()
{
lock (ResultQueueTransferThread)
{
while (ResultQueueTransferThread.Count > 0)
{
var actionToQueue = ResultQueueTransferThread.Dequeue();
ResultQueueMainThread.Enqueue(actionToQueue);
}
}
while (ResultQueueMainThread.Count > 0)
{
var finishedRequest = ResultQueueMainThread.Dequeue();
finishedRequest();
}
}
private static string ResponseToString(WebResponse webResponse)
{
if (webResponse == null)
return null;
try
{
using (var responseStream = webResponse.GetResponseStream())
{
if (responseStream == null)
return null;
using (var stream = new StreamReader(responseStream))
{
return stream.ReadToEnd();
}
}
}
catch (WebException webException)
{
try
{
using (var responseStream = webException.Response.GetResponseStream())
{
if (responseStream == null)
return null;
using (var stream = new StreamReader(responseStream))
{
return stream.ReadToEnd();
}
}
}
catch (Exception e)
{
Debug.LogException(e);
return null;
}
}
catch (Exception e)
{
Debug.LogException(e);
return null;
}
}
public int GetPendingMessages()
{
var count = 0;
lock (ActiveRequests)
count += ActiveRequests.Count + _activeCallCount;
lock (ResultQueueTransferThread)
count += ResultQueueTransferThread.Count;
return count;
}
}
}
#endif
| |
#define FSHARP
// F#: Added CodeTypeReferenceExpression as a target where calling static methods
// Added casting where assigning inherited class to variable of base type
//
/*
Currently there is the following porblem:
#light
type ISome =
interface
abstract InterfaceMethod : int -> int
end
and Test =
class
interface ISome with
member this.InterfaceMethod (a) =
a + 5
end
end
>>> error: The type 'ISome' is not an interface type.
*/
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Reflection;
using Microsoft.Samples.CodeDomTestSuite;
public class DeclareMethod : CodeDomTestTree {
public override TestTypes TestType {
get {
return TestTypes.Everett;
}
}
public override bool ShouldCompile {
get {
return true;
}
}
public override bool ShouldVerify {
get {
return true;
}
}
public override string Name {
get {
return "DeclareMethod";
}
}
public override string Description {
get {
return "Tests declaration of methods.";
}
}
public override CompilerParameters GetCompilerParameters (CodeDomProvider provider) {
CompilerParameters parms = base.GetCompilerParameters (provider);
// some languages don't compile correctly if no executable is
// generated and an entry point is defined
if (Supports (provider, GeneratorSupport.EntryPointMethod)) {
parms.GenerateExecutable = true;
}
return parms;
}
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {
CodeNamespace nspace = new CodeNamespace ("NSPC");
nspace.Imports.Add (new CodeNamespaceImport ("System"));
cu.Namespaces.Add (nspace);
CodeTypeDeclaration cd = new CodeTypeDeclaration ("TEST");
cd.IsClass = true;
nspace.Types.Add (cd);
if (Supports (provider, GeneratorSupport.ReferenceParameters)) {
//************** static internal method with parameters with out and ref directions, **************
//************** and void return type **************
// GENERATES (C#):
// /*FamANDAssem*/ internal static void Work(ref int i, out int j) {
// i = (i + 4);
// j = 5;
// }
CodeMemberMethod cmm1 = new CodeMemberMethod ();
cmm1.Name = "Work";
cmm1.ReturnType = new CodeTypeReference ("System.void");
cmm1.Attributes = MemberAttributes.Static | MemberAttributes.FamilyAndAssembly;
// add parameter with ref direction
CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression (typeof (int), "i");
param.Direction = FieldDirection.Ref;
cmm1.Parameters.Add (param);
// add parameter with out direction
param = new CodeParameterDeclarationExpression (typeof (int), "j");
param.Direction = FieldDirection.Out;
cmm1.Parameters.Add (param);
cmm1.Statements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("i"),
new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"),
CodeBinaryOperatorType.Add, new CodePrimitiveExpression (4))));
cmm1.Statements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("j"),
new CodePrimitiveExpression (5)));
cd.Members.Add (cmm1);
}
// ********* pass by value using a protected method ******
// GENERATES (C#):
// protected static int ProtectedMethod(int a) {
// return a;
// }
CodeMemberMethod cmm = new CodeMemberMethod ();
cmm.Name = "ProtectedMethod";
cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a"));
cmm.Attributes = MemberAttributes.Family | MemberAttributes.Static;
cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a")));
cmm.ReturnType = new CodeTypeReference (typeof (int));
cd.Members.Add (cmm);
// declare a method to test the protected method with new attribute
// GENERATES (C#):
// public static int CallProtected(int a) {
// return (a + ProtectedMethod(a));
// }
AddScenario ("CheckCallProtected");
cmm = new CodeMemberMethod ();
cmm.ReturnType = new CodeTypeReference (typeof (int));
cmm.Name = "CallProtected";
cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a"));
cmm.Attributes = MemberAttributes.Public;
CodeMethodReferenceExpression meth = new CodeMethodReferenceExpression ();
meth.MethodName = "ProtectedMethod";
meth.TargetObject = new CodeTypeReferenceExpression("TEST2");
cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("a"),
CodeBinaryOperatorType.Add, new CodeMethodInvokeExpression (meth, new CodeArgumentReferenceExpression ("a")))));
cd.Members.Add (cmm);
// GENERATES (C#):
// public static void Main() {
// }
if (Supports (provider, GeneratorSupport.EntryPointMethod)) {
CodeEntryPointMethod cep = new CodeEntryPointMethod ();
cd.Members.Add (cep);
}
// add a second class
cd = new CodeTypeDeclaration ("TEST2");
cd.BaseTypes.Add (new CodeTypeReference ("TEST"));
cd.IsClass = true;
nspace.Types.Add (cd);
if (Supports (provider, GeneratorSupport.ReferenceParameters)) {
// GENERATES (C#):
// public static int CallingWork(int a) {
// a = 10;
// int b;
// TEST.Work(ref a, out b);
// return (a + b);
// }
AddScenario ("CheckCallingWork");
cmm = new CodeMemberMethod ();
cmm.Name = "CallingWork";
cmm.Attributes = MemberAttributes.Public;
CodeParameterDeclarationExpression parames = new CodeParameterDeclarationExpression (typeof (int), "a");
cmm.Parameters.Add (parames);
cmm.ReturnType = new CodeTypeReference ("System.Int32");
cmm.Statements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("a"),
new CodePrimitiveExpression (10)));
cmm.Statements.Add (new CodeVariableDeclarationStatement (typeof (int), "b"));
// invoke the method called "work"
CodeMethodInvokeExpression methodinvoked = new CodeMethodInvokeExpression (new CodeTypeReferenceExpression ("TEST"), "Work");
// add parameter with ref direction
CodeDirectionExpression parameter = new CodeDirectionExpression (FieldDirection.Ref,
new CodeArgumentReferenceExpression ("a"));
methodinvoked.Parameters.Add (parameter);
// add parameter with out direction
parameter = new CodeDirectionExpression (FieldDirection.Out, new CodeVariableReferenceExpression ("b"));
methodinvoked.Parameters.Add (parameter);
cmm.Statements.Add (methodinvoked);
cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression
(new CodeArgumentReferenceExpression ("a"), CodeBinaryOperatorType.Add, new CodeVariableReferenceExpression ("b"))));
cd.Members.Add (cmm);
}
// ***** declare a private method with value return type ******
// GENERATES (C#):
// private static int PrivateMethod() {
// return 5;
// }
cmm = new CodeMemberMethod ();
cmm.Name = "PrivateMethod";
cmm.Attributes = MemberAttributes.Private | MemberAttributes.Static;
cmm.Statements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (5)));
cmm.ReturnType = new CodeTypeReference (typeof (int));
cd.Members.Add (cmm);
// declare a method to test the private method
// GENERATES (C#):
// public static int CallPrivateMethod(int a) {
// return (a + PrivateMethod());
// }
AddScenario ("CheckCallPrivateMethod");
cmm = new CodeMemberMethod ();
cmm.ReturnType = new CodeTypeReference (typeof (int));
cmm.Name = "CallPrivateMethod";
cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a"));
cmm.Attributes = MemberAttributes.Public;
meth = new CodeMethodReferenceExpression ();
meth.TargetObject = new CodeTypeReferenceExpression("TEST2");
meth.MethodName = "PrivateMethod";
cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("a"),
CodeBinaryOperatorType.Add, new CodeMethodInvokeExpression (meth))));
cd.Members.Add (cmm);
// ********* pass by value using a protected static method ******
// this class needs to inherit from the first class so that we can call the protected method from here and call the
// public method that calls the protected method from that class
// declare a method to test the protected method
// GENERATES (C#):
// public static int CallProtectedAndPublic(int a) {
// return (CallProtected(a) + ProtectedMethod(a));
// }
AddScenario ("CheckCallProtectedAndPublic");
cmm = new CodeMemberMethod ();
cmm.ReturnType = new CodeTypeReference (typeof (int));
cmm.Name = "CallProtectedAndPublic";
cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a"));
cmm.Attributes = MemberAttributes.Public;
meth = new CodeMethodReferenceExpression ();
meth.MethodName = "ProtectedMethod";
meth.TargetObject = new CodeTypeReferenceExpression("TEST2");
CodeMethodReferenceExpression meth2 = new CodeMethodReferenceExpression ();
meth2.MethodName = "CallProtected";
cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (new CodeMethodInvokeExpression (meth2,
new CodeArgumentReferenceExpression ("a")),
CodeBinaryOperatorType.Add, new CodeMethodInvokeExpression (meth,
new CodeArgumentReferenceExpression ("a")))));
cd.Members.Add (cmm);
if (Supports (provider, GeneratorSupport.DeclareInterfaces)) {
// ******** implement a single public interface ***********
// declare an interface
// GENERATES (C#):
// public interface TEST3 {
// int InterfaceMethod(int a);
// }
cd = new CodeTypeDeclaration ("TEST3");
cd.IsInterface = true;
nspace.Types.Add (cd);
cmm = new CodeMemberMethod ();
cmm.Name = "InterfaceMethod";
cmm.ReturnType = new CodeTypeReference (typeof (int));
cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a"));
cd.Members.Add (cmm);
// implement the interface
// GENERATES (C#):
// public class TEST3b : object, TEST3 {
// public virtual int InterfaceMethod(int a) {
// return a;
// }
// }
cd = new CodeTypeDeclaration ("TEST3b");
cd.BaseTypes.Add (new CodeTypeReference ("System.Object"));
cd.BaseTypes.Add (new CodeTypeReference ("TEST3"));
cd.IsClass = true;
nspace.Types.Add (cd);
cmm = new CodeMemberMethod ();
cmm.Name = "InterfaceMethod";
cmm.ReturnType = new CodeTypeReference (typeof (int));
cmm.ImplementationTypes.Add (new CodeTypeReference ("TEST3"));
cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a"));
cmm.Attributes = MemberAttributes.Public;
cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a")));
cd.Members.Add (cmm);
// ********implement two interfaces with overloading method name*******
// declare the second interface
// GENERATES (C#):
// public interface TEST4 {
// int InterfaceMethod(int a);
// }
cd = new CodeTypeDeclaration ("TEST4");
cd.IsInterface = true;
nspace.Types.Add (cd);
cmm = new CodeMemberMethod ();
cmm.Name = "InterfaceMethod";
cmm.ReturnType = new CodeTypeReference (typeof (int));
cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a"));
cd.Members.Add (cmm);
// implement both of the interfaces
// GENERATES (C#):
// public class TEST4b : object, TEST3, TEST4 {
// public int InterfaceMethod(int a) {
// return a;
// }
// }
cd = new CodeTypeDeclaration ("TEST4b");
cd.BaseTypes.Add (new CodeTypeReference ("System.Object"));
cd.BaseTypes.Add (new CodeTypeReference ("TEST3"));
cd.BaseTypes.Add (new CodeTypeReference ("TEST4"));
cd.IsClass = true;
nspace.Types.Add (cd);
cmm = new CodeMemberMethod ();
cmm.Name = "InterfaceMethod";
cmm.ImplementationTypes.Add (new CodeTypeReference ("TEST3"));
cmm.ImplementationTypes.Add (new CodeTypeReference ("TEST4"));
cmm.ReturnType = new CodeTypeReference (typeof (int));
cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a"));
cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a")));
cd.Members.Add (cmm);
}
// create a class which will have a method to call the method name that was overloaded
// this class will also call a method in the class that implements the private implements testcase
cd = new CodeTypeDeclaration ("TEST5");
cd.IsClass = true;
nspace.Types.Add (cd);
if (Supports (provider, GeneratorSupport.DeclareInterfaces)) {
// GENERATES (C#):
// public static int TestMultipleInterfaces(int i) {
// TEST4b t = new TEST4b();
// TEST3 TEST3 = ((TEST3)(t));
// TEST4 TEST4 = ((TEST4)(t));
// return (TEST3.InterfaceMethod(i) - TEST4.InterfaceMethod(i));
// }
AddScenario ("CheckTestMultipleInterfaces");
cmm = new CodeMemberMethod ();
cmm.Name = "TestMultipleInterfaces";
cmm.ReturnType = new CodeTypeReference (typeof (int));
cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i"));
cmm.Attributes = MemberAttributes.Public;
cmm.Statements.Add (new CodeVariableDeclarationStatement ("TEST4b", "t", new CodeObjectCreateExpression ("TEST4b")));
cmm.Statements.Add (new CodeVariableDeclarationStatement ("TEST3", "TEST3", new CodeCastExpression ("TEST3",
new CodeVariableReferenceExpression ("t"))));
cmm.Statements.Add (new CodeVariableDeclarationStatement ("TEST4", "TEST4", new CodeCastExpression ("TEST4",
new CodeVariableReferenceExpression ("t"))));
CodeMethodInvokeExpression methodinvoking = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("TEST3")
, "InterfaceMethod");
methodinvoking.Parameters.Add (new CodeArgumentReferenceExpression ("i"));
CodeMethodInvokeExpression methodinvoking2 = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("TEST4")
, "InterfaceMethod");
methodinvoking2.Parameters.Add (new CodeArgumentReferenceExpression ("i"));
cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (
methodinvoking, CodeBinaryOperatorType.Subtract, methodinvoking2)));
cd.Members.Add (cmm);
// GENERATES (C#):
// public static int PrivateImplements(int i) {
// TEST6 t = new TEST6();
// TEST3 TEST3 = ((TEST3)(t));
// TEST4 TEST4 = ((TEST4)(t));
// return (TEST3.InterfaceMethod(i) - TEST4.InterfaceMethod(i));
// }
AddScenario ("CheckPrivateImplements");
cmm = new CodeMemberMethod ();
cmm.Name = "PrivateImplements";
cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i"));
cmm.ReturnType = new CodeTypeReference (typeof (int));
cmm.Attributes = MemberAttributes.Public;
cmm.Statements.Add (new CodeVariableDeclarationStatement ("TEST6", "t", new CodeObjectCreateExpression ("TEST6")));
cmm.Statements.Add (new CodeVariableDeclarationStatement ("TEST3", "TEST3", new CodeCastExpression ("TEST3",
new CodeVariableReferenceExpression ("t"))));
cmm.Statements.Add (new CodeVariableDeclarationStatement ("TEST4", "TEST4", new CodeCastExpression ("TEST4",
new CodeVariableReferenceExpression ("t"))));
methodinvoking = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("TEST3")
, "InterfaceMethod");
methodinvoking.Parameters.Add (new CodeArgumentReferenceExpression ("i"));
methodinvoking2 = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("TEST4")
, "InterfaceMethod");
methodinvoking2.Parameters.Add (new CodeArgumentReferenceExpression ("i"));
cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (
methodinvoking, CodeBinaryOperatorType.Subtract, methodinvoking2)));
cd.Members.Add (cmm);
//******************* private implements ***************************
// implement both of the interfaces
// GENERATES (C#):
// public class TEST6 : object, TEST3, TEST4 {
// int TEST3.InterfaceMethod(int a) {
// return a;
// }
// int TEST4.InterfaceMethod(int a) {
// return (5 * a);
// }
// }
CodeTypeDeclaration ctd = new CodeTypeDeclaration ("TEST6");
ctd.BaseTypes.Add (new CodeTypeReference ("System.Object"));
ctd.BaseTypes.Add (new CodeTypeReference ("TEST3"));
ctd.BaseTypes.Add (new CodeTypeReference ("TEST4"));
ctd.IsClass = true;
nspace.Types.Add (ctd);
// make a seperate implementation for each base
// first for TEST3 base
cmm = new CodeMemberMethod ();
cmm.Name = "InterfaceMethod";
cmm.ReturnType = new CodeTypeReference (typeof (int));
cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a"));
cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a")));
cmm.PrivateImplementationType = new CodeTypeReference ("TEST3");
ctd.Members.Add (cmm);
// now implement for TEST4 base
cmm = new CodeMemberMethod ();
cmm = new CodeMemberMethod ();
cmm.Name = "InterfaceMethod";
cmm.ReturnType = new CodeTypeReference (typeof (int));
cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a"));
cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
cmm.PrivateImplementationType = new CodeTypeReference ("TEST4");
cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (new
CodePrimitiveExpression (5), CodeBinaryOperatorType.Multiply, new
CodeArgumentReferenceExpression ("a"))));
ctd.Members.Add (cmm);
}
// method to test the 'new' scenario by calling the 'new' method
// GENERATES (C#):
// public int CallingNewScenario(int i) {
// ClassWVirtualMethod t = new ClassWNewMethod();
// return (((ClassWNewMethod)(t)).VirtualMethod(i) - t.VirtualMethod(i));
// }
CodeMethodInvokeExpression methodinvoke;
#if !FSHARP
AddScenario ("CheckCallingNewScenario");
cmm = new CodeMemberMethod ();
cmm.Name = "CallingNewScenario";
cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i"));
cmm.ReturnType = new CodeTypeReference (typeof (int));
cmm.Attributes = MemberAttributes.Public;
cmm.Statements.Add (new CodeVariableDeclarationStatement ("ClassWVirtualMethod", "t", new CodeCastExpression(new CodeTypeReference("ClassWVirtualMethod"), new CodeObjectCreateExpression ("ClassWNewMethod"))));
CodeMethodInvokeExpression methodinvoke = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("t"), "VirtualMethod");
methodinvoke.Parameters.Add (new CodeArgumentReferenceExpression ("i"));
CodeMethodInvokeExpression methodinvoke2 = new CodeMethodInvokeExpression (new CodeCastExpression ("ClassWNewMethod", new
CodeVariableReferenceExpression ("t")), "VirtualMethod");
methodinvoke2.Parameters.Add (new CodeArgumentReferenceExpression ("i"));
cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (
methodinvoke2, CodeBinaryOperatorType.Subtract, methodinvoke)));
cd.Members.Add (cmm);
#endif
// similar to the 'new' test, write a method to complete testing of the 'override' scenario
// GENERATES (C#):
// public static int CallingOverrideScenario(int i) {
// ClassWVirtualMethod t = new ClassWOverrideMethod();
// return t.VirtualMethod(i);
// }
AddScenario ("CheckCallingOverrideScenario");
cmm = new CodeMemberMethod ();
cmm.Name = "CallingOverrideScenario";
cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i"));
cmm.ReturnType = new CodeTypeReference (typeof (int));
cmm.Attributes = MemberAttributes.Public;
cmm.Statements.Add(new CodeVariableDeclarationStatement("ClassWVirtualMethod", "t", new CodeCastExpression(new CodeTypeReference("ClassWVirtualMethod"), new CodeObjectCreateExpression("ClassWOverrideMethod"))));
methodinvoke = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("t"), "VirtualMethod");
methodinvoke.Parameters.Add (new CodeArgumentReferenceExpression ("i"));
cmm.Statements.Add (new CodeMethodReturnStatement (methodinvoke));
cd.Members.Add (cmm);
//*************** overload member function ****************
// new class which will include both functions
// GENERATES (C#):
// public class TEST7 {
// public static int OverloadedMethod(int a) {
// return a;
// }
// public static int OverloadedMethod(int a, int b) {
// return (b + a);
// }
// public static int CallingOverloadedMethods(int i) {
// return (OverloadedMethod(i, i) - OverloadedMethod(i));
// }
// }
cd = new CodeTypeDeclaration ("TEST7");
cd.IsClass = true;
nspace.Types.Add (cd);
cmm = new CodeMemberMethod ();
cmm.Name = "OverloadedMethod";
cmm.ReturnType = new CodeTypeReference (typeof (int));
cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a"));
cmm.Attributes = MemberAttributes.Public;
cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a")));
cd.Members.Add (cmm);
cmm = new CodeMemberMethod ();
cmm.Name = "OverloadedMethod";
cmm.ReturnType = new CodeTypeReference (typeof (int));
cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a"));
cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "b"));
cmm.Attributes = MemberAttributes.Public;
cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (
new CodeArgumentReferenceExpression ("b"), CodeBinaryOperatorType.Add,
new CodeArgumentReferenceExpression ("a"))));
cd.Members.Add (cmm);
// declare a method that will call both OverloadedMethod functions
AddScenario ("CheckCallingOverloadedMethods");
cmm = new CodeMemberMethod ();
cmm.Name = "CallingOverloadedMethods";
cmm.ReturnType = new CodeTypeReference (typeof (int));
cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i"));
cmm.Attributes = MemberAttributes.Public;
CodeMethodReferenceExpression methodref = new CodeMethodReferenceExpression ();
methodref.MethodName = "OverloadedMethod";
cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (
new CodeMethodInvokeExpression (methodref, new
CodeArgumentReferenceExpression ("i"), new CodeArgumentReferenceExpression ("i"))
, CodeBinaryOperatorType.Subtract, new CodeMethodInvokeExpression (methodref, new
CodeArgumentReferenceExpression ("i")))));
cd.Members.Add (cmm);
// ***************** declare method using new ******************
// first declare a class with a virtual method in it
// GENERATES (C#):
// public class ClassWVirtualMethod {
// public virtual int VirtualMethod(int a) {
// return a;
// }
// }
cd = new CodeTypeDeclaration ("ClassWVirtualMethod");
cd.IsClass = true;
nspace.Types.Add (cd);
cmm = new CodeMemberMethod ();
cmm.Name = "VirtualMethod";
cmm.ReturnType = new CodeTypeReference (typeof (int));
cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a"));
cmm.Attributes = MemberAttributes.Public;
cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a")));
cd.Members.Add (cmm);
#if !FSHARP
// now declare a class that inherits from the previous class and has a 'new' method with the
// name VirtualMethod
// GENERATES (C#):
// public class ClassWNewMethod : ClassWVirtualMethod {
// public new virtual int VirtualMethod(int a) {
// return (2 * a);
// }
// }
cd = new CodeTypeDeclaration ("ClassWNewMethod");
cd.BaseTypes.Add (new CodeTypeReference ("ClassWVirtualMethod"));
cd.IsClass = true;
nspace.Types.Add (cd);
cmm = new CodeMemberMethod ();
cmm.Name = "VirtualMethod";
cmm.ReturnType = new CodeTypeReference (typeof (int));
cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a"));
cmm.Attributes = MemberAttributes.Public | MemberAttributes.New;
cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (
new CodePrimitiveExpression (2), CodeBinaryOperatorType.Multiply
, new CodeArgumentReferenceExpression ("a"))));
cd.Members.Add (cmm);
#endif
// *************** declare a method using override ******************
// now declare a class that inherits from the previous class and has a 'new' method with the
// name VirtualMethod
// GENERATES (C#):
// public class ClassWOverrideMethod : ClassWVirtualMethod {
// public override int VirtualMethod(int a) {
// return (2 * a);
// }
// }
cd = new CodeTypeDeclaration ("ClassWOverrideMethod");
cd.BaseTypes.Add (new CodeTypeReference ("ClassWVirtualMethod"));
cd.IsClass = true;
nspace.Types.Add (cd);
cmm = new CodeMemberMethod ();
cmm.Name = "VirtualMethod";
cmm.ReturnType = new CodeTypeReference (typeof (int));
cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a"));
cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override;
cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (
new CodePrimitiveExpression (2), CodeBinaryOperatorType.Multiply
, new CodeArgumentReferenceExpression ("a"))));
cd.Members.Add (cmm);
}
public override void VerifyAssembly (CodeDomProvider provider, Assembly asm) {
object genObject;
Type genType;
AddScenario ("InstantiateTEST2", "Find and instantiate TEST2.");
if (!FindAndInstantiate ("NSPC.TEST2", asm, out genObject, out genType))
return;
VerifyScenario ("InstantiateTEST2");
if (Supports (provider, GeneratorSupport.ReferenceParameters) &&
VerifyMethod (genType, genObject, "CallingWork", new object [] {1516}, 19)) {
VerifyScenario ("CheckCallingWork");
}
if (VerifyMethod (genType, genObject, "CallPrivateMethod", new object [] {1516}, 1521)) {
VerifyScenario ("CheckCallPrivateMethod");
}
if (VerifyMethod (genType, genObject, "CallProtectedAndPublic", new object [] {1516}, 4548)) {
VerifyScenario ("CheckCallProtectedAndPublic");
}
AddScenario ("InstantiateTEST", "Find and instantiate TEST.");
if (!FindAndInstantiate ("NSPC.TEST", asm, out genObject, out genType))
return;
VerifyScenario ("InstantiateTEST");
if (VerifyMethod (genType, genObject, "CallProtected", new object[] {2}, 4)) {
VerifyScenario ("CheckCallProtected");
}
AddScenario ("InstantiateTEST5", "Find and instantiate TEST5.");
if (!FindAndInstantiate ("NSPC.TEST5", asm, out genObject, out genType))
return;
VerifyScenario ("InstantiateTEST5");
if (VerifyMethod (genType, genObject, "CallingNewScenario", new object[] {2}, 2)) {
VerifyScenario ("CheckCallingNewScenario");
}
if (VerifyMethod (genType, genObject, "CallingOverrideScenario", new object[] {2}, 4)) {
VerifyScenario ("CheckCallingOverrideScenario");
}
if (Supports (provider, GeneratorSupport.DeclareInterfaces)) {
if (VerifyMethod (genType, genObject, "TestMultipleInterfaces", new object[] {2}, 0)) {
VerifyScenario ("CheckTestMultipleInterfaces");
}
if (VerifyMethod (genType, genObject, "PrivateImplements", new object[] {2}, -8)) {
VerifyScenario ("CheckPrivateImplements");
}
}
AddScenario ("InstantiateTEST7", "Find and instantiate TEST7.");
if (!FindAndInstantiate ("NSPC.TEST7", asm, out genObject, out genType))
return;
VerifyScenario ("InstantiateTEST7");
if (VerifyMethod (genType, genObject, "CallingOverloadedMethods", new object[] {2}, 2)) {
VerifyScenario ("CheckCallingOverloadedMethods");
}
}
}
| |
//
// This code was created by Jeff Molofee '99
//
// If you've found this code useful, please let me know.
//
// Visit me at www.demonews.com/hosted/nehe
//
//=====================================================================
// Converted to C# and MonoMac by Kenneth J. Pouncey
// http://www.cocoa-mono.org
//
// Copyright (c) 2011 Kenneth J. Pouncey
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using MonoMac.Foundation;
using MonoMac.AppKit;
using MonoMac.CoreVideo;
using MonoMac.CoreGraphics;
using MonoMac.OpenGL;
namespace NeHeLesson3
{
public partial class MyOpenGLView : MonoMac.AppKit.NSView
{
NSOpenGLContext openGLContext;
NSOpenGLPixelFormat pixelFormat;
MainWindowController controller;
CVDisplayLink displayLink;
NSObject notificationProxy;
[Export("initWithFrame:")]
public MyOpenGLView (RectangleF frame) : this(frame, null)
{
}
public MyOpenGLView (RectangleF frame, NSOpenGLContext context) : base(frame)
{
var attribs = new object [] {
NSOpenGLPixelFormatAttribute.Accelerated,
NSOpenGLPixelFormatAttribute.NoRecovery,
NSOpenGLPixelFormatAttribute.DoubleBuffer,
NSOpenGLPixelFormatAttribute.ColorSize, 24,
NSOpenGLPixelFormatAttribute.DepthSize, 16 };
pixelFormat = new NSOpenGLPixelFormat (attribs);
if (pixelFormat == null)
Console.WriteLine ("No OpenGL pixel format");
// NSOpenGLView does not handle context sharing, so we draw to a custom NSView instead
openGLContext = new NSOpenGLContext (pixelFormat, context);
openGLContext.MakeCurrentContext ();
// Synchronize buffer swaps with vertical refresh rate
openGLContext.SwapInterval = true;
// Initialize our newly created view.
InitGL ();
SetupDisplayLink();
// Look for changes in view size
// Note, -reshape will not be called automatically on size changes because NSView does not export it to override
notificationProxy = NSNotificationCenter.DefaultCenter.AddObserver (NSView.GlobalFrameChangedNotification, HandleReshape);
}
public override void DrawRect (RectangleF dirtyRect)
{
// Ignore if the display link is still running
if (!displayLink.IsRunning && controller != null)
DrawView ();
}
public override bool AcceptsFirstResponder ()
{
// We want this view to be able to receive key events
return true;
}
public override void LockFocus ()
{
base.LockFocus ();
if (openGLContext.View != this)
openGLContext.View = this;
}
public override void KeyDown (NSEvent theEvent)
{
controller.KeyDown (theEvent);
}
public override void MouseDown (NSEvent theEvent)
{
controller.MouseDown (theEvent);
}
// All Setup For OpenGL Goes Here
public bool InitGL ()
{
// Enables Smooth Shading
GL.ShadeModel (ShadingModel.Smooth);
// Set background color to black
GL.ClearColor (Color.Black);
// Setup Depth Testing
// Depth Buffer setup
GL.ClearDepth (1.0);
// Enables Depth testing
GL.Enable (EnableCap.DepthTest);
// The type of depth testing to do
GL.DepthFunc (DepthFunction.Lequal);
// Really Nice Perspective Calculations
GL.Hint (HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);
return true;
}
private void DrawView ()
{
var previous = NSApplication.CheckForIllegalCrossThreadCalls;
NSApplication.CheckForIllegalCrossThreadCalls = false;
// This method will be called on both the main thread (through -drawRect:) and a secondary thread (through the display link rendering loop)
// Also, when resizing the view, -reshape is called on the main thread, but we may be drawing on a secondary thread
// Add a mutex around to avoid the threads accessing the context simultaneously
openGLContext.CGLContext.Lock ();
// Make sure we draw to the right context
openGLContext.MakeCurrentContext ();
// Delegate to the scene object for rendering
controller.Scene.DrawGLScene ();
openGLContext.FlushBuffer ();
openGLContext.CGLContext.Unlock ();
NSApplication.CheckForIllegalCrossThreadCalls = previous;
}
private void SetupDisplayLink ()
{
// Create a display link capable of being used with all active displays
displayLink = new CVDisplayLink ();
// Set the renderer output callback function
displayLink.SetOutputCallback (MyDisplayLinkOutputCallback);
// Set the display link for the current renderer
CGLContext cglContext = openGLContext.CGLContext;
CGLPixelFormat cglPixelFormat = PixelFormat.CGLPixelFormat;
displayLink.SetCurrentDisplay (cglContext, cglPixelFormat);
}
public CVReturn MyDisplayLinkOutputCallback (CVDisplayLink displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut)
{
CVReturn result = GetFrameForTime (inOutputTime);
return result;
}
private CVReturn GetFrameForTime (CVTimeStamp outputTime)
{
// There is no autorelease pool when this method is called because it will be called from a background thread
// It's important to create one or you will leak objects
using (NSAutoreleasePool pool = new NSAutoreleasePool ()) {
// Update the animation
DrawView ();
}
return CVReturn.Success;
}
public NSOpenGLContext OpenGLContext {
get { return openGLContext; }
}
public NSOpenGLPixelFormat PixelFormat {
get { return pixelFormat; }
}
public MainWindowController MainController {
set { controller = value; }
}
public void UpdateView ()
{
// This method will be called on the main thread when resizing, but we may be drawing on a secondary thread through the display link
// Add a mutex around to avoid the threads accessing the context simultaneously
openGLContext.CGLContext.Lock ();
// Delegate to the scene object to update for a change in the view size
controller.Scene.ResizeGLScene (Bounds);
openGLContext.Update ();
openGLContext.CGLContext.Unlock ();
}
private void HandleReshape (NSNotification note)
{
UpdateView ();
}
public void StartAnimation ()
{
if (displayLink != null && !displayLink.IsRunning)
displayLink.Start ();
}
public void StopAnimation ()
{
if (displayLink != null && displayLink.IsRunning)
displayLink.Stop ();
}
// Clean up the notifications
public void DeAllocate()
{
displayLink.Stop();
displayLink.SetOutputCallback(null);
NSNotificationCenter.DefaultCenter.RemoveObserver(notificationProxy);
}
[Export("toggleFullScreen:")]
public void toggleFullScreen (NSObject sender)
{
controller.toggleFullScreen (sender);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows.Media;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
namespace NuGetConsole.Implementation.Console
{
class WpfConsoleClassifier : ObjectWithFactory<WpfConsoleService>, IClassifier
{
ITextBuffer TextBuffer { get; set; }
private readonly ComplexCommandSpans _commandLineSpans = new ComplexCommandSpans();
private readonly OrderedTupleSpans<IClassificationType> _colorSpans = new OrderedTupleSpans<IClassificationType>();
public WpfConsoleClassifier(WpfConsoleService factory, ITextBuffer textBuffer)
: base(factory)
{
this.TextBuffer = textBuffer;
TextBuffer.Changed += TextBuffer_Changed;
}
void TextBuffer_Changed(object sender, TextContentChangedEventArgs e)
{
// When input line changes, raise ClassificationChanged event
if (HasConsole && Console.InputLineStart != null)
{
SnapshotSpan commandExtent = Console.InputLineExtent;
if (e.Changes.Any((c) => c.OldPosition >= commandExtent.Span.Start))
{
if (_commandLineSpans.Count > 0)
{
int i = _commandLineSpans.FindCommandStart(_commandLineSpans.Count - 1);
commandExtent = new SnapshotSpan(
new SnapshotPoint(commandExtent.Snapshot, _commandLineSpans[i].Item1.Start),
commandExtent.End);
}
this.ClassificationChanged.Raise(this, new ClassificationChangedEventArgs(commandExtent));
}
}
}
/// <summary>
/// The CommandTokenizer for this console if available.
/// </summary>
ICommandTokenizer CommandTokenizer { get; set; }
WpfConsole _console;
WpfConsole Console
{
get
{
if (_console == null)
{
TextBuffer.Properties.TryGetProperty<WpfConsole>(typeof(IConsole), out _console);
if (_console != null)
{
// Only processing command lines when we have a CommandTokenizer
CommandTokenizer = Factory.GetCommandTokenizer(_console);
if (CommandTokenizer != null)
{
_console.Dispatcher.ExecuteInputLine += Console_ExecuteInputLine;
}
_console.NewColorSpan += Console_NewColorSpan;
_console.ConsoleCleared += Console_ConsoleCleared;
}
}
return _console;
}
}
void Console_ExecuteInputLine(object sender, EventArgs<Tuple<SnapshotSpan, bool>> e)
{
// Don't add empty spans (e.g. executed "cls")
SnapshotSpan snapshotSpan = e.Arg.Item1.TranslateTo(Console.WpfTextView.TextSnapshot, SpanTrackingMode.EdgePositive);
if (!snapshotSpan.IsEmpty)
{
_commandLineSpans.Add(snapshotSpan, e.Arg.Item2);
}
}
void Console_NewColorSpan(object sender, EventArgs<Tuple<SnapshotSpan, Color?, Color?>> e)
{
// At least one of foreground or background must be specified, otherwise we don't care.
if (e.Arg.Item2 != null || e.Arg.Item3 != null)
{
_colorSpans.Add(Tuple.Create(
e.Arg.Item1.Span,
TextFormatClassifier.GetClassificationType(e.Arg.Item2, e.Arg.Item3)));
ClassificationChanged.Raise(this, new ClassificationChangedEventArgs(e.Arg.Item1));
}
}
void Console_ConsoleCleared(object sender, EventArgs e)
{
ClearCachedCommandLineClassifications();
_commandLineSpans.Clear();
_colorSpans.Clear();
}
ITextFormatClassifier _textFormatClassifier;
ITextFormatClassifier TextFormatClassifier
{
get
{
if (_textFormatClassifier == null)
{
_textFormatClassifier = Factory.TextFormatClassifierProvider.GetTextFormatClassifier(
Console.WpfTextView);
}
return _textFormatClassifier;
}
}
bool HasConsole
{
get { return Console != null; }
}
#region IClassifier
public event EventHandler<ClassificationChangedEventArgs> ClassificationChanged;
public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span)
{
List<ClassificationSpan> classificationSpans = new List<ClassificationSpan>();
if (HasConsole)
{
ITextSnapshot snapshot = span.Snapshot;
// Check command line spans
if (CommandTokenizer != null)
{
bool hasInputLine = Console.InputLineStart != null;
if (hasInputLine)
{
// Add current input line temporarily
_commandLineSpans.Add(Console.InputLineExtent, false);
}
try
{
foreach (var cmdSpans in _commandLineSpans.Overlap(span))
{
if (cmdSpans.Count > 0)
{
classificationSpans.AddRange(GetCommandLineClassifications(snapshot, cmdSpans));
}
}
}
finally
{
if (hasInputLine)
{
// Remove added current input line
_commandLineSpans.PopLast();
}
}
}
// Check color spans
foreach (var t in _colorSpans.Overlap(span))
{
classificationSpans.Add(new ClassificationSpan(
new SnapshotSpan(snapshot, t.Item1), t.Item2));
}
}
return classificationSpans;
}
/// <summary>
/// Get classifications for one complex command.
/// </summary>
/// <param name="snapshot">The snapshot for the command spans.</param>
/// <param name="cmdSpans">The command spans.</param>
/// <returns>List of classifications for the given command spans.</returns>
/// <remarks>
/// The editor queries for classifications line by line. For a n-line complex command, this will be
/// called n times for the same command. This implementation caches one parsed results for the last
/// command.
/// </remarks>
IList<ClassificationSpan> GetCommandLineClassifications(ITextSnapshot snapshot, IList<Span> cmdSpans)
{
IList<ClassificationSpan> cachedCommandLineClassifications;
if (TryGetCachedCommandLineClassifications(snapshot, cmdSpans, out cachedCommandLineClassifications))
{
return cachedCommandLineClassifications;
}
else
{
List<ClassificationSpan> spans = new List<ClassificationSpan>();
spans.AddRange(GetTokenizerClassifications(snapshot, cmdSpans));
SaveCachedCommandLineClassifications(snapshot, cmdSpans, spans);
return spans;
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public IList<ClassificationSpan> GetTokenizerClassifications(ITextSnapshot snapshot, IList<Span> spans)
{
List<ClassificationSpan> classificationSpans = new List<ClassificationSpan>();
string[] lines = spans.Select(snapshot.GetText).ToArray();
try
{
IEnumerable<Token> tokens = CommandTokenizer.Tokenize(lines);
foreach (Token token in tokens)
{
IClassificationType classificationType = Factory.GetTokenTypeClassification();
for (int i = token.StartLine; i <= token.EndLine; i++)
{
// Tokenize() may append \r\n, resulting in more lines than spans lines
if (i - 1 < spans.Count)
{
Span span = spans[i - 1];
int start = (i == token.StartLine) ? span.Start + (token.StartColumn - 1) : span.Start;
int end = (i == token.EndLine) ? span.Start + (token.EndColumn - 1) : span.End;
classificationSpans.Add(new ClassificationSpan(
new SnapshotSpan(snapshot, start, end - start), classificationType));
}
}
}
}
catch (Exception x)
{
// Don't care about parser run-time exceptions
Debug.Print(x.ToString());
}
return classificationSpans;
}
#region CommandLineClassifications cache
ITextSnapshot _cacheSnapshot;
int _cacheCommandStartPosition;
WeakReference _cacheClassifications;
/// <summary>
/// Clear cached command line classifications.
/// </summary>
void ClearCachedCommandLineClassifications()
{
_cacheSnapshot = null;
_cacheClassifications = null;
}
/// <summary>
/// Save command line classifications to cache.
/// </summary>
/// <param name="snapshot">The snapshot for the command.</param>
/// <param name="cmdSpans">The command spans.</param>
/// <param name="spans">Classification results of the command.</param>
void SaveCachedCommandLineClassifications(ITextSnapshot snapshot, IList<Span> cmdSpans, IList<ClassificationSpan> spans)
{
_cacheSnapshot = snapshot;
_cacheCommandStartPosition = cmdSpans[0].Start;
_cacheClassifications = new WeakReference(spans);
}
/// <summary>
/// Try get classifications from cache if a command classifications are cached.
/// </summary>
/// <param name="snapshot">The snapshot for the command.</param>
/// <param name="cmdSpans">The command spans.</param>
/// <param name="cachedCommandLineClassifications">The cached classifications if found.</param>
/// <returns>If cached results are found.</returns>
bool TryGetCachedCommandLineClassifications(ITextSnapshot snapshot, IList<Span> cmdSpans, out IList<ClassificationSpan> cachedCommandLineClassifications)
{
// The cached command is identified by text snapshot and command start position.
if (_cacheSnapshot == snapshot && _cacheCommandStartPosition == cmdSpans[0].Start)
{
IList<ClassificationSpan> spans = _cacheClassifications.Target as IList<ClassificationSpan>;
if (spans != null)
{
cachedCommandLineClassifications = spans;
return true;
}
else
{
ClearCachedCommandLineClassifications(); // weak reference is gone
}
}
cachedCommandLineClassifications = null;
return false;
}
#endregion
#endregion
}
}
| |
using System;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Runtime.InteropServices;
namespace WeifenLuo.WinFormsUI.Docking
{
partial class DockPanel
{
// This class comes from Jacob Slusser's MdiClientController class:
// http://www.codeproject.com/cs/miscctrl/mdiclientcontroller.asp
private class MdiClientController : NativeWindow, IComponent, IDisposable
{
private bool m_autoScroll = true;
private BorderStyle m_borderStyle = BorderStyle.Fixed3D;
private MdiClient m_mdiClient = null;
private Form m_parentForm = null;
private ISite m_site = null;
public MdiClientController()
{
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
lock (this)
{
if (Site != null && Site.Container != null)
Site.Container.Remove(this);
if (Disposed != null)
Disposed(this, EventArgs.Empty);
}
}
}
public bool AutoScroll
{
get { return m_autoScroll; }
set
{
// By default the MdiClient control scrolls. It can appear though that
// there are no scrollbars by turning them off when the non-client
// area is calculated. I decided to expose this method following
// the .NET vernacular of an AutoScroll property.
m_autoScroll = value;
if (MdiClient != null)
UpdateStyles();
}
}
public BorderStyle BorderStyle
{
set
{
// Error-check the enum.
if (!Enum.IsDefined(typeof(BorderStyle), value))
throw new InvalidEnumArgumentException();
m_borderStyle = value;
if (MdiClient == null)
return;
// This property can actually be visible in design-mode,
// but to keep it consistent with the others,
// prevent this from being show at design-time.
if (Site != null && Site.DesignMode)
return;
// There is no BorderStyle property exposed by the MdiClient class,
// but this can be controlled by Win32 functions. A Win32 ExStyle
// of WS_EX_CLIENTEDGE is equivalent to a Fixed3D border and a
// Style of WS_BORDER is equivalent to a FixedSingle border.
// This code is inspired Jason Dori's article:
// "Adding designable borders to user controls".
// http://www.codeproject.com/cs/miscctrl/CsAddingBorders.asp
if (!Win32Helper.IsRunningOnMono)
{
// Get styles using Win32 calls
int style = NativeMethods.GetWindowLong(MdiClient.Handle, (int)Win32.GetWindowLongIndex.GWL_STYLE);
int exStyle = NativeMethods.GetWindowLong(MdiClient.Handle, (int)Win32.GetWindowLongIndex.GWL_EXSTYLE);
// Add or remove style flags as necessary.
switch (m_borderStyle)
{
case BorderStyle.Fixed3D:
exStyle |= (int)Win32.WindowExStyles.WS_EX_CLIENTEDGE;
style &= ~((int)Win32.WindowStyles.WS_BORDER);
break;
case BorderStyle.FixedSingle:
exStyle &= ~((int)Win32.WindowExStyles.WS_EX_CLIENTEDGE);
style |= (int)Win32.WindowStyles.WS_BORDER;
break;
case BorderStyle.None:
style &= ~((int)Win32.WindowStyles.WS_BORDER);
exStyle &= ~((int)Win32.WindowExStyles.WS_EX_CLIENTEDGE);
break;
}
// Set the styles using Win32 calls
NativeMethods.SetWindowLong(MdiClient.Handle, (int)Win32.GetWindowLongIndex.GWL_STYLE, style);
NativeMethods.SetWindowLong(MdiClient.Handle, (int)Win32.GetWindowLongIndex.GWL_EXSTYLE, exStyle);
}
// Cause an update of the non-client area.
UpdateStyles();
}
}
public MdiClient MdiClient
{
get { return m_mdiClient; }
}
[Browsable(false)]
public Form ParentForm
{
get { return m_parentForm; }
set
{
// If the ParentForm has previously been set,
// unwire events connected to the old parent.
if (m_parentForm != null)
{
m_parentForm.HandleCreated -= new EventHandler(ParentFormHandleCreated);
m_parentForm.MdiChildActivate -= new EventHandler(ParentFormMdiChildActivate);
}
m_parentForm = value;
if (m_parentForm == null)
return;
// If the parent form has not been created yet,
// wait to initialize the MDI client until it is.
if (m_parentForm.IsHandleCreated)
{
InitializeMdiClient();
RefreshProperties();
}
else
m_parentForm.HandleCreated += new EventHandler(ParentFormHandleCreated);
m_parentForm.MdiChildActivate += new EventHandler(ParentFormMdiChildActivate);
}
}
public ISite Site
{
get { return m_site; }
set
{
m_site = value;
if (m_site == null)
return;
// If the component is dropped onto a form during design-time,
// set the ParentForm property.
IDesignerHost host = (value.GetService(typeof(IDesignerHost)) as IDesignerHost);
if (host != null)
{
Form parent = host.RootComponent as Form;
if (parent != null)
ParentForm = parent;
}
}
}
public void RenewMdiClient()
{
// Reinitialize the MdiClient and its properties.
InitializeMdiClient();
RefreshProperties();
}
public event EventHandler Disposed;
public event EventHandler HandleAssigned;
public event EventHandler MdiChildActivate;
public event LayoutEventHandler Layout;
protected virtual void OnHandleAssigned(EventArgs e)
{
// Raise the HandleAssigned event.
if (HandleAssigned != null)
HandleAssigned(this, e);
}
protected virtual void OnMdiChildActivate(EventArgs e)
{
// Raise the MdiChildActivate event
if (MdiChildActivate != null)
MdiChildActivate(this, e);
}
protected virtual void OnLayout(LayoutEventArgs e)
{
// Raise the Layout event
if (Layout != null)
Layout(this, e);
}
public event PaintEventHandler Paint;
protected virtual void OnPaint(PaintEventArgs e)
{
// Raise the Paint event.
if (Paint != null)
Paint(this, e);
}
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case (int)Win32.Msgs.WM_NCCALCSIZE:
// If AutoScroll is set to false, hide the scrollbars when the control
// calculates its non-client area.
if (!AutoScroll)
if (!Win32Helper.IsRunningOnMono)
NativeMethods.ShowScrollBar(m.HWnd, (int)Win32.ScrollBars.SB_BOTH, 0 /*false*/);
break;
}
base.WndProc(ref m);
}
private void ParentFormHandleCreated(object sender, EventArgs e)
{
// The form has been created, unwire the event, and initialize the MdiClient.
this.m_parentForm.HandleCreated -= new EventHandler(ParentFormHandleCreated);
InitializeMdiClient();
RefreshProperties();
}
private void ParentFormMdiChildActivate(object sender, EventArgs e)
{
OnMdiChildActivate(e);
}
private void MdiClientLayout(object sender, LayoutEventArgs e)
{
OnLayout(e);
}
private void MdiClientHandleDestroyed(object sender, EventArgs e)
{
// If the MdiClient handle has been released, drop the reference and
// release the handle.
if (m_mdiClient != null)
{
m_mdiClient.HandleDestroyed -= new EventHandler(MdiClientHandleDestroyed);
m_mdiClient = null;
}
ReleaseHandle();
}
private void InitializeMdiClient()
{
// If the mdiClient has previously been set, unwire events connected
// to the old MDI.
if (MdiClient != null)
{
MdiClient.HandleDestroyed -= new EventHandler(MdiClientHandleDestroyed);
MdiClient.Layout -= new LayoutEventHandler(MdiClientLayout);
}
if (ParentForm == null)
return;
// Get the MdiClient from the parent form.
foreach (Control control in ParentForm.Controls)
{
// If the form is an MDI container, it will contain an MdiClient control
// just as it would any other control.
m_mdiClient = control as MdiClient;
if (m_mdiClient == null)
continue;
// Assign the MdiClient Handle to the NativeWindow.
ReleaseHandle();
AssignHandle(MdiClient.Handle);
// Raise the HandleAssigned event.
OnHandleAssigned(EventArgs.Empty);
// Monitor the MdiClient for when its handle is destroyed.
MdiClient.HandleDestroyed += new EventHandler(MdiClientHandleDestroyed);
MdiClient.Layout += new LayoutEventHandler(MdiClientLayout);
break;
}
}
private void RefreshProperties()
{
// Refresh all the properties
BorderStyle = m_borderStyle;
AutoScroll = m_autoScroll;
}
private void UpdateStyles()
{
// To show style changes, the non-client area must be repainted. Using the
// control's Invalidate method does not affect the non-client area.
// Instead use a Win32 call to signal the style has changed.
if (!Win32Helper.IsRunningOnMono)
NativeMethods.SetWindowPos(MdiClient.Handle, IntPtr.Zero, 0, 0, 0, 0,
Win32.FlagsSetWindowPos.SWP_NOACTIVATE |
Win32.FlagsSetWindowPos.SWP_NOMOVE |
Win32.FlagsSetWindowPos.SWP_NOSIZE |
Win32.FlagsSetWindowPos.SWP_NOZORDER |
Win32.FlagsSetWindowPos.SWP_NOOWNERZORDER |
Win32.FlagsSetWindowPos.SWP_FRAMECHANGED);
}
}
private MdiClientController m_mdiClientController = null;
private MdiClientController GetMdiClientController()
{
if (m_mdiClientController == null)
{
m_mdiClientController = new MdiClientController();
m_mdiClientController.HandleAssigned += new EventHandler(MdiClientHandleAssigned);
m_mdiClientController.MdiChildActivate += new EventHandler(ParentFormMdiChildActivate);
m_mdiClientController.Layout += new LayoutEventHandler(MdiClient_Layout);
}
return m_mdiClientController;
}
private void ParentFormMdiChildActivate(object sender, EventArgs e)
{
if (GetMdiClientController().ParentForm == null)
return;
IDockContent content = GetMdiClientController().ParentForm.ActiveMdiChild as IDockContent;
if (content == null)
return;
if (content.DockHandler.DockPanel == this && content.DockHandler.Pane != null)
content.DockHandler.Pane.ActiveContent = content;
}
private bool MdiClientExists
{
get { return GetMdiClientController().MdiClient != null; }
}
private void SetMdiClientBounds(Rectangle bounds)
{
GetMdiClientController().MdiClient.Bounds = bounds;
}
private void SuspendMdiClientLayout()
{
if (GetMdiClientController().MdiClient != null)
GetMdiClientController().MdiClient.SuspendLayout();
}
private void ResumeMdiClientLayout(bool perform)
{
if (GetMdiClientController().MdiClient != null)
GetMdiClientController().MdiClient.ResumeLayout(perform);
}
private void PerformMdiClientLayout()
{
if (GetMdiClientController().MdiClient != null)
GetMdiClientController().MdiClient.PerformLayout();
}
// Called when:
// 1. DockPanel.DocumentStyle changed
// 2. DockPanel.Visible changed
// 3. MdiClientController.Handle assigned
private void SetMdiClient()
{
MdiClientController controller = GetMdiClientController();
if (this.DocumentStyle == DocumentStyle.DockingMdi)
{
controller.AutoScroll = false;
controller.BorderStyle = BorderStyle.None;
if (MdiClientExists)
controller.MdiClient.Dock = DockStyle.Fill;
}
else if (DocumentStyle == DocumentStyle.DockingSdi || DocumentStyle == DocumentStyle.DockingWindow)
{
controller.AutoScroll = true;
controller.BorderStyle = BorderStyle.Fixed3D;
if (MdiClientExists)
controller.MdiClient.Dock = DockStyle.Fill;
}
else if (this.DocumentStyle == DocumentStyle.SystemMdi)
{
controller.AutoScroll = true;
controller.BorderStyle = BorderStyle.Fixed3D;
if (controller.MdiClient != null)
{
controller.MdiClient.Dock = DockStyle.None;
controller.MdiClient.Bounds = SystemMdiClientBounds;
}
}
}
internal Rectangle RectangleToMdiClient(Rectangle rect)
{
if (MdiClientExists)
return GetMdiClientController().MdiClient.RectangleToClient(rect);
else
return Rectangle.Empty;
}
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.IO;
using System.Windows.Forms;
using Vlc.DotNet.Core;
using Vlc.DotNet.Core.Interops.Signatures;
using Vlc.DotNet.Forms.TypeEditors;
namespace Vlc.DotNet.Forms
{
public partial class VlcControl : Control, ISupportInitialize
{
private VlcMediaPlayer myVlcMediaPlayer;
#region VlcControl Init
public VlcControl()
{
InitializeComponent();
}
private void InitializeComponent()
{
// Init Component behaviour
BackColor = System.Drawing.Color.Black;
}
[Category("Media Player")]
public string[] VlcMediaplayerOptions { get; set; }
[Category("Media Player")]
[Editor(typeof(DirectoryEditor), typeof(UITypeEditor))]
public DirectoryInfo VlcLibDirectory { get; set; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false)]
public bool IsPlaying
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.IsPlaying();
}
else
{
return false;
}
}
}
public void BeginInit()
{
// not used yet
}
public void EndInit()
{
if (IsInDesignMode() || myVlcMediaPlayer != null)
return;
if (VlcLibDirectory == null && (VlcLibDirectory = OnVlcLibDirectoryNeeded()) == null)
{
throw new Exception("'VlcLibDirectory' must be set.");
}
if (VlcMediaplayerOptions == null)
{
myVlcMediaPlayer = new VlcMediaPlayer(VlcLibDirectory);
}
else
{
myVlcMediaPlayer = new VlcMediaPlayer(VlcLibDirectory, VlcMediaplayerOptions);
}
myVlcMediaPlayer.VideoHostControlHandle = Handle;
RegisterEvents();
}
// work around http://stackoverflow.com/questions/34664/designmode-with-controls/708594
private static bool IsInDesignMode()
{
return System.Reflection.Assembly.GetExecutingAssembly().Location.Contains("VisualStudio");
}
public event EventHandler<VlcLibDirectoryNeededEventArgs> VlcLibDirectoryNeeded;
bool disposed = false;
protected void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected override void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
if (myVlcMediaPlayer != null)
{
UnregisterEvents();
if (IsPlaying)
Stop();
myVlcMediaPlayer.Dispose();
}
myVlcMediaPlayer = null;
base.Dispose(disposing);
}
disposed = true;
}
}
public DirectoryInfo OnVlcLibDirectoryNeeded()
{
var del = VlcLibDirectoryNeeded;
if (del != null)
{
var args = new VlcLibDirectoryNeededEventArgs();
del(this, args);
return args.VlcLibDirectory;
}
return null;
}
#endregion
#region VlcControl Functions & Properties
public void Play()
{
//EndInit();
if (myVlcMediaPlayer != null)
{
myVlcMediaPlayer.Play();
}
}
public void Play(FileInfo file, params string[] options)
{
//EndInit();
if (myVlcMediaPlayer != null)
{
myVlcMediaPlayer.SetMedia(file, options);
Play();
}
}
public void Play(Uri uri, params string[] options)
{
//EndInit();
if (myVlcMediaPlayer != null)
{
myVlcMediaPlayer.SetMedia(uri, options);
Play();
}
}
public void Pause()
{
//EndInit();
if (myVlcMediaPlayer != null)
{
myVlcMediaPlayer.Pause();
}
}
public void Stop()
{
//EndInit();
if (myVlcMediaPlayer != null)
{
myVlcMediaPlayer.Stop();
}
}
public VlcMedia GetCurrentMedia()
{
//EndInit();
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.GetMedia();
}
else
{
return null;
}
}
public void TakeSnapshot(string fileName)
{
FileInfo fileInfo = new FileInfo(fileName);
myVlcMediaPlayer.TakeSnapshot(fileInfo);
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false)]
public float Position
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.Position;
}
else
{
return -1;
}
}
set
{
if (myVlcMediaPlayer != null)
{
myVlcMediaPlayer.Position = value;
}
}
}
[Browsable(false)]
public IChapterManagement Chapter
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.Chapters;
}
else
{
return null;
}
}
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false)]
public float Rate
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.Rate;
}
else
{
return -1;
}
}
set
{
if (myVlcMediaPlayer != null)
{
myVlcMediaPlayer.Rate = value;
}
}
}
[Browsable(false)]
public MediaStates State
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.State;
}
else
{
return MediaStates.NothingSpecial;
}
}
}
[Browsable(false)]
public ISubTitlesManagement SubTitles
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.SubTitles;
}
else
{
return null;
}
}
}
[Browsable(false)]
public IVideoManagement Video
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.Video;
}
else
{
return null;
}
}
}
[Browsable(false)]
public IAudioManagement Audio
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.Audio;
}
else
{
return null;
}
}
}
[Browsable(false)]
public long Length
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.Length;
}
else
{
return -1;
}
}
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false)]
public long Time
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.Time;
}
else
{
return -1;
}
}
set
{
if (myVlcMediaPlayer != null)
{
myVlcMediaPlayer.Time = value;
}
}
}
[Browsable(false)]
public int Spu
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.Spu;
}
return -1;
}
set
{
if (myVlcMediaPlayer != null)
{
myVlcMediaPlayer.Spu = value;
}
}
}
public void SetMedia(FileInfo file, params string[] options)
{
//EndInit();
myVlcMediaPlayer.SetMedia(file, options);
}
public void SetMedia(Uri file, params string[] options)
{
//EndInit();
myVlcMediaPlayer.SetMedia(file, options);
}
#endregion
}
}
| |
/*
* Copyright (c) 2006-2012 IowaComputerGurus Inc (http://www.iowacomputergurus.com)
* Copyright Contact: webmaster@iowacomputergurus.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.Web.UI.WebControls;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Framework;
using DotNetNuke.Security.Roles;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.UserControls;
using ICG.Modules.ExpandableTextHtml.Components;
namespace ICG.Modules.ExpandableTextHtml
{
public partial class EditExpandableTextHtml : PortalModuleBase
{
#region Protected Members
/// <summary>
/// Title input control
/// </summary>
protected TextEditor txtTitle;
/// <summary>
/// Body input control
/// </summary>
protected TextEditor txtBody;
#endregion
private int itemId = Null.NullInteger; //Stores the item id for the curren titem
protected void Page_Load(object sender, EventArgs e)
{
try
{
jQuery.RequestDnnPluginsRegistration();
//Store the item id on every load
if (Request.QueryString["EntryId"] != null)
{
itemId = Int32.Parse(Request.QueryString["EntryId"]);
}
if (!IsPostBack)
{
//Load the list of roles
var roleController = new RoleController();
ddlRequiredRole.DataSource = roleController.GetPortalRoles(PortalId);
ddlRequiredRole.DataTextField = "RoleName";
ddlRequiredRole.DataValueField = "RoleName";
ddlRequiredRole.DataBind();
ddlRequiredRole.Items.Insert(0,
new ListItem(
Localization.GetString("SameAsModule", LocalResourceFile),
"-1"));
//check we have an item to lookup
if (!Null.IsNull(itemId))
{
//load the item
var controller = new ExpandableTextHtmlController();
var item = controller.GetExpandableTextHtml(ModuleId, itemId);
//ensure we have an item
if (item != null)
{
txtTitle.Text = item.Title;
txtBody.Text = item.Body;
chkIsExpanded.Checked = item.IsExpanded;
txtSortOrder.Text = item.SortOrder.ToString();
litContentId.Text = string.Format("ICG_ETH_{0}", item.ItemId.ToString());
txtPublishDate.Text = item.PublishDate.ToShortDateString();
var foundItem = ddlRequiredRole.Items.FindByValue(item.RequiredRole);
if (foundItem != null)
ddlRequiredRole.SelectedValue = item.RequiredRole;
}
else
Response.Redirect(Globals.NavigateURL(), true);
}
else
{
cmdDelete.Visible = false;
//Default sort order to 0
txtSortOrder.Text = "0";
}
}
}
catch (Exception ex)
{
Exceptions.ProcessModuleLoadException(this, ex);
}
}
#region Localization Helper
/// <summary>
/// This method will return localized text
/// </summary>
/// <param name="keyName"></param>
/// <returns></returns>
public string GetLocalizeString(string keyName)
{
return Localization.GetString(keyName, LocalResourceFile);
}
#endregion
/// <summary>
/// This method handles an insert or update!
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void cmdUpdate_Click(object sender, EventArgs e)
{
try
{
var controller = new ExpandableTextHtmlController();
var item = new ExpandableTextHtmlInfo();
txtTitle.HtmlEncode = false;
item.Title = txtTitle.Text;
txtBody.HtmlEncode = false;
item.Body = txtBody.Text;
item.LastUpdated = DateTime.Now;
item.ModuleId = ModuleId;
item.ItemId = itemId;
item.IsExpanded = chkIsExpanded.Checked;
item.SortOrder = int.Parse(txtSortOrder.Text);
item.RequiredRole = ddlRequiredRole.SelectedValue;
//Do we need to default the publish date
item.PublishDate = string.IsNullOrEmpty(txtPublishDate.Text) ? DateTime.Now.Date : DateTime.Parse(txtPublishDate.Text);
//Determine if we need to clean the title text
if (item.Title.StartsWith("<p>") && item.Title.EndsWith("</p>"))
{
item.Title = item.Title.Substring(3, item.Title.Length - 7);
}
//determine if we are adding or updating
if (Null.IsNull(item.ItemId))
controller.AddExpandableTextHtml(item);
else
controller.UpdateExpandableTextHtml(item);
//Purge the cache
ModuleController.SynchronizeModule(ModuleId);
//Call cancel to return
cmdCancel_Click(sender, e);
}
catch (Exception ex)
{
Exceptions.ProcessModuleLoadException(this, ex);
}
}
/// <summary>
/// Handles a cancel, exits to the page
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void cmdCancel_Click(object sender, EventArgs e)
{
try
{
Response.Redirect(Globals.NavigateURL(), true);
}
catch (Exception ex)
{
Exceptions.ProcessModuleLoadException(this, ex);
}
}
/// <summary>
/// Handles a delete
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void cmdDelete_Click(object sender, EventArgs e)
{
try
{
if (!Null.IsNull(itemId))
{
var controller = new ExpandableTextHtmlController();
controller.DeleteExpandableTextHtml(ModuleId, itemId);
//Purge the cache
ModuleController.SynchronizeModule(ModuleId);
//Call cancel to return
cmdCancel_Click(sender, e);
}
}
catch (Exception ex)
{
Exceptions.ProcessModuleLoadException(this, ex);
}
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Reflection;
using Microsoft.SPOT.Platform.Test;
namespace Microsoft.SPOT.Platform.Tests
{
public class StructStructTests : IMFTestInterface
{
[SetUp]
public InitializeResult Initialize()
{
Log.Comment("Adding set up for the tests");
Log.Comment("These tests examine the conversion (casting) of two structs");
Log.Comment("There are two structs S and T");
Log.Comment("The names of the tests describe the tests by listing which two objects will be converted between");
Log.Comment("Followed by which (The source or the destination) will contain a cast definition");
Log.Comment("Followed further by 'i's or 'e's to indicate which of the cast definition and the actual cast are");
Log.Comment("implicit or explicit.");
Log.Comment("");
Log.Comment("For example, S_T_Source_i_e tests the conversion of S to T, with an implicit definition");
Log.Comment("of the cast in the S struct, and an explicit cast in the body of the method.");
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
Log.Comment("Cleaning up after the tests");
}
//StructStruct Test methods
//The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\StructStruct
//Test Case Calls
[TestMethod]
public MFTestResults StructStruct_S_T_Source_i_i_Test()
{
if (StructStructTestClass_S_T_Source_i_i.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults StructStruct_S_T_Source_i_e_Test()
{
if (StructStructTestClass_S_T_Source_i_e.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults StructStruct_S_T_Source_e_e_Test()
{
if (StructStructTestClass_S_T_Source_e_e.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults StructStruct_S_T_Dest_i_i_Test()
{
if (StructStructTestClass_S_T_Dest_i_i.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults StructStruct_S_T_Dest_i_e_Test()
{
if (StructStructTestClass_S_T_Dest_i_e.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults StructStruct_S_T_Dest_e_e_Test()
{
if (StructStructTestClass_S_T_Dest_e_e.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
//Compiled Test Cases
struct StructStructTestClass_S_T_Source_i_i_S
{
static public implicit operator StructStructTestClass_S_T_Source_i_i_T(StructStructTestClass_S_T_Source_i_i_S foo)
{
Log.Comment(" StructStructTestClass_S_T_Source_i_i_S to StructStructTestClass_S_T_Source_i_i_T Source implicit");
return new StructStructTestClass_S_T_Source_i_i_T();
}
}
struct StructStructTestClass_S_T_Source_i_i_T
{
}
class StructStructTestClass_S_T_Source_i_i
{
public static void Main_old()
{
StructStructTestClass_S_T_Source_i_i_S s = new StructStructTestClass_S_T_Source_i_i_S();
StructStructTestClass_S_T_Source_i_i_T t;
try
{
t = s;
}
catch (System.Exception)
{
Log.Comment("System.Exception Caught");
}
}
public static bool testMethod()
{
Main_old();
return true;
}
}
struct StructStructTestClass_S_T_Source_i_e_S
{
static public implicit operator StructStructTestClass_S_T_Source_i_e_T(StructStructTestClass_S_T_Source_i_e_S foo)
{
Log.Comment(" StructStructTestClass_S_T_Source_i_e_S to StructStructTestClass_S_T_Source_i_e_T Source implicit");
return new StructStructTestClass_S_T_Source_i_e_T();
}
}
struct StructStructTestClass_S_T_Source_i_e_T
{
}
class StructStructTestClass_S_T_Source_i_e
{
public static void Main_old()
{
StructStructTestClass_S_T_Source_i_e_S s = new StructStructTestClass_S_T_Source_i_e_S();
StructStructTestClass_S_T_Source_i_e_T t;
try
{
t = (StructStructTestClass_S_T_Source_i_e_T)s;
}
catch (System.Exception)
{
Log.Comment("System.Exception Caught");
}
}
public static bool testMethod()
{
Main_old();
return true;
}
}
struct StructStructTestClass_S_T_Source_e_e_S
{
static public explicit operator StructStructTestClass_S_T_Source_e_e_T(StructStructTestClass_S_T_Source_e_e_S foo)
{
Log.Comment(" StructStructTestClass_S_T_Source_e_e_S to StructStructTestClass_S_T_Source_e_e_T Source explicit");
return new StructStructTestClass_S_T_Source_e_e_T();
}
}
struct StructStructTestClass_S_T_Source_e_e_T
{
}
class StructStructTestClass_S_T_Source_e_e
{
public static void Main_old()
{
StructStructTestClass_S_T_Source_e_e_S s = new StructStructTestClass_S_T_Source_e_e_S();
StructStructTestClass_S_T_Source_e_e_T t;
try
{
t = (StructStructTestClass_S_T_Source_e_e_T)s;
}
catch (System.Exception)
{
Log.Comment("System.Exception Caught");
}
}
public static bool testMethod()
{
Main_old();
return true;
}
}
struct StructStructTestClass_S_T_Dest_i_i_S
{
}
struct StructStructTestClass_S_T_Dest_i_i_T
{
static public implicit operator StructStructTestClass_S_T_Dest_i_i_T(StructStructTestClass_S_T_Dest_i_i_S foo)
{
Log.Comment(" StructStructTestClass_S_T_Dest_i_i_S to StructStructTestClass_S_T_Dest_i_i_T Dest implicit");
return new StructStructTestClass_S_T_Dest_i_i_T();
}
}
class StructStructTestClass_S_T_Dest_i_i
{
public static void Main_old()
{
StructStructTestClass_S_T_Dest_i_i_S s = new StructStructTestClass_S_T_Dest_i_i_S();
StructStructTestClass_S_T_Dest_i_i_T t;
try
{
t = s;
}
catch (System.Exception)
{
Log.Comment("System.Exception Caught");
}
}
public static bool testMethod()
{
Main_old();
return true;
}
}
struct StructStructTestClass_S_T_Dest_i_e_S
{
}
struct StructStructTestClass_S_T_Dest_i_e_T
{
static public implicit operator StructStructTestClass_S_T_Dest_i_e_T(StructStructTestClass_S_T_Dest_i_e_S foo)
{
Log.Comment(" StructStructTestClass_S_T_Dest_i_e_S to StructStructTestClass_S_T_Dest_i_e_T Dest implicit");
return new StructStructTestClass_S_T_Dest_i_e_T();
}
}
class StructStructTestClass_S_T_Dest_i_e
{
public static void Main_old()
{
StructStructTestClass_S_T_Dest_i_e_S s = new StructStructTestClass_S_T_Dest_i_e_S();
StructStructTestClass_S_T_Dest_i_e_T t;
try
{
t = (StructStructTestClass_S_T_Dest_i_e_T)s;
}
catch (System.Exception)
{
Log.Comment("System.Exception Caught");
}
}
public static bool testMethod()
{
Main_old();
return true;
}
}
struct StructStructTestClass_S_T_Dest_e_e_S
{
}
struct StructStructTestClass_S_T_Dest_e_e_T
{
static public explicit operator StructStructTestClass_S_T_Dest_e_e_T(StructStructTestClass_S_T_Dest_e_e_S foo)
{
Log.Comment(" StructStructTestClass_S_T_Dest_e_e_S to StructStructTestClass_S_T_Dest_e_e_T Dest explicit");
return new StructStructTestClass_S_T_Dest_e_e_T();
}
}
class StructStructTestClass_S_T_Dest_e_e
{
public static void Main_old()
{
StructStructTestClass_S_T_Dest_e_e_S s = new StructStructTestClass_S_T_Dest_e_e_S();
StructStructTestClass_S_T_Dest_e_e_T t;
try
{
t = (StructStructTestClass_S_T_Dest_e_e_T)s;
}
catch (System.Exception)
{
Log.Comment("System.Exception Caught");
}
}
public static bool testMethod()
{
Main_old();
return true;
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
// Respawntime is the amount of time it takes for a static "auto-respawn"
// turret to re-appear after it's been picked up. Any turret marked as "static"
// is automaticlly respawned.
$TurretShape::RespawnTime = 30 * 1000;
// DestroyedFadeDelay is the how long a destroyed turret sticks around before it
// fades out and is deleted.
$TurretShape::DestroyedFadeDelay = 5 * 1000;
// ----------------------------------------------------------------------------
// TurretShapeData
// ----------------------------------------------------------------------------
function TurretShapeData::onAdd(%this, %obj)
{
%obj.setRechargeRate(%this.rechargeRate);
%obj.setEnergyLevel(%this.MaxEnergy);
%obj.setRepairRate(0);
if (%obj.mountable || %obj.mountable $= "")
%this.isMountable(%obj, true);
else
%this.isMountable(%obj, false);
if (%this.nameTag !$= "")
%obj.setShapeName(%this.nameTag);
// Mount weapons
for(%i = 0; %i < %this.numWeaponMountPoints; %i++)
{
// Handle inventory
%obj.incInventory(%this.weapon[%i], 1);
%obj.incInventory(%this.weaponAmmo[%i], %this.weaponAmmoAmount[%i]);
// Mount the image
%obj.mountImage(%this.weapon[%i].image, %i, %this.startLoaded);
%obj.setImageGenericTrigger(%i, 0, false); // Used to indicate the turret is destroyed
}
if (%this.enterSequence !$= "")
{
%obj.entranceThread = 0;
%obj.playThread(%obj.entranceThread, %this.enterSequence);
%obj.pauseThread(%obj.entranceThread);
}
else
{
%obj.entranceThread = -1;
}
}
function TurretShapeData::onRemove(%this, %obj)
{
//echo("\c4TurretShapeData::onRemove("@ %this.getName() @", "@ %obj.getClassName() @")");
// if there are passengers/driver, kick them out
for(%i = 0; %i < %this.numMountPoints; %i++)
{
if (%obj.getMountNodeObject(%i))
{
%passenger = %obj.getMountNodeObject(%i);
%passenger.getDataBlock().doDismount(%passenger, true);
}
}
}
// This is on MissionGroup so it doesn't happen when the mission has ended
function Scene::respawnTurret(%this, %datablock, %className, %transform, %static, %respawn)
{
%turret = new (%className)()
{
datablock = %datablock;
static = %static;
respawn = %respawn;
};
%turret.setTransform(%transform);
getRootScene().add(%turret);
return %turret;
}
// ----------------------------------------------------------------------------
// TurretShapeData damage state
// ----------------------------------------------------------------------------
// This method is called by weapons fire
function TurretShapeData::damage(%this, %turret, %sourceObject, %position, %damage, %damageType)
{
//echo("\TurretShapeData::damage(" @ %turret @ ", "@ %sourceObject @ ", " @ %position @ ", "@ %damage @ ", "@ %damageType @ ")");
if (%turret.getState() $= "Dead")
return;
%turret.applyDamage(%damage);
// Update the numerical Health HUD
%mountedObject = %turret.getObjectMount();
if (%mountedObject)
%mountedObject.updateHealth();
// Kill any occupants
if (%turret.getState() $= "Dead")
{
for (%i = 0; %i < %this.numMountPoints; %i++)
{
%player = %turret.getMountNodeObject(%i);
if (%player != 0)
%player.killWithSource(%sourceObject, "InsideTurret");
}
}
}
function TurretShapeData::onDamage(%this, %obj, %delta)
{
// This method is invoked by the ShapeBase code whenever the
// object's damage level changes.
}
function TurretShapeData::onDestroyed(%this, %obj, %lastState)
{
// This method is invoked by the ShapeBase code whenever the
// object's damage state changes.
// Fade out the destroyed object. Then schedule a return.
%obj.startFade(1000, $TurretShape::DestroyedFadeDelay, true);
%obj.schedule($TurretShape::DestroyedFadeDelay + 1000, "delete");
if (%obj.doRespawn())
{
getRootScene().schedule($TurretShape::RespawnTime, "respawnTurret", %this, %obj.getClassName(), %obj.getTransform(), true, true);
}
}
function TurretShapeData::onDisabled(%this, %obj, %lastState)
{
// This method is invoked by the ShapeBase code whenever the
// object's damage state changes.
}
function TurretShapeData::onEnabled(%this, %obj, %lastState)
{
// This method is invoked by the ShapeBase code whenever the
// object's damage state changes.
}
// ----------------------------------------------------------------------------
// TurretShapeData player mounting and dismounting
// ----------------------------------------------------------------------------
function TurretShapeData::isMountable(%this, %obj, %val)
{
%obj.mountable = %val;
}
function TurretShapeData::onMountObject(%this, %turret, %player, %node)
{
if (%turret.entranceThread >= 0)
{
%turret.setThreadDir(%turret.entranceThread, true);
%turret.setThreadPosition(%turret.entranceThread, 0);
%turret.playThread(%turret.entranceThread, "");
}
}
function TurretShapeData::onUnmountObject(%this, %turret, %player)
{
if (%turret.entranceThread >= 0)
{
// Play the entrance thread backwards for an exit
%turret.setThreadDir(%turret.entranceThread, false);
%turret.setThreadPosition(%turret.entranceThread, 1);
%turret.playThread(%turret.entranceThread, "");
}
}
function TurretShapeData::mountPlayer(%this, %turret, %player)
{
//echo("\c4TurretShapeData::mountPlayer("@ %this.getName() @", "@ %turret @", "@ %player.client.nameBase @")");
if (isObject(%turret) && %turret.getDamageState() !$= "Destroyed")
{
//%player.startFade(1000, 0, true);
//%this.schedule(1000, "setMountTurret", %turret, %player);
//%player.schedule(1500, "startFade", 1000, 0, false);
%this.setMountTurret(%turret, %player);
}
}
function TurretShapeData::setMountTurret(%this, %turret, %player)
{
//echo("\c4TurretShapeData::setMountTurret("@ %this.getName() @", "@ %turret @", "@ %player.client.nameBase @")");
if (isObject(%turret) && %turret.getDamageState() !$= "Destroyed")
{
%node = %this.findEmptySeat(%turret, %player);
if (%node >= 0)
{
//echo("\c4Mount Node: "@ %node);
%turret.mountObject(%player, %node);
//%player.playAudio(0, MountVehicleSound);
%player.mVehicle = %turret;
}
}
}
function TurretShapeData::findEmptySeat(%this, %turret, %player)
{
//echo("\c4This turret has "@ %this.numMountPoints @" mount points.");
for (%i = 0; %i < %this.numMountPoints; %i++)
{
%node = %turret.getMountNodeObject(%i);
if (%node == 0)
return %i;
}
return -1;
}
function TurretShapeData::switchSeats(%this, %turret, %player)
{
for (%i = 0; %i < %this.numMountPoints; %i++)
{
%node = %turret.getMountNodeObject(%i);
if (%node == %player || %node > 0)
continue;
if (%node == 0)
return %i;
}
return -1;
}
function TurretShapeData::onMount(%this, %turret, %player, %node)
{
//echo("\c4TurretShapeData::onMount("@ %this.getName() @", "@ %turret @", "@ %player.client.nameBase @")");
%player.client.RefreshVehicleHud(%turret, %this.reticle, %this.zoomReticle);
//%player.client.UpdateVehicleHealth(%turret);
}
function TurretShapeData::onUnmount(%this, %turret, %player, %node)
{
//echo("\c4TurretShapeData::onUnmount(" @ %this.getName() @ ", " @ %turret @ ", " @ %player.client.nameBase @ ")");
%player.client.RefreshVehicleHud(0, "", "");
}
// ----------------------------------------------------------------------------
// TurretShape damage
// ----------------------------------------------------------------------------
// This method is called by weapons fire
function TurretShape::damage(%this, %sourceObject, %position, %damage, %damageType)
{
//echo("\TurretShape::damage(" @ %this @ ", "@ %sourceObject @ ", " @ %position @ ", "@ %damage @ ", "@ %damageType @ ")");
%this.getDataBlock().damage(%this, %sourceObject, %position, %damage, %damageType);
}
// ----------------------------------------------------------------------------
// TurretDamage
// ----------------------------------------------------------------------------
// Customized kill message for deaths caused by turrets
function sendMsgClientKilled_TurretDamage( %msgType, %client, %sourceClient, %damLoc )
{
if ( %sourceClient $= "" ) // editor placed turret
messageAll( %msgType, '%1 was shot down by a turret!', %client.playerName );
else if ( %sourceClient == %client ) // own mine
messageAll( %msgType, '%1 kill by his own turret!', %client.playerName );
else // enemy placed mine
messageAll( %msgType, '%1 was killed by a turret of %2!', %client.playerName, %sourceClient.playerName );
}
// ----------------------------------------------------------------------------
// AITurretShapeData
// ----------------------------------------------------------------------------
function AITurretShapeData::onAdd(%this, %obj)
{
Parent::onAdd(%this, %obj);
%obj.mountable = false;
}
// Player has thrown a deployable turret. This copies from ItemData::onThrow()
function AITurretShapeData::onThrow(%this, %user, %amount)
{
// Remove the object from the inventory
if (%amount $= "")
%amount = 1;
if (%this.maxInventory !$= "")
if (%amount > %this.maxInventory)
%amount = %this.maxInventory;
if (!%amount)
return 0;
%user.decInventory(%this,%amount);
// Construct the actual object in the world, and add it to
// the mission group so it's cleaned up when the mission is
// done. The turret's rotation matches the player's.
%rot = %user.getEulerRotation();
%obj = new AITurretShape()
{
datablock = %this;
rotation = "0 0 1 " @ getWord(%rot, 2);
count = 1;
sourceObject = %user;
client = %user.client;
isAiControlled = true;
};
getRootScene().add(%obj);
// Let the turret know that we're a firend
%obj.addToIgnoreList(%user);
// We need to add this turret to a list on the client so that if we die,
// the turret will still ignore our player.
%client = %user.client;
if (%client)
{
if (!%client.ownedTurrets)
{
%client.ownedTurrets = new SimSet();
}
// Go through the client's owned turret list. Make sure we're
// a friend of every turret and every turret is a friend of ours.
// Commence hugging!
for (%i=0; %i<%client.ownedTurrets.getCount(); %i++)
{
%turret = %client.ownedTurrets.getObject(%i);
%turret.addToIgnoreList(%obj);
%obj.addToIgnoreList(%turret);
}
// Add ourselves to the client's owned list.
%client.ownedTurrets.add(%obj);
}
return %obj;
}
function AITurretShapeData::onDestroyed(%this, %turret, %lastState)
{
// This method is invoked by the ShapeBase code whenever the
// object's damage state changes.
%turret.playAudio(0, TurretDestroyed);
%turret.setAllGunsFiring(false);
%turret.resetTarget();
%turret.setTurretState( "Destroyed", true );
// Set the weapons to destoryed
for(%i = 0; %i < %this.numWeaponMountPoints; %i++)
{
%turret.setImageGenericTrigger(%i, 0, true);
}
Parent::onDestroyed(%this, %turret, %lastState);
}
function AITurretShapeData::OnScanning(%this, %turret)
{
//echo("AITurretShapeData::OnScanning: " SPC %this SPC %turret);
%turret.startScanForTargets();
%turret.playAudio(0, TurretScanningSound);
}
function AITurretShapeData::OnTarget(%this, %turret)
{
//echo("AITurretShapeData::OnTarget: " SPC %this SPC %turret);
%turret.startTrackingTarget();
%turret.playAudio(0, TargetAquiredSound);
}
function AITurretShapeData::OnNoTarget(%this, %turret)
{
//echo("AITurretShapeData::OnNoTarget: " SPC %this SPC %turret);
%turret.setAllGunsFiring(false);
%turret.recenterTurret();
%turret.playAudio(0, TargetLostSound);
}
function AITurretShapeData::OnFiring(%this, %turret)
{
//echo("AITurretShapeData::OnFiring: " SPC %this SPC %turret);
%turret.setAllGunsFiring(true);
}
function AITurretShapeData::OnThrown(%this, %turret)
{
//echo("AITurretShapeData::OnThrown: " SPC %this SPC %turret);
%turret.playAudio(0, TurretThrown);
}
function AITurretShapeData::OnDeploy(%this, %turret)
{
//echo("AITurretShapeData::OnDeploy: " SPC %this SPC %turret);
// Set the weapons to loaded
for(%i = 0; %i < %this.numWeaponMountPoints; %i++)
{
%turret.setImageLoaded(%i, true);
}
%turret.playAudio(0, TurretActivatedSound);
}
// ----------------------------------------------------------------------------
// Player deployable turret
// ----------------------------------------------------------------------------
// Cannot use the Weapon class for deployable turrets as it is already tied
// to ItemData.
function DeployableTurretWeapon::onUse(%this, %obj)
{
Weapon::onUse(%this, %obj);
}
function DeployableTurretWeapon::onPickup(%this, %obj, %shape, %amount)
{
Weapon::onPickup(%this, %obj, %shape, %amount);
}
function DeployableTurretWeapon::onInventory(%this, %obj, %amount)
{
if (%obj.client !$= "" && !%obj.isAiControlled)
{
%obj.client.setAmmoAmountHud( 1, %amount );
}
// Cycle weapons if we are out of ammo
if ( !%amount && ( %slot = %obj.getMountSlot( %this.image ) ) != -1 )
%obj.cycleWeapon( "prev" );
}
function DeployableTurretWeaponImage::onMount(%this, %obj, %slot)
{
// The turret doesn't use ammo from a player's perspective.
%obj.setImageAmmo(%slot, true);
%numTurrets = %obj.getInventory(%this.item);
if (%obj.client !$= "" && !%obj.isAiControlled)
%obj.client.RefreshWeaponHud( 1, %this.item.previewImage, %this.item.reticle, %this.item.zoomReticle, %numTurrets);
}
function DeployableTurretWeaponImage::onUnmount(%this, %obj, %slot)
{
if (%obj.client !$= "" && !%obj.isAiControlled)
%obj.client.RefreshWeaponHud(0, "", "");
}
function DeployableTurretWeaponImage::onFire(%this, %obj, %slot)
{
//echo("\DeployableTurretWeaponImage::onFire( "@%this.getName()@", "@%obj.client.nameBase@", "@%slot@" )");
// To fire a deployable turret is to throw it. Schedule the throw
// so that it doesn't happen during this ShapeBaseImageData's state machine.
// If we throw the last one then we end up unmounting while the state machine
// is still being processed.
%obj.schedule(0, "throw", %this.item);
}
| |
// 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 Microsoft.CodeAnalysis.UnitTests;
using Xunit;
namespace Desktop.Analyzers.UnitTests
{
public partial class DoNotUseInsecureDTDProcessingAnalyzerTests : DiagnosticAnalyzerTestBase
{
private static readonly string s_CA3075XmlTextReaderSetInsecureResolutionMessage = DesktopAnalyzersResources.XmlTextReaderSetInsecureResolutionMessage;
private DiagnosticResult GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(int line, int column)
{
return GetCSharpResultAt(line, column, CA3075RuleId, s_CA3075XmlTextReaderSetInsecureResolutionMessage);
}
private DiagnosticResult GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(int line, int column)
{
return GetBasicResultAt(line, column, CA3075RuleId, s_CA3075XmlTextReaderSetInsecureResolutionMessage);
}
[Fact]
public void UseXmlTextReaderNoCtorShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
var count = reader.AttributeCount;
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
Dim count = reader.AttributeCount
End Sub
End Class
End Namespace");
}
[Fact]
public void XmlTextReaderNoCtorSetResolverToNullShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
reader.XmlResolver = new XmlUrlResolver();
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(10, 13)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
reader.XmlResolver = New XmlUrlResolver()
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(7, 13)
);
}
[Fact]
public void XmlTextReaderNoCtorSetDtdProcessingToParseShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
reader.DtdProcessing = DtdProcessing.Parse;
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(10, 13)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
reader.DtdProcessing = DtdProcessing.Parse
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(7, 13)
);
}
[Fact]
public void XmlTextReaderNoCtorSetBothToInsecureValuesShouldGenerateDiagnostics()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader, XmlUrlResolver resolver)
{
reader.XmlResolver = resolver;
reader.DtdProcessing = DtdProcessing.Parse;
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(10, 13),
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(11, 13)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader, resolver As XmlUrlResolver)
reader.XmlResolver = resolver
reader.DtdProcessing = DtdProcessing.Parse
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(7, 13),
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(8, 13)
);
}
[Fact]
public void XmlTextReaderNoCtorSetInSecureResolverInTryClauseShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
try
{
reader.XmlResolver = new XmlUrlResolver();
}
catch { throw; }
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(12, 17)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
Try
reader.XmlResolver = New XmlUrlResolver()
Catch
Throw
End Try
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(8, 17)
);
}
[Fact]
public void XmlTextReaderNoCtorSetInSecureResolverInCatchBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
try { }
catch { reader.XmlResolver = new XmlUrlResolver(); }
finally {}
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(11, 21)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
Try
Catch
reader.XmlResolver = New XmlUrlResolver()
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(9, 17)
);
}
[Fact]
public void XmlTextReaderNoCtorSetInSecureResolverInFinallyBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
try { }
catch { throw; }
finally { reader.XmlResolver = new XmlUrlResolver(); }
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(12, 23)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
Try
Catch
Throw
Finally
reader.XmlResolver = New XmlUrlResolver()
End Try
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(11, 17)
);
}
[Fact]
public void XmlTextReaderNoCtorSetDtdprocessingToParseInTryClauseShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
try
{
reader.DtdProcessing = DtdProcessing.Parse;
}
catch { throw; }
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(12, 17)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
Try
reader.DtdProcessing = DtdProcessing.Parse
Catch
Throw
End Try
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(8, 17)
);
}
[Fact]
public void XmlTextReaderNoCtorSetDtdprocessingToParseInCatchBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
try { }
catch { reader.DtdProcessing = DtdProcessing.Parse; }
finally { }
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(11, 21)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
Try
Catch
reader.DtdProcessing = DtdProcessing.Parse
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(9, 17)
);
}
[Fact]
public void XmlTextReaderNoCtorSetDtdprocessingToParseInFinallyBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
try { }
catch { throw; }
finally { reader.DtdProcessing = DtdProcessing.Parse; }
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(12, 23)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
Try
Catch
Throw
Finally
reader.DtdProcessing = DtdProcessing.Parse
End Try
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(11, 17)
);
}
[Fact]
public void ConstructXmlTextReaderSetInsecureResolverInInitializerShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(string path)
{
XmlTextReader doc = new XmlTextReader(path)
{
XmlResolver = new XmlUrlResolver()
};
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(10, 33)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(path As String)
Dim doc As New XmlTextReader(path) With { _
.XmlResolver = New XmlUrlResolver() _
}
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(7, 24)
);
}
[Fact]
public void ConstructXmlTextReaderSetDtdProcessingParseInInitializerShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(string path)
{
XmlTextReader doc = new XmlTextReader(path)
{
DtdProcessing = DtdProcessing.Parse
};
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(10, 33)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(path As String)
Dim doc As New XmlTextReader(path) With { _
.DtdProcessing = DtdProcessing.Parse _
}
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(7, 24)
);
}
[Fact]
public void ConstructXmlTextReaderSetBothToInsecureValuesInInitializerShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(string path)
{
XmlTextReader doc = new XmlTextReader(path)
{
DtdProcessing = DtdProcessing.Parse,
XmlResolver = new XmlUrlResolver()
};
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(10, 33)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(path As String)
Dim doc As New XmlTextReader(path) With { _
.DtdProcessing = DtdProcessing.Parse, _
.XmlResolver = New XmlUrlResolver() _
}
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(7, 24)
);
}
[Fact]
public void XmlTextReaderDerivedTypeSetInsecureResolverShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System;
using System.Xml;
namespace TestNamespace
{
class DerivedType : XmlTextReader {}
class TestClass
{
void TestMethod()
{
var c = new DerivedType(){ XmlResolver = new XmlUrlResolver() };
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(13, 21)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class DerivedType
Inherits XmlTextReader
End Class
Class TestClass
Private Sub TestMethod()
Dim c = New DerivedType() With { _
.XmlResolver = New XmlUrlResolver() _
}
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(11, 21)
);
}
[Fact]
public void XmlTextReaderDerivedTypeSetDtdProcessingParseShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System;
using System.Xml;
namespace TestNamespace
{
class DerivedType : XmlTextReader {}
class TestClass
{
void TestMethod()
{
var c = new DerivedType(){ DtdProcessing = DtdProcessing.Parse };
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(13, 21)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class DerivedType
Inherits XmlTextReader
End Class
Class TestClass
Private Sub TestMethod()
Dim c = New DerivedType() With { _
.DtdProcessing = DtdProcessing.Parse _
}
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(11, 21)
);
}
[Fact]
public void XmlTextReaderCreatedAsTempSetSecureSettingsShouldNotGenerateDiagnostics()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
public void Method1(string path)
{
Method2(new XmlTextReader(path){ XmlResolver = null, DtdProcessing = DtdProcessing.Prohibit });
}
public void Method2(XmlTextReader reader){}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Public Sub Method1(path As String)
Method2(New XmlTextReader(path) With { _
.XmlResolver = Nothing, _
.DtdProcessing = DtdProcessing.Prohibit _
})
End Sub
Public Sub Method2(reader As XmlTextReader)
End Sub
End Class
End Namespace");
}
[Fact]
public void XmlTextReaderCreatedAsTempSetInsecureResolverShouldGenerateDiagnostics()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
public void Method1(string path)
{
Method2(new XmlTextReader(path){ XmlResolver = new XmlUrlResolver(), DtdProcessing = DtdProcessing.Prohibit });
}
public void Method2(XmlTextReader reader){}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(11, 21)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Public Sub Method1(path As String)
Method2(New XmlTextReader(path) With { _
.XmlResolver = New XmlUrlResolver(), _
.DtdProcessing = DtdProcessing.Prohibit _
})
End Sub
Public Sub Method2(reader As XmlTextReader)
End Sub
End Class
End Namespace
",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(8, 21)
);
}
[Fact]
public void XmlTextReaderCreatedAsTempSetDtdProcessingParseShouldGenerateDiagnostics()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
public void Method1(string path)
{
Method2(new XmlTextReader(path){ XmlResolver = null, DtdProcessing = DtdProcessing.Parse });
}
public void Method2(XmlTextReader reader){}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(11, 21)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Public Sub Method1(path As String)
Method2(New XmlTextReader(path) With { _
.XmlResolver = Nothing, _
.DtdProcessing = DtdProcessing.Parse _
})
End Sub
Public Sub Method2(reader As XmlTextReader)
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(8, 21)
);
}
}
}
| |
/*
* 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 MySql.Data.MySqlClient;
using OpenMetaverse;
using OpenSim.Framework;
using System;
using System.Reflection;
namespace OpenSim.Data.MySQL
{
public class MySQLGroupsData : IGroupsData
{
private MySqlGroupsGroupsHandler m_Groups;
private MySqlGroupsMembershipHandler m_Membership;
private MySqlGroupsRolesHandler m_Roles;
private MySqlGroupsRoleMembershipHandler m_RoleMembership;
private MySqlGroupsInvitesHandler m_Invites;
private MySqlGroupsNoticesHandler m_Notices;
private MySqlGroupsPrincipalsHandler m_Principals;
public MySQLGroupsData(string connectionString, string realm)
{
m_Groups = new MySqlGroupsGroupsHandler(connectionString, realm + "_groups", realm + "_Store");
m_Membership = new MySqlGroupsMembershipHandler(connectionString, realm + "_membership");
m_Roles = new MySqlGroupsRolesHandler(connectionString, realm + "_roles");
m_RoleMembership = new MySqlGroupsRoleMembershipHandler(connectionString, realm + "_rolemembership");
m_Invites = new MySqlGroupsInvitesHandler(connectionString, realm + "_invites");
m_Notices = new MySqlGroupsNoticesHandler(connectionString, realm + "_notices");
m_Principals = new MySqlGroupsPrincipalsHandler(connectionString, realm + "_principals");
}
#region groups table
public bool StoreGroup(GroupData data)
{
return m_Groups.Store(data);
}
public GroupData RetrieveGroup(UUID groupID)
{
GroupData[] groups = m_Groups.Get("GroupID", groupID.ToString());
if (groups.Length > 0)
return groups[0];
return null;
}
public GroupData RetrieveGroup(string name)
{
GroupData[] groups = m_Groups.Get("Name", name);
if (groups.Length > 0)
return groups[0];
return null;
}
public GroupData[] RetrieveGroups(string pattern)
{
if (string.IsNullOrEmpty(pattern))
pattern = "1";
else
pattern = string.Format("Name LIKE '%{0}%'", pattern);
return m_Groups.Get(string.Format("ShowInList=1 AND ({0}) ORDER BY Name LIMIT 100", pattern));
}
public bool DeleteGroup(UUID groupID)
{
return m_Groups.Delete("GroupID", groupID.ToString());
}
public int GroupsCount()
{
return (int)m_Groups.GetCount("Location=\"\"");
}
#endregion groups table
#region membership table
public MembershipData[] RetrieveMembers(UUID groupID)
{
return m_Membership.Get("GroupID", groupID.ToString());
}
public MembershipData RetrieveMember(UUID groupID, string pricipalID)
{
MembershipData[] m = m_Membership.Get(new string[] { "GroupID", "PrincipalID" },
new string[] { groupID.ToString(), pricipalID });
if (m != null && m.Length > 0)
return m[0];
return null;
}
public MembershipData[] RetrieveMemberships(string pricipalID)
{
return m_Membership.Get("PrincipalID", pricipalID.ToString());
}
public bool StoreMember(MembershipData data)
{
return m_Membership.Store(data);
}
public bool DeleteMember(UUID groupID, string pricipalID)
{
return m_Membership.Delete(new string[] { "GroupID", "PrincipalID" },
new string[] { groupID.ToString(), pricipalID });
}
public int MemberCount(UUID groupID)
{
return (int)m_Membership.GetCount("GroupID", groupID.ToString());
}
#endregion membership table
#region roles table
public bool StoreRole(RoleData data)
{
return m_Roles.Store(data);
}
public RoleData RetrieveRole(UUID groupID, UUID roleID)
{
RoleData[] data = m_Roles.Get(new string[] { "GroupID", "RoleID" },
new string[] { groupID.ToString(), roleID.ToString() });
if (data != null && data.Length > 0)
return data[0];
return null;
}
public RoleData[] RetrieveRoles(UUID groupID)
{
//return m_Roles.RetrieveRoles(groupID);
return m_Roles.Get("GroupID", groupID.ToString());
}
public bool DeleteRole(UUID groupID, UUID roleID)
{
return m_Roles.Delete(new string[] { "GroupID", "RoleID" },
new string[] { groupID.ToString(), roleID.ToString() });
}
public int RoleCount(UUID groupID)
{
return (int)m_Roles.GetCount("GroupID", groupID.ToString());
}
#endregion roles table
#region rolememberhip table
public RoleMembershipData[] RetrieveRolesMembers(UUID groupID)
{
RoleMembershipData[] data = m_RoleMembership.Get("GroupID", groupID.ToString());
return data;
}
public RoleMembershipData[] RetrieveRoleMembers(UUID groupID, UUID roleID)
{
RoleMembershipData[] data = m_RoleMembership.Get(new string[] { "GroupID", "RoleID" },
new string[] { groupID.ToString(), roleID.ToString() });
return data;
}
public RoleMembershipData[] RetrieveMemberRoles(UUID groupID, string principalID)
{
RoleMembershipData[] data = m_RoleMembership.Get(new string[] { "GroupID", "PrincipalID" },
new string[] { groupID.ToString(), principalID.ToString() });
return data;
}
public RoleMembershipData RetrieveRoleMember(UUID groupID, UUID roleID, string principalID)
{
RoleMembershipData[] data = m_RoleMembership.Get(new string[] { "GroupID", "RoleID", "PrincipalID" },
new string[] { groupID.ToString(), roleID.ToString(), principalID.ToString() });
if (data != null && data.Length > 0)
return data[0];
return null;
}
public int RoleMemberCount(UUID groupID, UUID roleID)
{
return (int)m_RoleMembership.GetCount(new string[] { "GroupID", "RoleID" },
new string[] { groupID.ToString(), roleID.ToString() });
}
public bool StoreRoleMember(RoleMembershipData data)
{
return m_RoleMembership.Store(data);
}
public bool DeleteRoleMember(RoleMembershipData data)
{
return m_RoleMembership.Delete(new string[] { "GroupID", "RoleID", "PrincipalID" },
new string[] { data.GroupID.ToString(), data.RoleID.ToString(), data.PrincipalID });
}
public bool DeleteMemberAllRoles(UUID groupID, string principalID)
{
return m_RoleMembership.Delete(new string[] { "GroupID", "PrincipalID" },
new string[] { groupID.ToString(), principalID });
}
#endregion rolememberhip table
#region principals table
public bool StorePrincipal(PrincipalData data)
{
return m_Principals.Store(data);
}
public PrincipalData RetrievePrincipal(string principalID)
{
PrincipalData[] p = m_Principals.Get("PrincipalID", principalID);
if (p != null && p.Length > 0)
return p[0];
return null;
}
public bool DeletePrincipal(string principalID)
{
return m_Principals.Delete("PrincipalID", principalID);
}
#endregion principals table
#region invites table
public bool StoreInvitation(InvitationData data)
{
return m_Invites.Store(data);
}
public InvitationData RetrieveInvitation(UUID inviteID)
{
InvitationData[] invites = m_Invites.Get("InviteID", inviteID.ToString());
if (invites != null && invites.Length > 0)
return invites[0];
return null;
}
public InvitationData RetrieveInvitation(UUID groupID, string principalID)
{
InvitationData[] invites = m_Invites.Get(new string[] { "GroupID", "PrincipalID" },
new string[] { groupID.ToString(), principalID });
if (invites != null && invites.Length > 0)
return invites[0];
return null;
}
public bool DeleteInvite(UUID inviteID)
{
return m_Invites.Delete("InviteID", inviteID.ToString());
}
public void DeleteOldInvites()
{
m_Invites.DeleteOld();
}
#endregion invites table
#region notices table
public bool StoreNotice(NoticeData data)
{
return m_Notices.Store(data);
}
public NoticeData RetrieveNotice(UUID noticeID)
{
NoticeData[] notices = m_Notices.Get("NoticeID", noticeID.ToString());
if (notices != null && notices.Length > 0)
return notices[0];
return null;
}
public NoticeData[] RetrieveNotices(UUID groupID)
{
NoticeData[] notices = m_Notices.Get("GroupID", groupID.ToString());
return notices;
}
public bool DeleteNotice(UUID noticeID)
{
return m_Notices.Delete("NoticeID", noticeID.ToString());
}
public void DeleteOldNotices()
{
m_Notices.DeleteOld();
}
#endregion notices table
#region combinations
public MembershipData RetrievePrincipalGroupMembership(string principalID, UUID groupID)
{
// TODO
return null;
}
public MembershipData[] RetrievePrincipalGroupMemberships(string principalID)
{
// TODO
return null;
}
#endregion combinations
}
public class MySqlGroupsGroupsHandler : MySQLGenericTableHandler<GroupData>
{
protected override Assembly Assembly
{
// WARNING! Moving migrations to this assembly!!!
get { return GetType().Assembly; }
}
public MySqlGroupsGroupsHandler(string connectionString, string realm, string store)
: base(connectionString, realm, store)
{
}
}
public class MySqlGroupsMembershipHandler : MySQLGenericTableHandler<MembershipData>
{
protected override Assembly Assembly
{
// WARNING! Moving migrations to this assembly!!!
get { return GetType().Assembly; }
}
public MySqlGroupsMembershipHandler(string connectionString, string realm)
: base(connectionString, realm, string.Empty)
{
}
}
public class MySqlGroupsRolesHandler : MySQLGenericTableHandler<RoleData>
{
protected override Assembly Assembly
{
// WARNING! Moving migrations to this assembly!!!
get { return GetType().Assembly; }
}
public MySqlGroupsRolesHandler(string connectionString, string realm)
: base(connectionString, realm, string.Empty)
{
}
}
public class MySqlGroupsRoleMembershipHandler : MySQLGenericTableHandler<RoleMembershipData>
{
protected override Assembly Assembly
{
// WARNING! Moving migrations to this assembly!!!
get { return GetType().Assembly; }
}
public MySqlGroupsRoleMembershipHandler(string connectionString, string realm)
: base(connectionString, realm, string.Empty)
{
}
}
public class MySqlGroupsInvitesHandler : MySQLGenericTableHandler<InvitationData>
{
protected override Assembly Assembly
{
// WARNING! Moving migrations to this assembly!!!
get { return GetType().Assembly; }
}
public MySqlGroupsInvitesHandler(string connectionString, string realm)
: base(connectionString, realm, string.Empty)
{
}
public void DeleteOld()
{
uint now = (uint)Util.UnixTimeSinceEpoch();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.CommandText = String.Format("delete from {0} where TMStamp < ?tstamp", m_Realm);
cmd.Parameters.AddWithValue("?tstamp", now - 14 * 24 * 60 * 60); // > 2 weeks old
ExecuteNonQuery(cmd);
}
}
}
public class MySqlGroupsNoticesHandler : MySQLGenericTableHandler<NoticeData>
{
protected override Assembly Assembly
{
// WARNING! Moving migrations to this assembly!!!
get { return GetType().Assembly; }
}
public MySqlGroupsNoticesHandler(string connectionString, string realm)
: base(connectionString, realm, string.Empty)
{
}
public void DeleteOld()
{
uint now = (uint)Util.UnixTimeSinceEpoch();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.CommandText = String.Format("delete from {0} where TMStamp < ?tstamp", m_Realm);
cmd.Parameters.AddWithValue("?tstamp", now - 14 * 24 * 60 * 60); // > 2 weeks old
ExecuteNonQuery(cmd);
}
}
}
public class MySqlGroupsPrincipalsHandler : MySQLGenericTableHandler<PrincipalData>
{
protected override Assembly Assembly
{
// WARNING! Moving migrations to this assembly!!!
get { return GetType().Assembly; }
}
public MySqlGroupsPrincipalsHandler(string connectionString, string realm)
: base(connectionString, realm, string.Empty)
{
}
}
}
| |
//
// SourceRowRenderer.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2005-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Gtk;
using Gdk;
using Pango;
using Hyena.Gui;
using Hyena.Gui.Theming;
using Hyena.Gui.Theatrics;
using Banshee.ServiceStack;
namespace Banshee.Sources.Gui
{
public class SourceRowRenderer : CellRendererText
{
protected SourceRowRenderer (IntPtr raw) : base (raw)
{
}
public static void CellDataHandler (ICellLayout layout, CellRenderer cell, ITreeModel model, TreeIter iter)
{
SourceRowRenderer renderer = cell as SourceRowRenderer;
if (renderer == null) {
return;
}
var type = model.GetValue (iter, (int)SourceModel.Columns.Type);
if (type == null || (SourceModel.EntryType) type != SourceModel.EntryType.Source) {
renderer.Visible = false;
return;
}
Source source = model.GetValue (iter, 0) as Source;
renderer.Source = source;
renderer.Iter = iter;
if (source == null) {
return;
}
renderer.Visible = true;
renderer.Text = source.Name;
renderer.Sensitive = source.CanActivate;
}
private Source source;
public Source Source {
get { return source; }
set { source = value; }
}
private SourceView view;
private Widget parent_widget;
public Widget ParentWidget {
get { return parent_widget; }
set { parent_widget = value; }
}
private TreeIter iter = TreeIter.Zero;
public TreeIter Iter {
get { return iter; }
set { iter = value; }
}
private int row_height = 22;
public int RowHeight {
get { return row_height; }
set { row_height = value; }
}
public SourceRowRenderer ()
{
}
private StateFlags RendererStateToWidgetState (Widget widget, CellRendererState flags)
{
if (!Sensitive) {
return StateFlags.Insensitive;
} else if ((flags & CellRendererState.Selected) == CellRendererState.Selected) {
return widget.HasFocus ? StateFlags.Selected : StateFlags.Active;
} else if ((flags & CellRendererState.Prelit) == CellRendererState.Prelit) {
ComboBox box = parent_widget as ComboBox;
return box != null && box.PopupShown ? StateFlags.Prelight : StateFlags.Normal;
} else if (widget.StateFlags == StateFlags.Insensitive) {
return StateFlags.Insensitive;
} else {
return StateFlags.Normal;
}
}
private int Depth {
get {
return Source.Parent != null ? 1 : 0;
}
}
protected override void OnGetPreferredWidth (Widget widget, out int minimum_width, out int natural_width)
{
base.OnGetPreferredWidth (widget, out minimum_width, out natural_width);
if (!(widget is TreeView)) {
minimum_width = natural_width = 200;
}
}
protected override void OnGetPreferredHeight (Widget widget, out int minimum_height, out int natural_height)
{
int minimum_text_h, natural_text_h;
base.GetPreferredHeight (widget, out minimum_text_h, out natural_text_h);
minimum_height = (int)Math.Max (RowHeight, minimum_text_h);
natural_height = (int)Math.Max (RowHeight, natural_text_h);
}
private int expander_right_x;
public bool InExpander (int x)
{
return x < expander_right_x;
}
protected override void OnRender (Cairo.Context cr, Widget widget, Gdk.Rectangle background_area,
Gdk.Rectangle cell_area, CellRendererState flags)
{
if (source == null || source is SourceManager.GroupSource) {
return;
}
view = widget as SourceView;
bool selected = view != null && view.Selection.IterIsSelected (iter);
StateFlags state = RendererStateToWidgetState (widget, flags);
RenderBackground (cr, background_area, selected, state);
int title_layout_width = 0, title_layout_height = 0;
int count_layout_width = 0, count_layout_height = 0;
int max_title_layout_width;
int img_padding = 6;
int expander_icon_spacing = 3;
int x = cell_area.X;
bool np_etc = (source.Order + Depth * 100) < 40;
if (!np_etc) {
x += Depth * img_padding + (int)Xpad;
} else {
// Don't indent NowPlaying and Play Queue as much
x += Math.Max (0, (int)Xpad - 2);
}
// Draw the expander if the source has children
double exp_h = (cell_area.Height - 2.0*Ypad) / 2.0;
double exp_w = exp_h * 1.6;
int y = Middle (cell_area, (int)exp_h);
if (view != null && source.Children != null && source.Children.Count > 0) {
var r = new Gdk.Rectangle (x, y, (int)exp_w, (int)exp_h);
view.Theme.DrawArrow (cr, r, source.Expanded ? Math.PI/2.0 : 0.0);
}
if (!np_etc) {
x += (int) exp_w;
x += 2; // a little spacing after the expander
expander_right_x = x;
}
// Draw icon
Pixbuf icon = SourceIconResolver.ResolveIcon (source, RowHeight);
bool dispose_icon = false;
if (state == StateFlags.Insensitive) {
// Code ported from gtk_cell_renderer_pixbuf_render()
var icon_source = new IconSource () {
Pixbuf = icon,
Size = IconSize.SmallToolbar,
SizeWildcarded = false
};
icon = widget.StyleContext.RenderIconPixbuf (icon_source, (IconSize)(-1));
dispose_icon = true;
icon_source.Dispose ();
}
if (icon != null) {
x += expander_icon_spacing;
cr.Save ();
Gdk.CairoHelper.SetSourcePixbuf (cr, icon, x, Middle (cell_area, icon.Height));
cr.Paint ();
cr.Restore ();
x += icon.Width;
if (dispose_icon) {
icon.Dispose ();
}
}
// Setup font info for the title/count, and see if we should show the count
bool hide_count = source.EnabledCount <= 0 || source.Properties.Get<bool> ("SourceView.HideCount");
FontDescription fd = widget.PangoContext.FontDescription.Copy ();
fd.Weight = (ISource)ServiceManager.PlaybackController.NextSource == (ISource)source
? Pango.Weight.Bold
: Pango.Weight.Normal;
if (view != null && source == view.NewPlaylistSource) {
fd.Style = Pango.Style.Italic;
hide_count = true;
}
Pango.Layout title_layout = new Pango.Layout (widget.PangoContext);
Pango.Layout count_layout = null;
// If we have a count to draw, setup its fonts and see how wide it is to see if we have room
if (!hide_count) {
count_layout = new Pango.Layout (widget.PangoContext);
count_layout.FontDescription = fd;
count_layout.SetMarkup (String.Format ("<span size=\"small\">{0}</span>", source.EnabledCount));
count_layout.GetPixelSize (out count_layout_width, out count_layout_height);
}
// Hide the count if the title has no space
max_title_layout_width = cell_area.Width - x - count_layout_width;//(icon == null ? 0 : icon.Width) - count_layout_width - 10;
if (!hide_count && max_title_layout_width <= 0) {
hide_count = true;
}
// Draw the source Name
title_layout.FontDescription = fd;
title_layout.Width = (int)(max_title_layout_width * Pango.Scale.PangoScale);
title_layout.Ellipsize = EllipsizeMode.End;
title_layout.SetText (source.Name);
title_layout.GetPixelSize (out title_layout_width, out title_layout_height);
x += img_padding;
widget.StyleContext.RenderLayout (cr, x, Middle (cell_area, title_layout_height), title_layout);
title_layout.Dispose ();
// Draw the count
if (!hide_count) {
if (view != null) {
cr.SetSourceColor (state == StateFlags.Normal || (view != null && state == StateFlags.Prelight)
? view.Theme.TextMidColor
: CairoExtensions.GdkRGBAToCairoColor (view.Theme.Widget.StyleContext.GetColor (state)));
cr.MoveTo (
cell_area.X + cell_area.Width - count_layout_width - 2,
cell_area.Y + 0.5 + (double)(cell_area.Height - count_layout_height) / 2.0);
Pango.CairoHelper.ShowLayout (cr, count_layout);
}
count_layout.Dispose ();
}
fd.Dispose ();
}
private void RenderBackground (Cairo.Context cr, Gdk.Rectangle background_area,
bool selected, StateFlags state)
{
if (view == null) {
return;
}
if (selected) {
// Just leave the standard GTK selection and focus
return;
}
if (!TreeIter.Zero.Equals (iter) && iter.Equals (view.HighlightedIter)) {
// Item is highlighted but not selected
view.Theme.DrawHighlightFrame (cr, background_area.X + 1, background_area.Y + 1,
background_area.Width - 2, background_area.Height - 2);
} else if (view.NotifyStage.ActorCount > 0) {
if (!TreeIter.Zero.Equals (iter) && view.NotifyStage.Contains (iter)) {
// Render the current step of the notification animation
Actor<TreeIter> actor = view.NotifyStage[iter];
Cairo.Color normal_color = CairoExtensions.GdkRGBAToCairoColor (view.StyleContext.GetBackgroundColor (StateFlags.Normal));
Cairo.Color selected_color = CairoExtensions.GdkRGBAToCairoColor (view.StyleContext.GetBackgroundColor (StateFlags.Selected));
Cairo.Color notify_bg_color = CairoExtensions.AlphaBlend (normal_color, selected_color, 0.5);
notify_bg_color.A = Math.Sin (actor.Percent * Math.PI);
cr.SetSourceColor (notify_bg_color);
CairoExtensions.RoundedRectangle (cr, background_area.X, background_area.Y, background_area.Width, background_area.Height, view.Theme.Context.Radius);
cr.Fill ();
}
}
}
private int Middle (Gdk.Rectangle area, int height)
{
return area.Y + (int)Math.Round ((double)(area.Height - height) / 2.0, MidpointRounding.AwayFromZero);
}
protected override ICellEditable OnStartEditing (Gdk.Event evnt, Widget widget, string path,
Gdk.Rectangle background_area, Gdk.Rectangle cell_area, CellRendererState flags)
{
CellEditEntry text = new CellEditEntry ();
text.EditingDone += OnEditDone;
text.Text = source.Name;
text.path = path;
text.Show ();
view.EditingRow = true;
return text;
}
private void OnEditDone (object o, EventArgs args)
{
CellEditEntry edit = (CellEditEntry)o;
if (view == null) {
return;
}
view.EditingRow = false;
using (var tree_path = new TreePath (edit.path)) {
view.UpdateRow (tree_path, edit.Text);
}
}
}
}
| |
//
// PersonaAuthorizer.cs
//
// Author:
// Zachary Gramana <zack@xamarin.com>
//
// Copyright (c) 2013, 2014 Xamarin Inc (http://www.xamarin.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.
//
/**
* Original iOS version by Jens Alfke
* Ported to Android by Marty Schoch, Traun Leyden
*
* Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Couchbase.Lite;
using Couchbase.Lite.Auth;
using Couchbase.Lite.Util;
using Sharpen;
namespace Couchbase.Lite.Auth
{
public class PersonaAuthorizer : Authorizer
{
public const string LoginParameterAssertion = "assertion";
private static IDictionary<IList<string>, string> assertions;
public const string AssertionFieldEmail = "email";
public const string AssertionFieldOrigin = "origin";
public const string AssertionFieldExpiration = "exp";
public const string QueryParameter = "personaAssertion";
private bool skipAssertionExpirationCheck;
private string emailAddress;
public PersonaAuthorizer(string emailAddress)
{
// set to true to skip checking whether assertions have expired (useful for testing)
this.emailAddress = emailAddress;
}
public virtual void SetSkipAssertionExpirationCheck(bool skipAssertionExpirationCheck
)
{
this.skipAssertionExpirationCheck = skipAssertionExpirationCheck;
}
public virtual bool IsSkipAssertionExpirationCheck()
{
return skipAssertionExpirationCheck;
}
public virtual string GetEmailAddress()
{
return emailAddress;
}
protected internal virtual bool IsAssertionExpired(IDictionary<string, object> parsedAssertion
)
{
if (this.IsSkipAssertionExpirationCheck() == true)
{
return false;
}
DateTime exp;
exp = (DateTime)parsedAssertion.Get(AssertionFieldExpiration);
DateTime now = new DateTime();
if (exp.Before(now))
{
Log.W(Database.Tag, string.Format("%s assertion for %s expired: %s", this.GetType
(), this.emailAddress, exp));
return true;
}
return false;
}
public virtual string AssertionForSite(Uri site)
{
string assertion = AssertionForEmailAndSite(this.emailAddress, site);
if (assertion == null)
{
Log.W(Database.Tag, string.Format("%s %s no assertion found for: %s", this.GetType
(), this.emailAddress, site));
return null;
}
IDictionary<string, object> result = ParseAssertion(assertion);
if (IsAssertionExpired(result))
{
return null;
}
return assertion;
}
public override bool UsesCookieBasedLogin()
{
return true;
}
public override IDictionary<string, string> LoginParametersForSite(Uri site)
{
IDictionary<string, string> loginParameters = new Dictionary<string, string>();
string assertion = AssertionForSite(site);
if (assertion != null)
{
loginParameters.Put(LoginParameterAssertion, assertion);
return loginParameters;
}
else
{
return null;
}
}
public override string LoginPathForSite(Uri site)
{
return "/_persona";
}
public static string RegisterAssertion(string assertion)
{
lock (typeof(PersonaAuthorizer))
{
string email;
string origin;
IDictionary<string, object> result = ParseAssertion(assertion);
email = (string)result.Get(AssertionFieldEmail);
origin = (string)result.Get(AssertionFieldOrigin);
// Normalize the origin URL string:
try
{
Uri originURL = new Uri(origin);
if (origin == null)
{
throw new ArgumentException("Invalid assertion, origin was null");
}
origin = originURL.ToExternalForm().ToLower();
}
catch (UriFormatException e)
{
string message = "Error registering assertion: " + assertion;
Log.E(Database.Tag, message, e);
throw new ArgumentException(message, e);
}
return RegisterAssertion(assertion, email, origin);
}
}
/// <summary>
/// don't use this!! this was factored out for testing purposes, and had to be
/// made public since tests are in their own package.
/// </summary>
/// <remarks>
/// don't use this!! this was factored out for testing purposes, and had to be
/// made public since tests are in their own package.
/// </remarks>
public static string RegisterAssertion(string assertion, string email, string origin
)
{
lock (typeof(PersonaAuthorizer))
{
IList<string> key = new AList<string>();
key.AddItem(email);
key.AddItem(origin);
if (assertions == null)
{
assertions = new Dictionary<IList<string>, string>();
}
Log.D(Database.Tag, "PersonaAuthorizer registering key: " + key);
assertions.Put(key, assertion);
return email;
}
}
public static IDictionary<string, object> ParseAssertion(string assertion)
{
// https://github.com/mozilla/id-specs/blob/prod/browserid/index.md
// http://self-issued.info/docs/draft-jones-json-web-token-04.html
IDictionary<string, object> result = new Dictionary<string, object>();
string[] components = assertion.Split("\\.");
// split on "."
if (components.Length < 4)
{
throw new ArgumentException("Invalid assertion given, only " + components.Length
+ " found. Expected 4+");
}
string component1Decoded = Sharpen.Runtime.GetStringForBytes(Base64.Decode(components
[1], Base64.Default));
string component3Decoded = Sharpen.Runtime.GetStringForBytes(Base64.Decode(components
[3], Base64.Default));
try
{
ObjectWriter mapper = new ObjectWriter();
IDictionary<object, object> component1Json = mapper.ReadValue<IDictionary>(component1Decoded
);
IDictionary<object, object> principal = (IDictionary<object, object>)component1Json
.Get("principal");
result.Put(AssertionFieldEmail, principal.Get("email"));
IDictionary<object, object> component3Json = mapper.ReadValue<IDictionary>(component3Decoded
);
result.Put(AssertionFieldOrigin, component3Json.Get("aud"));
long expObject = (long)component3Json.Get("exp");
Log.D(Database.Tag, "PersonaAuthorizer exp: " + expObject + " class: " + expObject
.GetType());
DateTime expDate = Sharpen.Extensions.CreateDate(expObject);
result.Put(AssertionFieldExpiration, expDate);
}
catch (IOException e)
{
string message = "Error parsing assertion: " + assertion;
Log.E(Database.Tag, message, e);
throw new ArgumentException(message, e);
}
return result;
}
public static string AssertionForEmailAndSite(string email, Uri site)
{
IList<string> key = new AList<string>();
key.AddItem(email);
key.AddItem(site.ToExternalForm().ToLower());
Log.D(Database.Tag, "PersonaAuthorizer looking up key: " + key + " from list of assertions"
);
return assertions.Get(key);
}
}
}
| |
//
// Copyright (C) 2009 Amr Hassan
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
using System;
using System.Collections.Generic;
using System.Xml;
namespace UB.LastFM.Services
{
/// <summary>
/// A Last.fm Group.
/// </summary>
public class Group : Base, IEquatable<Group>, IHasWeeklyAlbumCharts, IHasWeeklyArtistCharts,
IHasWeeklyTrackCharts, IHasURL
{
/// <summary>
/// Name of the group.
/// </summary>
public string Name {get; private set;}
public Group(string groupName, Session session)
:base(session)
{
Name = groupName;
}
internal override RequestParameters getParams ()
{
RequestParameters p = new RequestParameters();
p["group"] = Name;
return p;
}
/// <summary>
/// String representation of the object.
/// </summary>
/// <returns>
/// A <see cref="System.String"/>
/// </returns>
public override string ToString()
{
return Name;
}
/// <summary>
/// Returns the latest weekly track chart for this group.
/// </summary>
/// <returns>
/// A <see cref="WeeklyTrackChart"/>
/// </returns>
public WeeklyTrackChart GetWeeklyTrackChart()
{
XmlDocument doc = request("group.getWeeklyTrackChart");
XmlNode n = doc.GetElementsByTagName("weeklytrackchart")[0];
DateTime nfrom = Utilities.TimestampToDateTime(Int64.Parse(n.Attributes[1].InnerText), DateTimeKind.Utc);
DateTime nto = Utilities.TimestampToDateTime(Int64.Parse(n.Attributes[2].InnerText), DateTimeKind.Utc);
WeeklyTrackChart chart = new WeeklyTrackChart(new WeeklyChartTimeSpan(nfrom, nto));
foreach(XmlNode node in doc.GetElementsByTagName("track"))
{
int rank = Int32.Parse(node.Attributes[0].InnerText);
int playcount = Int32.Parse(extract(node, "playcount"));
WeeklyTrackChartItem item =
new WeeklyTrackChartItem(new Track(extract(node, "artist"), extract(node, "name"), Session),
rank, playcount, new WeeklyChartTimeSpan(nfrom, nto));
chart.Add(item);
}
return chart;
}
/// <summary>
/// Returns the weekly track chart for this group in the given <see cref="UB.LastFM.Services.WeeklyChartTimeSpan"/>.
/// </summary>
/// <param name="span">
/// A <see cref="WeeklyChartTimeSpan"/>
/// </param>
/// <returns>
/// A <see cref="WeeklyTrackChart"/>
/// </returns>
public WeeklyTrackChart GetWeeklyTrackChart(WeeklyChartTimeSpan span)
{
RequestParameters p = getParams();
p["from"] = Utilities.DateTimeToUTCTimestamp(span.From).ToString();
p["to"] = Utilities.DateTimeToUTCTimestamp(span.To).ToString();
XmlDocument doc = request("group.getWeeklyTrackChart", p);
XmlNode n = doc.GetElementsByTagName("weeklytrackchart")[0];
DateTime nfrom = Utilities.TimestampToDateTime(Int64.Parse(n.Attributes[1].InnerText), DateTimeKind.Utc);
DateTime nto = Utilities.TimestampToDateTime(Int64.Parse(n.Attributes[2].InnerText), DateTimeKind.Utc);
WeeklyTrackChart chart = new WeeklyTrackChart(new WeeklyChartTimeSpan(nfrom, nto));
foreach(XmlNode node in doc.GetElementsByTagName("track"))
{
int rank = Int32.Parse(node.Attributes[0].InnerText);
int playcount = Int32.Parse(extract(node, "playcount"));
WeeklyTrackChartItem item =
new WeeklyTrackChartItem(new Track(extract(node, "artist"), extract(node, "name"), Session),
rank, playcount, new WeeklyChartTimeSpan(nfrom, nto));
chart.Add(item);
}
return chart;
}
/// <summary>
/// Returns the latest weekly artist chart for this group.
/// </summary>
/// <returns>
/// A <see cref="WeeklyArtistChart"/>
/// </returns>
public WeeklyArtistChart GetWeeklyArtistChart()
{
XmlDocument doc = request("group.getWeeklyArtistChart");
XmlNode n = doc.GetElementsByTagName("weeklyartistchart")[0];
DateTime nfrom = Utilities.TimestampToDateTime(Int64.Parse(n.Attributes[1].InnerText), DateTimeKind.Utc);
DateTime nto = Utilities.TimestampToDateTime(Int64.Parse(n.Attributes[2].InnerText), DateTimeKind.Utc);
WeeklyArtistChart chart = new WeeklyArtistChart(new WeeklyChartTimeSpan(nfrom, nto));
foreach(XmlNode node in doc.GetElementsByTagName("artist"))
{
int rank = Int32.Parse(node.Attributes[0].InnerText);
int playcount = Int32.Parse(extract(node, "playcount"));
WeeklyArtistChartItem item =
new WeeklyArtistChartItem(new Artist(extract(node, "name"), Session),
rank, playcount, new WeeklyChartTimeSpan(nfrom, nto));
chart.Add(item);
}
return chart;
}
/// <summary>
/// Returns the weekly artist chart for this group in the given
/// <see cref="UB.LastFM.Services.WeeklyChartTimeSpan"/>.
/// </summary>
/// <param name="span">
/// A <see cref="WeeklyChartTimeSpan"/>
/// </param>
/// <returns>
/// A <see cref="WeeklyArtistChart"/>
/// </returns>
public WeeklyArtistChart GetWeeklyArtistChart(WeeklyChartTimeSpan span)
{
RequestParameters p = getParams();
p["from"] = Utilities.DateTimeToUTCTimestamp(span.From).ToString();
p["to"] = Utilities.DateTimeToUTCTimestamp(span.To).ToString();
XmlDocument doc = request("group.getWeeklyArtistChart", p);
XmlNode n = doc.GetElementsByTagName("weeklyartistchart")[0];
DateTime nfrom = Utilities.TimestampToDateTime(Int64.Parse(n.Attributes[1].InnerText), DateTimeKind.Utc);
DateTime nto = Utilities.TimestampToDateTime(Int64.Parse(n.Attributes[2].InnerText), DateTimeKind.Utc);
WeeklyArtistChart chart = new WeeklyArtistChart(new WeeklyChartTimeSpan(nfrom, nto));
foreach(XmlNode node in doc.GetElementsByTagName("artist"))
{
int rank = Int32.Parse(node.Attributes[0].InnerText);
int playcount = Int32.Parse(extract(node, "playcount"));
WeeklyArtistChartItem item =
new WeeklyArtistChartItem(new Artist(extract(node, "name"), Session),
rank, playcount, new WeeklyChartTimeSpan(nfrom, nto));
chart.Add(item);
}
return chart;
}
/// <summary>
/// Returns the latest weekly album chart for this group.
/// </summary>
/// <returns>
/// A <see cref="WeeklyAlbumChart"/>
/// </returns>
public WeeklyAlbumChart GetWeeklyAlbumChart()
{
XmlDocument doc = request("group.getWeeklyAlbumChart");
XmlNode n = doc.GetElementsByTagName("weeklyalbumchart")[0];
DateTime nfrom = Utilities.TimestampToDateTime(Int64.Parse(n.Attributes[1].InnerText), DateTimeKind.Utc);
DateTime nto = Utilities.TimestampToDateTime(Int64.Parse(n.Attributes[2].InnerText), DateTimeKind.Utc);
WeeklyAlbumChart chart = new WeeklyAlbumChart(new WeeklyChartTimeSpan(nfrom, nto));
foreach(XmlNode node in doc.GetElementsByTagName("album"))
{
int rank = Int32.Parse(node.Attributes[0].InnerText);
int playcount = Int32.Parse(extract(node, "playcount"));
WeeklyAlbumChartItem item =
new WeeklyAlbumChartItem(new Album(extract(node, "artist"), extract(node, "name"), Session),
rank, playcount, new WeeklyChartTimeSpan(nfrom, nto));
chart.Add(item);
}
return chart;
}
/// <summary>
/// Returns the weekly album chart for this group in the given <see cref="UB.LastFM.Services.WeeklyChartTimeSpan"/>.
/// </summary>
/// <param name="span">
/// A <see cref="WeeklyChartTimeSpan"/>
/// </param>
/// <returns>
/// A <see cref="WeeklyAlbumChart"/>
/// </returns>
public WeeklyAlbumChart GetWeeklyAlbumChart(WeeklyChartTimeSpan span)
{
RequestParameters p = getParams();
p["from"] = Utilities.DateTimeToUTCTimestamp(span.From).ToString();
p["to"] = Utilities.DateTimeToUTCTimestamp(span.To).ToString();
XmlDocument doc = request("group.getWeeklyAlbumChart", p);
XmlNode n = doc.GetElementsByTagName("weeklyalbumchart")[0];
DateTime nfrom = Utilities.TimestampToDateTime(Int64.Parse(n.Attributes[1].InnerText), DateTimeKind.Utc);
DateTime nto = Utilities.TimestampToDateTime(Int64.Parse(n.Attributes[2].InnerText), DateTimeKind.Utc);
WeeklyAlbumChart chart = new WeeklyAlbumChart(new WeeklyChartTimeSpan(nfrom, nto));
foreach(XmlNode node in doc.GetElementsByTagName("album"))
{
int rank = Int32.Parse(node.Attributes[0].InnerText);
int playcount = Int32.Parse(extract(node, "playcount"));
WeeklyAlbumChartItem item =
new WeeklyAlbumChartItem(new Album(extract(node, "artist"), extract(node, "name"), Session),
rank, playcount, new WeeklyChartTimeSpan(nfrom, nto));
chart.Add(item);
}
return chart;
}
/// <summary>
/// Returns the available timespans for charts available for this group.
/// </summary>
/// <returns>
/// A <see cref="WeeklyChartTimeSpan"/>
/// </returns>
public WeeklyChartTimeSpan[] GetWeeklyChartTimeSpans()
{
XmlDocument doc = request("group.getWeeklyChartList");
List<WeeklyChartTimeSpan> list = new List<WeeklyChartTimeSpan>();
foreach(XmlNode node in doc.GetElementsByTagName("chart"))
{
long lfrom = long.Parse(node.Attributes[0].InnerText);
long lto = long.Parse(node.Attributes[1].InnerText);
DateTime from = Utilities.TimestampToDateTime(lfrom, DateTimeKind.Utc);
DateTime to = Utilities.TimestampToDateTime(lto, DateTimeKind.Utc);
list.Add(new WeeklyChartTimeSpan(from, to));
}
return list.ToArray();
}
public bool Equals(Group group)
{
return (group.Name == this.Name);
}
/// <summary>
/// Returns the Last.fm page of this object.
/// </summary>
/// <param name="language">
/// A <see cref="SiteLanguage"/>
/// </param>
/// <returns>
/// A <see cref="System.String"/>
/// </returns>
public string GetURL(SiteLanguage language)
{
string domain = getSiteDomain(language);
return "http://" + domain + "/group/" + urlSafe(Name);
}
/// <summary>
/// The object's Last.fm page url.
/// </summary>
public string URL
{ get { return GetURL(SiteLanguage.English); } }
/// <value>
/// The members in this group.
/// </value>
public GroupMembers Members
{ get { return new GroupMembers(this, Session); } }
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.Serialization;
using System.Text;
//Thanks to supersonicclay
//From https://github.com/supersonicclay/csharp-date/blob/master/CSharpDate/Date.cs
namespace Signum.Utilities
{
[Serializable, TypeConverter(typeof(DateTypeConverter))]
public struct Date : IComparable, IFormattable, ISerializable, IComparable<Date>, IEquatable<Date>
{
private DateTime _dt;
public static readonly Date MaxValue = new Date(DateTime.MaxValue);
public static readonly Date MinValue = new Date(DateTime.MinValue);
public Date(int year, int month, int day)
{
this._dt = new DateTime(year, month, day);
}
public Date(DateTime dateTime)
{
this._dt = dateTime.AddTicks(-dateTime.Ticks % TimeSpan.TicksPerDay);
}
private Date(SerializationInfo info, StreamingContext context)
{
this._dt = DateTime.FromFileTime(info.GetInt64("ticks"));
}
public static TimeSpan operator -(Date d1, Date d2)
{
return d1._dt - d2._dt;
}
public static DateTime operator -(Date d, TimeSpan t)
{
return d._dt - t;
}
public static bool operator !=(Date d1, Date d2)
{
return d1._dt != d2._dt;
}
public static DateTime operator +(Date d, TimeSpan t)
{
return d._dt + t;
}
public static bool operator <(Date d1, Date d2)
{
return d1._dt < d2._dt;
}
public static bool operator <=(Date d1, Date d2)
{
return d1._dt <= d2._dt;
}
public static bool operator ==(Date d1, Date d2)
{
return d1._dt == d2._dt;
}
public static bool operator >(Date d1, Date d2)
{
return d1._dt > d2._dt;
}
public static bool operator >=(Date d1, Date d2)
{
return d1._dt >= d2._dt;
}
public static implicit operator DateTime(Date d)
{
return d._dt;
}
public static explicit operator Date(DateTime d)
{
return new Date(d);
}
public int Day
{
get
{
return this._dt.Day;
}
}
public DayOfWeek DayOfWeek
{
get
{
return this._dt.DayOfWeek;
}
}
public int DayOfYear
{
get
{
return this._dt.DayOfYear;
}
}
public int Month
{
get
{
return this._dt.Month;
}
}
public static Date Today
{
get
{
return new Date(DateTime.Today);
}
}
public int Year
{
get
{
return this._dt.Year;
}
}
public long Ticks
{
get
{
return this._dt.Ticks;
}
}
public Date AddDays(int value)
{
return new Date(this._dt.AddDays(value));
}
public Date AddMonths(int months)
{
return new Date(this._dt.AddMonths(months));
}
public Date AddYears(int value)
{
return new Date(this._dt.AddYears(value));
}
public static int Compare(Date d1, Date d2)
{
return d1.CompareTo(d2);
}
public int CompareTo(Date value)
{
return this._dt.CompareTo(value._dt);
}
public int CompareTo(object? value)
{
return this._dt.CompareTo(value);
}
public static int DaysInMonth(int year, int month)
{
return DateTime.DaysInMonth(year, month);
}
public bool Equals(Date value)
{
return this._dt.Equals(value._dt);
}
public override bool Equals(object? value)
{
return value is Date && this._dt.Equals(((Date)value)._dt);
}
public override int GetHashCode()
{
return this._dt.GetHashCode();
}
public static bool Equals(Date d1, Date d2)
{
return d1._dt.Equals(d2._dt);
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("ticks", this._dt.Ticks);
}
public static bool IsLeapYear(int year)
{
return DateTime.IsLeapYear(year);
}
public static Date Parse(string s)
{
return new Date(DateTime.Parse(s));
}
public static Date Parse(string s, IFormatProvider provider)
{
return new Date(DateTime.Parse(s, provider));
}
public static Date Parse(string s, IFormatProvider provider, DateTimeStyles style)
{
return new Date(DateTime.Parse(s, provider, style));
}
public static Date ParseExact(string s, string format, IFormatProvider provider)
{
return new Date(DateTime.ParseExact(s, ConvertFormat(format), provider));
}
public static Date ParseExact(string s, string format, IFormatProvider provider, DateTimeStyles style)
{
return new Date(DateTime.ParseExact(s, ConvertFormat(format), provider, style));
}
public static Date ParseExact(string s, string[] formats, IFormatProvider provider, DateTimeStyles style)
{
return new Date(DateTime.ParseExact(s, formats, provider, style));
}
public DateTime Add(TimeSpan value)
{
return this + value;
}
public TimeSpan Subtract(Date value)
{
return this - value;
}
public DateTime Subtract(TimeSpan value)
{
return this - value;
}
public string ToLongString()
{
return this._dt.ToLongDateString();
}
public string ToShortString()
{
return this._dt.ToShortDateString();
}
public override string ToString()
{
return this.ToShortString();
}
public string ToString(IFormatProvider provider) => ToString(null, provider);
public string ToString(string format) => ToString(format, CultureInfo.CurrentCulture);
public string ToString(string? format, IFormatProvider? provider)
{
return this._dt.ToString(ConvertFormat(format), provider);
}
[return: NotNullIfNotNull("format")]
private static string? ConvertFormat(string? format)
{
if (format == "O" || format == "o" || format == "s")
{
format = "yyyy-MM-dd";
}
return format;
}
public static bool TryParse(string s, out Date result)
{
DateTime d;
bool success = DateTime.TryParse(s, out d);
result = new Date(d);
return success;
}
public static bool TryParse(string s, IFormatProvider provider, DateTimeStyles style, out Date result)
{
DateTime d;
bool success = DateTime.TryParse(s, provider, style, out d);
result = new Date(d);
return success;
}
public static bool TryParseExact(string s, string format, IFormatProvider provider, DateTimeStyles style, out Date result)
{
if (format == "O" || format == "o" || format == "s")
{
format = "yyyy-MM-dd";
}
DateTime d;
bool success = DateTime.TryParseExact(s, format, provider, style, out d);
result = new Date(d);
return success;
}
public static bool TryParseExact(string s, string[] formats, IFormatProvider provider, DateTimeStyles style, out Date result)
{
DateTime d;
bool success = DateTime.TryParseExact(s, formats, provider, style, out d);
result = new Date(d);
return success;
}
}
public class DateTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(string);
}
public override object? ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
return string.IsNullOrEmpty((string)value) ? (Date?)null : (Date?)Date.ParseExact((string)value, "o", CultureInfo.InvariantCulture);
}
public override object? ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
var date = (Date?)value;
return date == null ? null : date.Value.ToString("o");
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Editor.CSharp.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp;
using Roslyn.Test.Utilities;
using Xunit;
using Microsoft.CodeAnalysis.CSharp;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp
{
public class GenericNamePartiallyWrittenSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests
{
internal override ISignatureHelpProvider CreateSignatureHelpProvider()
{
return new GenericNamePartiallyWrittenSignatureHelpProvider();
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void NestedGenericUnterminated()
{
var markup = @"
class G<T> { };
class C
{
void Foo()
{
G<G<int>$$
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("G<T>", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[WorkItem(544088)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void DeclaringGenericTypeWith1ParameterUnterminated()
{
var markup = @"
class G<T> { };
class C
{
void Foo()
{
[|G<$$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("G<T>", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void CallingGenericAsyncMethod()
{
var markup = @"
using System.Threading.Tasks;
class Program
{
void Main(string[] args)
{
Foo<$$
}
Task<int> Foo<T>()
{
return Foo<T>();
}
}
";
var documentation = $@"
{WorkspacesResources.Usage}
int x = await Foo();";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpFeaturesResources.Awaitable}) Task<int> Program.Foo<T>()", documentation, string.Empty, currentParameterIndex: 0));
// TODO: Enable the script case when we have support for extension methods in scripts
Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: false, sourceCodeKind: Microsoft.CodeAnalysis.SourceCodeKind.Regular);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericMethod_BrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
new C().Foo<$$
}
}
";
var referencedCode = @"
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public void Foo<T>(T x)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericMethod_BrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new C().Foo<$$
}
}
";
var referencedCode = @"
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo<T>(T x)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericMethod_BrowsableAdvanced()
{
var markup = @"
class Program
{
void M()
{
new C().Foo<$$
}
}
";
var referencedCode = @"
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public void Foo<T>(T x)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericMethod_BrowsableMixed()
{
var markup = @"
class Program
{
void M()
{
new C().Foo<$$
}
}
";
var referencedCode = @"
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public void Foo<T>(T x)
{ }
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo<T, U>(T x, U y)
{ }
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void C.Foo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C.Foo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C.Foo<T, U>(T x, U y)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void GenericExtensionMethod()
{
var markup = @"
interface IFoo
{
void Bar<T>();
}
static class FooExtensions
{
public static void Bar<T1, T2>(this IFoo foo) { }
}
class Program
{
static void Main()
{
IFoo f = null;
f.[|Bar<$$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void IFoo.Bar<T>()", currentParameterIndex: 0),
new SignatureHelpTestItem($"({CSharpFeaturesResources.Extension}) void IFoo.Bar<T1, T2>()", currentParameterIndex: 0),
};
// Extension methods are supported in Interactive/Script (yet).
Test(markup, expectedOrderedItems, sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(544088)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InvokingGenericMethodWith1ParameterUnterminated()
{
var markup = @"
class C
{
/// <summary>
/// Method Foo
/// </summary>
/// <typeparam name=""T"">Method type parameter</typeparam>
void Foo<T>() { }
void Bar()
{
[|Foo<$$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<T>()",
"Method Foo", "Method type parameter", currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnTriggerBracket()
{
var markup = @"
class G<S, T> { };
class C
{
void Foo()
{
[|G<$$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnTriggerComma()
{
var markup = @"
class G<S, T> { };
class C
{
void Foo()
{
[|G<int,$$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", string.Empty, string.Empty, currentParameterIndex: 1));
Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[WorkItem(1067933)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InvokedWithNoToken()
{
var markup = @"
// foo<$$";
Test(markup);
}
}
}
| |
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using ModestTree;
using Zenject.Internal;
#pragma warning disable 414
namespace Zenject.Tests.Injection
{
//[TestFixture]
// Conclusion here is that the compiled expressions are basically identical to reflection
// baking during the instantiate (though there are wins during initialization)
// When compiled expressions are not used such as IL2CPP however there is a noticable
// improvement of maybe 15-20% for instantiate
public class TestInstantiateApproaches : ZenjectUnitTestFixture
{
//[Test]
public void TestWithoutReflectionBaking()
{
Log.Trace("Average without baking: {0:0.000}", Run<FooDerivedNoBaking>());
}
//[Test]
public void TestWithReflectionBaking()
{
Log.Trace("Average with baking: {0:0.000}", Run<FooDerivedBaked>());
}
double Run<T>()
{
Container.Bind<Test0>().FromInstance(new Test0());
// Do not include initial reflection costs
Container.Instantiate<T>();
Container.Instantiate<T>();
var measurements = new List<double>();
for (int k = 0; k < 10; k++)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < 10000; i++)
{
Container.Instantiate<T>();
}
stopwatch.Stop();
measurements.Add(stopwatch.Elapsed.TotalSeconds);
}
return measurements.Average();
}
[NoReflectionBaking]
class Test0
{
}
[NoReflectionBaking]
abstract class FooBaseBaked
{
[Inject]
public Test0 BaseFieldPublic = null;
[Inject]
Test0 BaseFieldPrivate = null;
[Inject]
protected Test0 BaseFieldProtected = null;
[Inject]
public Test0 BasePropertyPublic
{
get; set;
}
[Inject]
Test0 BasePropertyPrivate
{
get;
set;
}
[Inject]
protected Test0 BasePropertyProtected
{
get;
set;
}
[Inject]
public void PostInjectBase()
{
DidPostInjectBase = true;
}
public bool DidPostInjectBase
{
get; private set;
}
private static void __zenFieldSetter0(object P_0, object P_1)
{
((FooBaseBaked)P_0).BaseFieldPublic = (Test0)P_1;
}
private static void __zenFieldSetter1(object P_0, object P_1)
{
((FooBaseBaked)P_0).BaseFieldPrivate = (Test0)P_1;
}
private static void __zenFieldSetter2(object P_0, object P_1)
{
((FooBaseBaked)P_0).BaseFieldProtected = (Test0)P_1;
}
private static void __zenPropertySetter0(object P_0, object P_1)
{
((FooBaseBaked)P_0).BasePropertyPublic = (Test0)P_1;
}
private static void __zenPropertySetter1(object P_0, object P_1)
{
((FooBaseBaked)P_0).BasePropertyPrivate = (Test0)P_1;
}
private static void __zenPropertySetter2(object P_0, object P_1)
{
((FooBaseBaked)P_0).BasePropertyProtected = (Test0)P_1;
}
private static void __zenInjectMethod0(object P_0, object[] P_1)
{
((FooBaseBaked)P_0).PostInjectBase();
}
[Preserve]
private static InjectTypeInfo CreateInjectTypeInfo()
{
return new InjectTypeInfo(typeof(FooBaseBaked), new InjectTypeInfo.InjectConstructorInfo(null, new InjectableInfo[0]), new InjectTypeInfo.InjectMethodInfo[1]
{
new InjectTypeInfo.InjectMethodInfo(__zenInjectMethod0, new InjectableInfo[0], "PostInjectBase")
}, new InjectTypeInfo.InjectMemberInfo[6]
{
new InjectTypeInfo.InjectMemberInfo(__zenFieldSetter0, new InjectableInfo(false, null, "BaseFieldPublic", typeof(Test0), null, 0)),
new InjectTypeInfo.InjectMemberInfo(__zenFieldSetter1, new InjectableInfo(false, null, "BaseFieldPrivate", typeof(Test0), null, 0)),
new InjectTypeInfo.InjectMemberInfo(__zenFieldSetter2, new InjectableInfo(false, null, "BaseFieldProtected", typeof(Test0), null, 0)),
new InjectTypeInfo.InjectMemberInfo(__zenPropertySetter0, new InjectableInfo(false, null, "BasePropertyPublic", typeof(Test0), null, 0)),
new InjectTypeInfo.InjectMemberInfo(__zenPropertySetter1, new InjectableInfo(false, null, "BasePropertyPrivate", typeof(Test0), null, 0)),
new InjectTypeInfo.InjectMemberInfo(__zenPropertySetter2, new InjectableInfo(false, null, "BasePropertyProtected", typeof(Test0), null, 0))
});
}
}
[NoReflectionBaking]
class FooDerivedBaked : FooBaseBaked
{
public Test0 ConstructorParam = null;
// Instance
public FooDerivedBaked(Test0 param)
{
ConstructorParam = param;
}
[Inject]
public void PostInject()
{
}
[Inject]
public Test0 DerivedFieldPublic = null;
[Inject]
Test0 DerivedFieldPrivate = null;
[Inject]
protected Test0 DerivedFieldProtected = null;
[Inject]
public Test0 DerivedPropertyPublic
{
get; set;
}
[Inject]
Test0 DerivedPropertyPrivate
{
get;
set;
}
[Inject]
protected Test0 DerivedPropertyProtected
{
get;
set;
}
private static object __zenCreate(object[] P_0)
{
return new FooDerivedBaked((Test0)P_0[0]);
}
private static void __zenFieldSetter0(object P_0, object P_1)
{
((FooDerivedBaked)P_0).DerivedFieldPublic = (Test0)P_1;
}
private static void __zenFieldSetter1(object P_0, object P_1)
{
((FooDerivedBaked)P_0).DerivedFieldPrivate = (Test0)P_1;
}
private static void __zenFieldSetter2(object P_0, object P_1)
{
((FooDerivedBaked)P_0).DerivedFieldProtected = (Test0)P_1;
}
private static void __zenPropertySetter0(object P_0, object P_1)
{
((FooDerivedBaked)P_0).DerivedPropertyPublic = (Test0)P_1;
}
private static void __zenPropertySetter1(object P_0, object P_1)
{
((FooDerivedBaked)P_0).DerivedPropertyPrivate = (Test0)P_1;
}
private static void __zenPropertySetter2(object P_0, object P_1)
{
((FooDerivedBaked)P_0).DerivedPropertyProtected = (Test0)P_1;
}
private static void __zenInjectMethod0(object P_0, object[] P_1)
{
((FooDerivedBaked)P_0).PostInject();
}
[Preserve]
private static InjectTypeInfo CreateInjectTypeInfo()
{
return new InjectTypeInfo(typeof(FooDerivedBaked), new InjectTypeInfo.InjectConstructorInfo(__zenCreate, new InjectableInfo[1]
{
new InjectableInfo(false, null, "param", typeof(Test0), null, 0)
}), new InjectTypeInfo.InjectMethodInfo[1]
{
new InjectTypeInfo.InjectMethodInfo(__zenInjectMethod0, new InjectableInfo[0], "PostInject")
}, new InjectTypeInfo.InjectMemberInfo[6]
{
new InjectTypeInfo.InjectMemberInfo(__zenFieldSetter0, new InjectableInfo(false, null, "DerivedFieldPublic", typeof(Test0), null, 0)),
new InjectTypeInfo.InjectMemberInfo(__zenFieldSetter1, new InjectableInfo(false, null, "DerivedFieldPrivate", typeof(Test0), null, 0)),
new InjectTypeInfo.InjectMemberInfo(__zenFieldSetter2, new InjectableInfo(false, null, "DerivedFieldProtected", typeof(Test0), null, 0)),
new InjectTypeInfo.InjectMemberInfo(__zenPropertySetter0, new InjectableInfo(false, null, "DerivedPropertyPublic", typeof(Test0), null, 0)),
new InjectTypeInfo.InjectMemberInfo(__zenPropertySetter1, new InjectableInfo(false, null, "DerivedPropertyPrivate", typeof(Test0), null, 0)),
new InjectTypeInfo.InjectMemberInfo(__zenPropertySetter2, new InjectableInfo(false, null, "DerivedPropertyProtected", typeof(Test0), null, 0))
});
}
}
[NoReflectionBaking]
abstract class FooBaseNoBaking
{
[Inject]
public Test0 BaseFieldPublic = null;
[Inject]
Test0 BaseFieldPrivate = null;
[Inject]
protected Test0 BaseFieldProtected = null;
[Inject]
public Test0 BasePropertyPublic
{
get; set;
}
[Inject]
Test0 BasePropertyPrivate
{
get;
set;
}
[Inject]
protected Test0 BasePropertyProtected
{
get;
set;
}
[Inject]
public void PostInjectBase()
{
DidPostInjectBase = true;
}
public bool DidPostInjectBase
{
get; private set;
}
}
[NoReflectionBaking]
class FooDerivedNoBaking : FooBaseNoBaking
{
public Test0 ConstructorParam = null;
// Instance
public FooDerivedNoBaking(Test0 param)
{
ConstructorParam = param;
}
[Inject]
public void PostInject()
{
}
[Inject]
public Test0 DerivedFieldPublic = null;
[Inject]
Test0 DerivedFieldPrivate = null;
[Inject]
protected Test0 DerivedFieldProtected = null;
[Inject]
public Test0 DerivedPropertyPublic
{
get; set;
}
[Inject]
Test0 DerivedPropertyPrivate
{
get;
set;
}
[Inject]
protected Test0 DerivedPropertyProtected
{
get;
set;
}
}
}
}
| |
using System.Runtime.CompilerServices;
//[Khronos GLES1.1]http://www.khronos.org/registry/gles/api/1.1/gl.h
//[Khronos GLES1.0]http://www.khronos.org/registry/gles/api/1.0/gl.h
namespace System.Interop.OpenGL
{
#if CODE_ANALYSIS
[IgnoreNamespace, Imported]
#endif
public abstract class GLES11
{
/* ClearBufferMask */
public const uint DEPTH_BUFFER_BIT = 0x00000100;
public const uint STENCIL_BUFFER_BIT = 0x00000400;
public const uint COLOR_BUFFER_BIT = 0x00004000;
/* BeginMode */
public const uint POINTS = 0x0000;
public const uint LINES = 0x0001;
public const uint LINE_LOOP = 0x0002;
public const uint LINE_STRIP = 0x0003;
public const uint TRIANGLES = 0x0004;
public const uint TRIANGLE_STRIP = 0x0005;
public const uint TRIANGLE_FAN = 0x0006;
/* AlphaFunction */
public const uint NEVER = 0x0200;
public const uint LESS = 0x0201;
public const uint EQUAL = 0x0202;
public const uint LEQUAL = 0x0203;
public const uint GREATER = 0x0204;
public const uint NOTEQUAL = 0x0205;
public const uint GEQUAL = 0x0206;
public const uint ALWAYS = 0x0207;
/* BlendingFactorDest */
public const uint ZERO = 0;
public const uint ONE = 1;
public const uint SRC_COLOR = 0x0300;
public const uint ONE_MINUS_SRC_COLOR = 0x0301;
public const uint SRC_ALPHA = 0x0302;
public const uint ONE_MINUS_SRC_ALPHA = 0x0303;
public const uint DST_ALPHA = 0x0304;
public const uint ONE_MINUS_DST_ALPHA = 0x0305;
/* BlendingFactorSrc */
/* ZERO */
/* ONE */
public const uint DST_COLOR = 0x0306;
public const uint ONE_MINUS_DST_COLOR = 0x0307;
public const uint SRC_ALPHA_SATURATE = 0x0308;
/* SRC_ALPHA */
/* ONE_MINUS_SRC_ALPHA */
/* DST_ALPHA */
/* ONE_MINUS_DST_ALPHA */
/* ClipPlaneName */
public const uint CLIP_PLANE0 = 0x3000;
public const uint CLIP_PLANE1 = 0x3001;
public const uint CLIP_PLANE2 = 0x3002;
public const uint CLIP_PLANE3 = 0x3003;
public const uint CLIP_PLANE4 = 0x3004;
public const uint CLIP_PLANE5 = 0x3005;
/* ColorMaterialFace */
/* FRONT_AND_BACK */
/* ColorMaterialParameter */
/* AMBIENT_AND_DIFFUSE */
/* ColorPointerType */
/* UNSIGNED_BYTE */
/* FLOAT */
/* FIXED */
/* CullFaceMode */
public const uint FRONT = 0x0404;
public const uint BACK = 0x0405;
public const uint FRONT_AND_BACK = 0x0408;
/* DepthFunction */
/* NEVER */
/* LESS */
/* EQUAL */
/* LEQUAL */
/* GREATER */
/* NOTEQUAL */
/* GEQUAL */
/* ALWAYS */
/* EnableCap */
public const uint FOG = 0x0B60;
public const uint LIGHTING = 0x0B50;
public const uint TEXTURE_2D = 0x0DE1;
public const uint CULL_FACE = 0x0B44;
public const uint ALPHA_TEST = 0x0BC0;
public const uint BLEND = 0x0BE2;
public const uint COLOR_LOGIC_OP = 0x0BF2;
public const uint DITHER = 0x0BD0;
public const uint STENCIL_TEST = 0x0B90;
public const uint DEPTH_TEST = 0x0B71;
/* LIGHT0 */
/* LIGHT1 */
/* LIGHT2 */
/* LIGHT3 */
/* LIGHT4 */
/* LIGHT5 */
/* LIGHT6 */
/* LIGHT7 */
public const uint POINT_SMOOTH = 0x0B10;
public const uint LINE_SMOOTH = 0x0B20;
public const uint CISSOR_TEST = 0x0C11;
public const uint COLOR_MATERIAL = 0x0B57;
public const uint NORMALIZE = 0x0BA1;
public const uint RESCALE_NORMAL = 0x803A;
/* POLYGON_OFFSET_FILL */
public const uint VERTEX_ARRAY = 0x8074;
public const uint NORMAL_ARRAY = 0x8075;
public const uint COLOR_ARRAY = 0x8076;
public const uint TEXTURE_COORD_ARRAY = 0x8078;
public const uint MULTISAMPLE = 0x809D;
public const uint SAMPLE_ALPHA_TO_COVERAGE = 0x809E;
public const uint SAMPLE_ALPHA_TO_ONE = 0x809F;
public const uint SAMPLE_COVERAGE = 0x80A0;
/* ErrorCode */
public const uint NO_ERROR = 0;
public const uint INVALID_ENUM = 0x0500;
public const uint INVALID_VALUE = 0x0501;
public const uint INVALID_OPERATION = 0x0502;
public const uint OUT_OF_MEMORY = 0x0505;
/* FogMode */
/* LINEAR */
public const uint EXP = 0x0800;
public const uint EXP2 = 0x0801;
/* FogParameter */
public const uint FOG_DENSITY = 0x0B62;
public const uint FOG_START = 0x0B63;
public const uint FOG_END = 0x0B64;
public const uint FOG_MODE = 0x0B65;
public const uint FOG_COLOR = 0x0B66;
/* FrontFaceDirection */
public const uint CW = 0x0900;
public const uint CCW = 0x0901;
/* GetPName */
public const uint CURRENT_COLOR = 0x0B00;
public const uint CURRENT_NORMAL = 0x0B02;
public const uint CURRENT_TEXTURE_COORDS = 0x0B03;
public const uint POINT_SIZE = 0x0B11;
public const uint POINT_SIZE_MIN = 0x8126;
public const uint POINT_SIZE_MAX = 0x8127;
public const uint POINT_FADE_THRESHOLD_SIZE = 0x8128;
public const uint POINT_DISTANCE_ATTENUATION = 0x8129;
public const uint SMOOTH_POINT_SIZE_RANGE = 0x0B12;
public const uint LINE_WIDTH = 0x0B21;
public const uint SMOOTH_LINE_WIDTH_RANGE = 0x0B22;
public const uint ALIASED_POINT_SIZE_RANGE = 0x846D;
public const uint ALIASED_LINE_WIDTH_RANGE = 0x846E;
public const uint CULL_FACE_MODE = 0x0B45;
public const uint FRONT_FACE = 0x0B46;
public const uint SHADE_MODEL = 0x0B54;
public const uint DEPTH_RANGE = 0x0B70;
public const uint DEPTH_WRITEMASK = 0x0B72;
public const uint DEPTH_CLEAR_VALUE = 0x0B73;
public const uint DEPTH_FUNC = 0x0B74;
public const uint STENCIL_CLEAR_VALUE = 0x0B91;
public const uint STENCIL_FUNC = 0x0B92;
public const uint STENCIL_VALUE_MASK = 0x0B93;
public const uint STENCIL_FAIL = 0x0B94;
public const uint STENCIL_PASS_DEPTH_FAIL = 0x0B95;
public const uint STENCIL_PASS_DEPTH_PASS = 0x0B96;
public const uint STENCIL_REF = 0x0B97;
public const uint STENCIL_WRITEMASK = 0x0B98;
public const uint MATRIX_MODE = 0x0BA0;
public const uint VIEWPORT = 0x0BA2;
public const uint MODELVIEW_STACK_DEPTH = 0x0BA3;
public const uint PROJECTION_STACK_DEPTH = 0x0BA4;
public const uint TEXTURE_STACK_DEPTH = 0x0BA5;
public const uint MODELVIEW_MATRIX = 0x0BA6;
public const uint PROJECTION_MATRIX = 0x0BA7;
public const uint TEXTURE_MATRIX = 0x0BA8;
public const uint ALPHA_TEST_FUNC = 0x0BC1;
public const uint ALPHA_TEST_REF = 0x0BC2;
public const uint BLEND_DST = 0x0BE0;
public const uint BLEND_SRC = 0x0BE1;
public const uint LOGIC_OP_MODE = 0x0BF0;
public const uint SCISSOR_BOX = 0x0C10;
public const uint SCISSOR_TEST = 0x0C11;
public const uint COLOR_CLEAR_VALUE = 0x0C22;
public const uint COLOR_WRITEMASK = 0x0C23;
public const uint UNPACK_ALIGNMENT = 0x0CF5;
public const uint PACK_ALIGNMENT = 0x0D05;
public const uint MAX_LIGHTS = 0x0D31;
public const uint MAX_CLIP_PLANES = 0x0D32;
public const uint MAX_TEXTURE_SIZE = 0x0D33;
public const uint MAX_MODELVIEW_STACK_DEPTH = 0x0D36;
public const uint MAX_PROJECTION_STACK_DEPTH = 0x0D38;
public const uint MAX_TEXTURE_STACK_DEPTH = 0x0D39;
public const uint MAX_VIEWPORT_DIMS = 0x0D3A;
public const uint MAX_TEXTURE_UNITS = 0x84E2;
public const uint SUBPIXEL_BITS = 0x0D50;
public const uint RED_BITS = 0x0D52;
public const uint GREEN_BITS = 0x0D53;
public const uint BLUE_BITS = 0x0D54;
public const uint ALPHA_BITS = 0x0D55;
public const uint DEPTH_BITS = 0x0D56;
public const uint STENCIL_BITS = 0x0D57;
public const uint POLYGON_OFFSET_UNITS = 0x2A00;
public const uint POLYGON_OFFSET_FILL = 0x8037;
public const uint POLYGON_OFFSET_FACTOR = 0x8038;
public const uint TEXTURE_BINDING_2D = 0x8069;
public const uint VERTEX_ARRAY_SIZE = 0x807A;
public const uint VERTEX_ARRAY_TYPE = 0x807B;
public const uint VERTEX_ARRAY_STRIDE = 0x807C;
public const uint NORMAL_ARRAY_TYPE = 0x807E;
public const uint NORMAL_ARRAY_STRIDE = 0x807F;
public const uint COLOR_ARRAY_SIZE = 0x8081;
public const uint COLOR_ARRAY_TYPE = 0x8082;
public const uint COLOR_ARRAY_STRIDE = 0x8083;
public const uint TEXTURE_COORD_ARRAY_SIZE = 0x8088;
public const uint TEXTURE_COORD_ARRAY_TYPE = 0x8089;
public const uint TEXTURE_COORD_ARRAY_STRIDE = 0x808A;
public const uint VERTEX_ARRAY_POINTER = 0x808E;
public const uint NORMAL_ARRAY_POINTER = 0x808F;
public const uint COLOR_ARRAY_POINTER = 0x8090;
public const uint TEXTURE_COORD_ARRAY_POINTER = 0x8092;
public const uint SAMPLE_BUFFERS = 0x80A8;
public const uint SAMPLES = 0x80A9;
public const uint SAMPLE_COVERAGE_VALUE = 0x80AA;
public const uint SAMPLE_COVERAGE_INVERT = 0x80AB;
/* GetTextureParameter */
/* TEXTURE_MAG_FILTER */
/* TEXTURE_MIN_FILTER */
/* TEXTURE_WRAP_S */
/* TEXTURE_WRAP_T */
public const uint NUM_COMPRESSED_TEXTURE_FORMATS = 0x86A2;
public const uint COMPRESSED_TEXTURE_FORMATS = 0x86A3;
/* HintMode */
public const uint DONT_CARE = 0x1100;
public const uint FASTEST = 0x1101;
public const uint NICEST = 0x1102;
/* HintTarget */
public const uint PERSPECTIVE_CORRECTION_HINT = 0x0C50;
public const uint POINT_SMOOTH_HINT = 0x0C51;
public const uint LINE_SMOOTH_HINT = 0x0C52;
public const uint POLYGON_SMOOTH_HINT = 0x0C53;
public const uint FOG_HINT = 0x0C54;
/* LightModelParameter */
public const uint LIGHT_MODEL_AMBIENT = 0x0B53;
public const uint LIGHT_MODEL_TWO_SIDE = 0x0B52;
/* LightParameter */
public const uint AMBIENT = 0x1200;
public const uint DIFFUSE = 0x1201;
public const uint SPECULAR = 0x1202;
public const uint POSITION = 0x1203;
public const uint SPOT_DIRECTION = 0x1204;
public const uint SPOT_EXPONENT = 0x1205;
public const uint SPOT_CUTOFF = 0x1206;
public const uint CONSTANT_ATTENUATION = 0x1207;
public const uint LINEAR_ATTENUATION = 0x1208;
public const uint QUADRATIC_ATTENUATION = 0x1209;
/* DataType */
public const uint BYTE = 0x1400;
public const uint UNSIGNED_BYTE = 0x1401;
public const uint SHORT = 0x1402;
public const uint UNSIGNED_SHORT = 0x1403;
public const uint INT = 0x1404;
public const uint UNSIGNED_INT = 0x1405;
public const uint FLOAT = 0x1406;
public const uint FIXED = 0x140C;
/* LogicOp */
public const uint CLEAR = 0x1500;
public const uint AND = 0x1501;
public const uint AND_REVERSE = 0x1502;
public const uint COPY = 0x1503;
public const uint AND_INVERTED = 0x1504;
public const uint NOOP = 0x1505;
public const uint XOR = 0x1506;
public const uint OR = 0x1507;
public const uint NOR = 0x1508;
public const uint EQUIV = 0x1509;
public const uint INVERT = 0x150A;
public const uint OR_REVERSE = 0x150B;
public const uint COPY_INVERTED = 0x150C;
public const uint OR_INVERTED = 0x150D;
public const uint NAND = 0x150E;
public const uint SET = 0x150F;
/* MaterialFace */
/* FRONT_AND_BACK */
/* MaterialParameter */
public const uint EMISSION = 0x1600;
public const uint SHININESS = 0x1601;
public const uint AMBIENT_AND_DIFFUSE = 0x1602;
/* AMBIENT */
/* DIFFUSE */
/* SPECULAR */
/* MatrixMode */
public const uint MODELVIEW = 0x1700;
public const uint PROJECTION = 0x1701;
public const uint TEXTURE = 0x1702;
/* NormalPointerType */
/* BYTE */
/* SHORT */
/* FLOAT */
/* FIXED */
/* PixelFormat */
public const uint DEPTH_COMPONENT = 0x1902;
public const uint ALPHA = 0x1906;
public const uint RGB = 0x1907;
public const uint RGBA = 0x1908;
public const uint LUMINANCE = 0x1909;
public const uint LUMINANCE_ALPHA = 0x190A;
/* PixelType */
/* UNSIGNED_BYTE */
public const uint UNSIGNED_SHORT_4_4_4_4 = 0x8033;
public const uint UNSIGNED_SHORT_5_5_5_1 = 0x8034;
public const uint UNSIGNED_SHORT_5_6_5 = 0x8363;
/* ShadingModel */
public const uint FLAT = 0x1D00;
public const uint SMOOTH = 0x1D01;
/* StencilFunction */
/* NEVER */
/* LESS */
/* EQUAL */
/* LEQUAL */
/* GREATER */
/* NOTEQUAL */
/* GEQUAL */
/* ALWAYS */
/* StencilOp */
/* ZERO */
public const uint KEEP = 0x1E00;
public const uint REPLACE = 0x1E01;
public const uint INCR = 0x1E02;
public const uint DECR = 0x1E03;
/* INVERT */
/* StringName */
public const uint VENDOR = 0x1F00;
public const uint RENDERER = 0x1F01;
public const uint VERSION = 0x1F02;
public const uint EXTENSIONS = 0x1F03;
/* TexCoordPointerType */
/* SHORT */
/* FLOAT */
/* FIXED */
/* BYTE */
/* TextureEnvMode */
public const uint MODULATE = 0x2100;
public const uint DECAL = 0x2101;
/* BLEND */
public const uint ADD = 0x0104;
/* REPLACE */
/* TextureEnvParameter */
public const uint TEXTURE_ENV_MODE = 0x2200;
public const uint TEXTURE_ENV_COLOR = 0x2201;
/* TextureEnvTarget */
public const uint TEXTURE_ENV = 0x2300;
/* TextureMagFilter */
public const uint NEAREST = 0x2600;
public const uint LINEAR = 0x2601;
/* TextureMinFilter */
/* NEAREST */
/* LINEAR */
public const uint NEAREST_MIPMAP_NEAREST = 0x2700;
public const uint LINEAR_MIPMAP_NEAREST = 0x2701;
public const uint NEAREST_MIPMAP_LINEAR = 0x2702;
public const uint LINEAR_MIPMAP_LINEAR = 0x2703;
/* TextureParameterName */
public const uint TEXTURE_MAG_FILTER = 0x2800;
public const uint TEXTURE_MIN_FILTER = 0x2801;
public const uint TEXTURE_WRAP_S = 0x2802;
public const uint TEXTURE_WRAP_T = 0x2803;
public const uint GENERATE_MIPMAP = 0x8191;
/* TextureTarget */
/* TEXTURE_2D */
/* TextureUnit */
public const uint TEXTURE0 = 0x84C0;
public const uint TEXTURE1 = 0x84C1;
public const uint TEXTURE2 = 0x84C2;
public const uint TEXTURE3 = 0x84C3;
public const uint TEXTURE4 = 0x84C4;
public const uint TEXTURE5 = 0x84C5;
public const uint TEXTURE6 = 0x84C6;
public const uint TEXTURE7 = 0x84C7;
public const uint TEXTURE8 = 0x84C8;
public const uint TEXTURE9 = 0x84C9;
public const uint TEXTURE10 = 0x84CA;
public const uint TEXTURE11 = 0x84CB;
public const uint TEXTURE12 = 0x84CC;
public const uint TEXTURE13 = 0x84CD;
public const uint TEXTURE14 = 0x84CE;
public const uint TEXTURE15 = 0x84CF;
public const uint TEXTURE16 = 0x84D0;
public const uint TEXTURE17 = 0x84D1;
public const uint TEXTURE18 = 0x84D2;
public const uint TEXTURE19 = 0x84D3;
public const uint TEXTURE20 = 0x84D4;
public const uint TEXTURE21 = 0x84D5;
public const uint TEXTURE22 = 0x84D6;
public const uint TEXTURE23 = 0x84D7;
public const uint TEXTURE24 = 0x84D8;
public const uint TEXTURE25 = 0x84D9;
public const uint TEXTURE26 = 0x84DA;
public const uint TEXTURE27 = 0x84DB;
public const uint TEXTURE28 = 0x84DC;
public const uint TEXTURE29 = 0x84DD;
public const uint TEXTURE30 = 0x84DE;
public const uint TEXTURE31 = 0x84DF;
public const uint ACTIVE_TEXTURE = 0x84E0;
public const uint CLIENT_ACTIVE_TEXTURE = 0x84E1;
/* TextureWrapMode */
public const uint REPEAT = 0x2901;
public const uint CLAMP_TO_EDGE = 0x812F;
/* PixelInternalFormat */
public const uint PALETTE4_RGB8_OES = 0x8B90;
public const uint PALETTE4_RGBA8_OES = 0x8B91;
public const uint PALETTE4_R5_G6_B5_OES = 0x8B92;
public const uint PALETTE4_RGBA4_OES = 0x8B93;
public const uint PALETTE4_RGB5_A1_OES = 0x8B94;
public const uint PALETTE8_RGB8_OES = 0x8B95;
public const uint PALETTE8_RGBA8_OES = 0x8B96;
public const uint PALETTE8_R5_G6_B5_OES = 0x8B97;
public const uint PALETTE8_RGBA4_OES = 0x8B98;
public const uint PALETTE8_RGB5_A1_OES = 0x8B99;
/* VertexPointerType */
/* SHORT */
/* FLOAT */
/* FIXED */
/* BYTE */
/* LightName */
public const uint LIGHT0 = 0x4000;
public const uint LIGHT1 = 0x4001;
public const uint LIGHT2 = 0x4002;
public const uint LIGHT3 = 0x4003;
public const uint LIGHT4 = 0x4004;
public const uint LIGHT5 = 0x4005;
public const uint LIGHT6 = 0x4006;
public const uint LIGHT7 = 0x4007;
/* Buffer Objects */
public const uint ARRAY_BUFFER = 0x8892;
public const uint ELEMENT_ARRAY_BUFFER = 0x8893;
public const uint ARRAY_BUFFER_BINDING = 0x8894;
public const uint ELEMENT_ARRAY_BUFFER_BINDING = 0x8895;
public const uint VERTEX_ARRAY_BUFFER_BINDING = 0x8896;
public const uint NORMAL_ARRAY_BUFFER_BINDING = 0x8897;
public const uint COLOR_ARRAY_BUFFER_BINDING = 0x8898;
public const uint TEXTURE_COORD_ARRAY_BUFFER_BINDING = 0x889A;
public const uint STATIC_DRAW = 0x88E4;
public const uint DYNAMIC_DRAW = 0x88E8;
public const uint BUFFER_SIZE = 0x8764;
public const uint BUFFER_USAGE = 0x8765;
/* Texture combine + dot3 */
public const uint SUBTRACT = 0x84E7;
public const uint COMBINE = 0x8570;
public const uint COMBINE_RGB = 0x8571;
public const uint COMBINE_ALPHA = 0x8572;
public const uint RGB_SCALE = 0x8573;
public const uint ADD_SIGNED = 0x8574;
public const uint INTERPOLATE = 0x8575;
public const uint CONSTANT = 0x8576;
public const uint PRIMARY_COLOR = 0x8577;
public const uint PREVIOUS = 0x8578;
public const uint OPERAND0_RGB = 0x8590;
public const uint OPERAND1_RGB = 0x8591;
public const uint OPERAND2_RGB = 0x8592;
public const uint OPERAND0_ALPHA = 0x8598;
public const uint OPERAND1_ALPHA = 0x8599;
public const uint OPERAND2_ALPHA = 0x859A;
public const uint ALPHA_SCALE = 0x0D1C;
public const uint SRC0_RGB = 0x8580;
public const uint SRC1_RGB = 0x8581;
public const uint SRC2_RGB = 0x8582;
public const uint SRC0_ALPHA = 0x8588;
public const uint SRC1_ALPHA = 0x8589;
public const uint SRC2_ALPHA = 0x858A;
public const uint DOT3_RGB = 0x86AE;
public const uint DOT3_RGBA = 0x86AF;
}
}
| |
/*
*
* P1 : AWSD + T (A) + Space (B)
* P2 : Arrows + 2 (A) + 0 (B)
* P3 : Manette ou 5 (A)
* P4 : Manette ou 8 (A)
* */
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Playermovement : MonoBehaviour
{
public float movementSpeed = 5.0f;
public string player = "1";
public bool isFalling = true;//false;
float fallSpeed = 3f;
public Vector3 fallingIn;
float movingTowardsTrapSpeed = 1f;
protected Animator animator;
private List<GameObject> actionListeners;
private Vector3 translation;
void Start ()
{
animator = GetComponent<Animator> ();
animator.SetInteger ("direction", 0);
animator.speed = 0;
translation = new Vector3 (0, 0, 0);
actionListeners = new List<GameObject> ();
}
void Update ()
{
animator.SetBool ("isFalling", isFalling);
if (isFalling && (transform.localScale.x > 0f)) {
Debug.Log ("And he falls");
transform.localScale -= new Vector3 (fallSpeed * Time.deltaTime, fallSpeed * Time.deltaTime, 0f);
transform.position = Vector3.MoveTowards (transform.position, fallingIn, movingTowardsTrapSpeed * Time.deltaTime);
return;
}
//rigidbody.velocity = new Vector3(0, rigidbody.velocity.y, 0); //Set X and Z velocity to 0
translation.Set (0, 0, 0);
if (int.Parse (player) > 2) {
// 3 - Retrieve axis information
float inputX = Input.GetAxis ("HorizontalPlayer_" + player);
float inputY = Input.GetAxis ("VerticalPlayer_" + player);
bool isRunning = false;
float delta = 0.5f;
animator.speed = 1;
if (inputY > delta) {//haut
animator.SetInteger ("direction", 1);
isRunning = true;
transform.Translate (0, 1 * Time.deltaTime * movementSpeed, 0);
} else if (inputY < -delta) {//bas
animator.SetInteger ("direction", 2);
isRunning = true;
transform.Translate (0, -1 * Time.deltaTime * movementSpeed, 0);
} else if (inputX < -delta) {//gauche
animator.SetInteger ("direction", 3);
isRunning = true;
transform.Translate (-1 * Time.deltaTime * movementSpeed, 0, 0);
} else if (inputX > delta) {//droite
animator.SetInteger ("direction", 4);
isRunning = true;
transform.Translate (1 * Time.deltaTime * movementSpeed, 0, 0);
}
animator.SetBool ("isRunning", isRunning);
if(Input.GetButtonDown("ActionPlayer_" + player)){
this.throwActionA();
}
if(Input.GetButtonDown("ActionPlayer2_" + player)){
this.throwActionB();
}
/*if (Input.GetButtonDown ("suicidePlayer_" + player)) {
Debug.Log ("suicide of " + player);
}
if (Input.GetButtonDown ("actionPlayer_" + player)) {
Debug.Log ("action of " + player);
}
if (Input.GetButtonDown ("pausePlayer_" + player)) {
Debug.Log ("pause of " + player);
}*/
} else {
if (int.Parse (player) == 1) {
bool isRunning = false;
animator.speed = 1;
if (Input.GetKey (KeyCode.W)) {
animator.SetInteger ("direction", 1);
isRunning = true;
}
if (Input.GetKey (KeyCode.D)) {
isRunning = true;
animator.SetInteger ("direction", 4);
}
if (Input.GetKey (KeyCode.S)) {
isRunning = true;
animator.SetInteger ("direction", 2);
}
if (Input.GetKey (KeyCode.A)) {
isRunning = true;
animator.SetInteger ("direction", 3);
}
animator.SetBool ("isRunning", isRunning);
if (isRunning) {
switch (animator.GetInteger ("direction")) {
case 1:
translation.Set (0, 1 * Time.deltaTime * movementSpeed, 0);
break;
case 2:
translation.Set (0, -1 * Time.deltaTime * movementSpeed, 0);
break;
case 3:
translation.Set (-1 * Time.deltaTime * movementSpeed, 0, 0);
break;
case 4:
translation.Set (1 * Time.deltaTime * movementSpeed, 0, 0);
break;
default:
break;
}
}
if (Input.GetKeyDown (KeyCode.R)) {
Debug.Log ("suicide of " + player);
}
if (Input.GetKeyDown (KeyCode.T)) {
this.throwActionA();
}
if (Input.GetKeyDown (KeyCode.Space)) {
this.throwActionB();
}
if (Input.GetKeyDown (KeyCode.Y)) {
Debug.Log ("pause of " + player);
}
//Ctrl P2
} else if (int.Parse (player) == 2) {
bool isRunning = false;
animator.speed = 1;
if (Input.GetKey (KeyCode.UpArrow)) {
animator.SetInteger ("direction", 1);
isRunning = true;
}
if (Input.GetKey (KeyCode.RightArrow)) {
isRunning = true;
animator.SetInteger ("direction", 4);
}
if (Input.GetKey (KeyCode.DownArrow)) {
isRunning = true;
animator.SetInteger ("direction", 2);
}
if (Input.GetKey (KeyCode.LeftArrow)) {
isRunning = true;
animator.SetInteger ("direction", 3);
}
animator.SetBool ("isRunning", isRunning);
if (isRunning) {
switch (animator.GetInteger ("direction")) {
case 1:
translation.Set (0, 1 * Time.deltaTime * movementSpeed, 0);
break;
case 2:
translation.Set (0, -1 * Time.deltaTime * movementSpeed, 0);
break;
case 3:
translation.Set (-1 * Time.deltaTime * movementSpeed, 0, 0);
break;
case 4:
translation.Set (1 * Time.deltaTime * movementSpeed, 0, 0);
break;
default:
break;
}
}
if (Input.GetKeyDown ("[1]")) {
Debug.Log ("suicide of " + player);
}
if (Input.GetKeyDown ("[2]")) {
this.throwActionA();
}
if (Input.GetKeyDown ("[0]")) {
this.throwActionB();
}
if (Input.GetKeyDown ("[3]")) {
Debug.Log ("pause of " + player);
}
}
}
//Tricks pour les 2 autres joueurs
if(int.Parse(player) == 3 && Input.GetKeyDown("[5]"))
throwActionA();
else if(int.Parse (player) == 4 && Input.GetKeyDown("[8]")) {
throwActionA();
}
}
void FixedUpdate ()
{
if (!isFalling)
transform.Translate (translation);
}
public void setFalling (bool isFalling, Vector3 position)
{
bool isFlying = gameObject.GetComponent<ThrowPlayer> ().isFlying;
if (isFlying)
return;
this.isFalling = isFalling;
this.fallingIn = position;
}
public void addActionListener (GameObject listener)
{
actionListeners.Add (listener);
}
public void removeActionListener (GameObject listener)
{
actionListeners.Remove (listener);
}
public void throwActionA ()
{
List<GameObject> test = GetComponent<ThrowPlayer> ().PusherList;
for (int i=0; i<test.Count; i++) {
test [i].GetComponent<ThrowPlayer> ().IncCount ();
}
Debug.Log ("Action A of " + player);
}
public void throwActionB ()
{
foreach (GameObject listener in actionListeners)
{
listener.SendMessage("ActionPressed", int.Parse(player ));
}
Debug.Log ("Action B of " + player);
}
}
| |
using System;
using System.Collections.Generic;
using LibGit2Sharp.Handlers;
namespace LibGit2Sharp
{
/// <summary>
/// A Repository is the primary interface into a git repository
/// </summary>
public interface IRepository : IDisposable
{
/// <summary>
/// Shortcut to return the branch pointed to by HEAD
/// </summary>
Branch Head { get; }
/// <summary>
/// Provides access to the configuration settings for this repository.
/// </summary>
Configuration Config { get; }
/// <summary>
/// Gets the index.
/// </summary>
Index Index { get; }
/// <summary>
/// Lookup and enumerate references in the repository.
/// </summary>
ReferenceCollection Refs { get; }
/// <summary>
/// Lookup and enumerate commits in the repository.
/// Iterating this collection directly starts walking from the HEAD.
/// </summary>
IQueryableCommitLog Commits { get; }
/// <summary>
/// Lookup and enumerate branches in the repository.
/// </summary>
BranchCollection Branches { get; }
/// <summary>
/// Lookup and enumerate tags in the repository.
/// </summary>
TagCollection Tags { get; }
/// <summary>
/// Provides high level information about this repository.
/// </summary>
RepositoryInformation Info { get; }
/// <summary>
/// Provides access to diffing functionalities to 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.
/// </summary>
Diff Diff {get;}
/// <summary>
/// Gets the database.
/// </summary>
ObjectDatabase ObjectDatabase { get; }
/// <summary>
/// Lookup notes in the repository.
/// </summary>
NoteCollection Notes { get; }
/// <summary>
/// Submodules in the repository.
/// </summary>
SubmoduleCollection Submodules { get; }
/// <summary>
/// Checkout the commit pointed at by the tip of the specified <see cref="Branch"/>.
/// <para>
/// If this commit is the current tip of the branch as it exists in the repository, the HEAD
/// will point to this branch. Otherwise, the HEAD will be detached, pointing at the commit sha.
/// </para>
/// </summary>
/// <param name="branch">The <see cref="Branch"/> to check out.</param>
/// <param name="options"><see cref="CheckoutOptions"/> controlling checkout behavior.</param>
/// <param name="signature">Identity for use when updating the reflog.</param>
/// <returns>The <see cref="Branch"/> that was checked out.</returns>
Branch Checkout(Branch branch, CheckoutOptions options, Signature signature);
/// <summary>
/// Checkout the specified branch, reference or SHA.
/// <para>
/// If the committishOrBranchSpec parameter resolves to a branch name, then the checked out HEAD will
/// will point to the branch. Otherwise, the HEAD will be detached, pointing at the commit sha.
/// </para>
/// </summary>
/// <param name="committishOrBranchSpec">A revparse spec for the commit or branch to checkout.</param>
/// <param name="options"><see cref="CheckoutOptions"/> controlling checkout behavior.</param>
/// <param name="signature">Identity for use when updating the reflog.</param>
/// <returns>The <see cref="Branch"/> that was checked out.</returns>
Branch Checkout(string committishOrBranchSpec, CheckoutOptions options, Signature signature);
/// <summary>
/// Checkout the specified <see cref="LibGit2Sharp.Commit"/>.
/// <para>
/// Will detach the HEAD and make it point to this commit sha.
/// </para>
/// </summary>
/// <param name="commit">The <see cref="LibGit2Sharp.Commit"/> to check out.</param>
/// <param name="options"><see cref="CheckoutOptions"/> controlling checkout behavior.</param>
/// <param name="signature">Identity for use when updating the reflog.</param>
/// <returns>The <see cref="Branch"/> that was checked out.</returns>
Branch Checkout(Commit commit, CheckoutOptions options, Signature signature);
/// <summary>
/// Updates specifed paths in the index and working directory with the versions from the specified branch, reference, or SHA.
/// <para>
/// This method does not switch branches or update the current repository HEAD.
/// </para>
/// </summary>
/// <param name = "committishOrBranchSpec">A revparse spec for the commit or branch to checkout paths from.</param>
/// <param name="paths">The paths to checkout.</param>
/// <param name="checkoutOptions">Collection of parameters controlling checkout behavior.</param>
void CheckoutPaths(string committishOrBranchSpec, IEnumerable<string> paths, CheckoutOptions checkoutOptions);
/// <summary>
/// Try to lookup an object by its <see cref="ObjectId"/>. If no matching object is found, null will be returned.
/// </summary>
/// <param name="id">The id to lookup.</param>
/// <returns>The <see cref="GitObject"/> or null if it was not found.</returns>
GitObject Lookup(ObjectId id);
/// <summary>
/// Try to lookup an object by its sha or a reference canonical name. If no matching object is found, null will be returned.
/// </summary>
/// <param name="objectish">A revparse spec for the object to lookup.</param>
/// <returns>The <see cref="GitObject"/> or null if it was not found.</returns>
GitObject Lookup(string objectish);
/// <summary>
/// Try to lookup an object by its <see cref="ObjectId"/> and <see cref="ObjectType"/>. If no matching object is found, null will be returned.
/// </summary>
/// <param name="id">The id to lookup.</param>
/// <param name="type">The kind of GitObject being looked up</param>
/// <returns>The <see cref="GitObject"/> or null if it was not found.</returns>
GitObject Lookup(ObjectId id, ObjectType type);
/// <summary>
/// Try to lookup an object by its sha or a reference canonical name and <see cref="ObjectType"/>. If no matching object is found, null will be returned.
/// </summary>
/// <param name="objectish">A revparse spec for the object to lookup.</param>
/// <param name="type">The kind of <see cref="GitObject"/> being looked up</param>
/// <returns>The <see cref="GitObject"/> or null if it was not found.</returns>
GitObject Lookup(string objectish, ObjectType type);
/// <summary>
/// Stores the content of the <see cref="Repository.Index"/> as a new <see cref="LibGit2Sharp.Commit"/> into the repository.
/// The tip of the <see cref="Repository.Head"/> will be used as the parent of this new Commit.
/// Once the commit is created, the <see cref="Repository.Head"/> will move forward to point at it.
/// </summary>
/// <param name="message">The description of why a change was made to the repository.</param>
/// <param name="author">The <see cref="Signature"/> of who made the change.</param>
/// <param name="committer">The <see cref="Signature"/> of who added the change to the repository.</param>
/// <param name="options">The <see cref="CommitOptions"/> that specify the commit behavior.</param>
/// <returns>The generated <see cref="LibGit2Sharp.Commit"/>.</returns>
Commit Commit(string message, Signature author, Signature committer, CommitOptions options);
/// <summary>
/// Sets the current <see cref="Head"/> to the specified commit and optionally resets the <see cref="Index"/> and
/// the content of the working tree to match.
/// </summary>
/// <param name="resetMode">Flavor of reset operation to perform.</param>
/// <param name="commit">The target commit object.</param>
/// <param name="signature">Identity for use when updating the reflog.</param>
/// <param name="logMessage">Message to use when updating the reflog.</param>
void Reset(ResetMode resetMode, Commit commit, Signature signature, string logMessage);
/// <summary>
/// Replaces entries in the <see cref="Repository.Index"/> with entries from the specified commit.
/// </summary>
/// <param name="commit">The target commit object.</param>
/// <param name="paths">The list of paths (either files or directories) that should be considered.</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>
void Reset(Commit commit, IEnumerable<string> paths, ExplicitPathsOptions explicitPathsOptions);
/// <summary>
/// Clean the working tree by removing files that are not under version control.
/// </summary>
void RemoveUntrackedFiles();
/// <summary>
/// Revert the specified commit.
/// </summary>
/// <param name="commit">The <see cref="Commit"/> to revert.</param>
/// <param name="reverter">The <see cref="Signature"/> of who is performing the reverte.</param>
/// <param name="options"><see cref="RevertOptions"/> controlling revert behavior.</param>
/// <returns>The result of the revert.</returns>
RevertResult Revert(Commit commit, Signature reverter, RevertOptions options);
/// <summary>
/// Merge changes from commit into the branch pointed at by HEAD..
/// </summary>
/// <param name="commit">The commit to merge into the branch pointed at by HEAD.</param>
/// <param name="merger">The <see cref="Signature"/> of who is performing the merge.</param>
/// <param name="options">Specifies optional parameters controlling merge behavior; if null, the defaults are used.</param>
/// <returns>The <see cref="MergeResult"/> of the merge.</returns>
MergeResult Merge(Commit commit, Signature merger, MergeOptions options);
/// <summary>
/// Merges changes from branch into the branch pointed at by HEAD..
/// </summary>
/// <param name="branch">The branch to merge into the branch pointed at by HEAD.</param>
/// <param name="merger">The <see cref="Signature"/> of who is performing the merge.</param>
/// <param name="options">Specifies optional parameters controlling merge behavior; if null, the defaults are used.</param>
/// <returns>The <see cref="MergeResult"/> of the merge.</returns>
MergeResult Merge(Branch branch, Signature merger, MergeOptions options);
/// <summary>
/// Merges changes from the commit into the branch pointed at by HEAD.
/// </summary>
/// <param name="committish">The commit to merge into branch pointed at by HEAD.</param>
/// <param name="merger">The <see cref="Signature"/> of who is performing the merge.</param>
/// <param name="options">Specifies optional parameters controlling merge behavior; if null, the defaults are used.</param>
/// <returns>The <see cref="MergeResult"/> of the merge.</returns>
MergeResult Merge(string committish, Signature merger, MergeOptions options);
/// <summary>
/// Cherry picks changes from the commit into the branch pointed at by HEAD.
/// </summary>
/// <param name="commit">The commit to cherry pick into branch pointed at by HEAD.</param>
/// <param name="committer">The <see cref="Signature"/> of who is performing the cherry pick.</param>
/// <param name="options">Specifies optional parameters controlling cherry pick behavior; if null, the defaults are used.</param>
/// <returns>The <see cref="MergeResult"/> of the merge.</returns>
CherryPickResult CherryPick(Commit commit, Signature committer, CherryPickOptions options);
/// <summary>
/// Manipulate the currently ignored files.
/// </summary>
Ignore Ignore { get; }
/// <summary>
/// Provides access to network functionality for a repository.
/// </summary>
Network Network { get; }
///<summary>
/// Lookup and enumerate stashes in the repository.
///</summary>
StashCollection Stashes { get; }
/// <summary>
/// Find where each line of a file originated.
/// </summary>
/// <param name="path">Path of the file to blame.</param>
/// <param name="options">Specifies optional parameters; if null, the defaults are used.</param>
/// <returns>The blame for the file.</returns>
BlameHunkCollection Blame(string path, BlameOptions options);
/// <summary>
/// Promotes to the staging area the latest modifications of a file in the working directory (addition, updation or removal).
///
/// If this path is ignored by configuration then it will not be staged unless <see cref="StageOptions.IncludeIgnored"/> is unset.
/// </summary>
/// <param name="path">The path of the file within the working directory.</param>
/// <param name="stageOptions">Determines how paths will be staged.</param>
void Stage(string path, StageOptions stageOptions);
/// <summary>
/// Promotes to the staging area the latest modifications of a collection of files in the working directory (addition, updation or removal).
///
/// Any paths (even those listed explicitly) that are ignored by configuration will not be staged unless <see cref="StageOptions.IncludeIgnored"/> is unset.
/// </summary>
/// <param name="paths">The collection of paths of the files within the working directory.</param>
/// <param name="stageOptions">Determines how paths will be staged.</param>
void Stage(IEnumerable<string> paths, StageOptions stageOptions);
/// <summary>
/// Removes from the staging area all the modifications of a file since the latest commit (addition, updation or removal).
/// </summary>
/// <param name="path">The path of the file within the working directory.</param>
/// <param name="explicitPathsOptions">
/// The passed <paramref name="path"/> will be treated as explicit paths.
/// Use these options to determine how unmatched explicit paths should be handled.
/// </param>
void Unstage(string path, ExplicitPathsOptions explicitPathsOptions);
/// <summary>
/// Removes from the staging area all the modifications of a collection of file since the latest commit (addition, updation or removal).
/// </summary>
/// <param name="paths">The collection of paths of the files within the working directory.</param>
/// <param name="explicitPathsOptions">
/// The passed <paramref name="paths"/> will be treated as explicit paths.
/// Use these options to determine how unmatched explicit paths should be handled.
/// </param>
void Unstage(IEnumerable<string> paths, ExplicitPathsOptions explicitPathsOptions);
/// <summary>
/// Moves and/or renames a file in the working directory and promotes the change to the staging area.
/// </summary>
/// <param name="sourcePath">The path of the file within the working directory which has to be moved/renamed.</param>
/// <param name="destinationPath">The target path of the file within the working directory.</param>
void Move(string sourcePath, string destinationPath);
/// <summary>
/// Moves and/or renames a collection of files in the working directory and promotes the changes to the staging area.
/// </summary>
/// <param name="sourcePaths">The paths of the files within the working directory which have to be moved/renamed.</param>
/// <param name="destinationPaths">The target paths of the files within the working directory.</param>
void Move(IEnumerable<string> sourcePaths, IEnumerable<string> destinationPaths);
/// <summary>
/// Removes a file from the staging area, and optionally removes it from the working directory as well.
/// <para>
/// If the file has already been deleted from the working directory, this method will only deal
/// with promoting the removal to the staging area.
/// </para>
/// <para>
/// The default behavior is to remove the file from the working directory as well.
/// </para>
/// <para>
/// When not passing a <paramref name="explicitPathsOptions"/>, the passed path will be treated as
/// a pathspec. You can for example use it to pass the relative path to a folder inside the working directory,
/// so that all files beneath this folders, and the folder itself, will be removed.
/// </para>
/// </summary>
/// <param name="path">The path of the file within the working directory.</param>
/// <param name="removeFromWorkingDirectory">True to remove the file from the working directory, False otherwise.</param>
/// <param name="explicitPathsOptions">
/// The passed <paramref name="path"/> will be treated as an explicit path.
/// Use these options to determine how unmatched explicit paths should be handled.
/// </param>
void Remove(string path, bool removeFromWorkingDirectory, ExplicitPathsOptions explicitPathsOptions);
/// <summary>
/// Removes a collection of fileS from the staging, and optionally removes them from the working directory as well.
/// <para>
/// If a file has already been deleted from the working directory, this method will only deal
/// with promoting the removal to the staging area.
/// </para>
/// <para>
/// The default behavior is to remove the files from the working directory as well.
/// </para>
/// <para>
/// When not passing a <paramref name="explicitPathsOptions"/>, the passed paths will be treated as
/// a pathspec. You can for example use it to pass the relative paths to folders inside the working directory,
/// so that all files beneath these folders, and the folders themselves, will be removed.
/// </para>
/// </summary>
/// <param name="paths">The collection of paths of the files within the working directory.</param>
/// <param name="removeFromWorkingDirectory">True to remove the files from the working directory, False otherwise.</param>
/// <param name="explicitPathsOptions">
/// The passed <paramref name="paths"/> will be treated as explicit paths.
/// Use these options to determine how unmatched explicit paths should be handled.
/// </param>
void Remove(IEnumerable<string> paths, bool removeFromWorkingDirectory, ExplicitPathsOptions explicitPathsOptions);
/// <summary>
/// Retrieves the state of a file in the working directory, comparing it against the staging area and the latest commmit.
/// </summary>
/// <param name="filePath">The relative path within the working directory to the file.</param>
/// <returns>A <see cref="FileStatus"/> representing the state of the <paramref name="filePath"/> parameter.</returns>
FileStatus RetrieveStatus(string filePath);
/// <summary>
/// Retrieves the state of all files in the working directory, comparing them against the staging area and the latest commmit.
/// </summary>
/// <param name="options">If set, the options that control the status investigation.</param>
/// <returns>A <see cref="RepositoryStatus"/> holding the state of all the files.</returns>
RepositoryStatus RetrieveStatus(StatusOptions options);
}
}
| |
#region License
//
// Copyright (c) 2018, Fluent Migrator Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Linq;
using FluentMigrator.Exceptions;
using FluentMigrator.Runner.Generators.SqlServer;
using NUnit.Framework;
using Shouldly;
namespace FluentMigrator.Tests.Unit.Generators.SqlServerCe
{
[TestFixture]
public class SqlServerCeColumnTests : BaseColumnTests
{
protected SqlServerCeGenerator Generator;
[SetUp]
public void Setup()
{
Generator = new SqlServerCeGenerator();
}
[Test]
public override void CanCreateNullableColumnWithCustomDomainTypeAndCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateColumnExpressionWithNullableCustomType();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE [TestTable1] ADD [TestColumn1] MyDomainType");
}
[Test]
public override void CanCreateNullableColumnWithCustomDomainTypeAndDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateColumnExpressionWithNullableCustomType();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE [TestTable1] ADD [TestColumn1] MyDomainType");
}
[Test]
public override void CanAlterColumnWithCustomSchema()
{
var expression = GeneratorTestHelper.GetAlterColumnExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE [TestTable1] ALTER COLUMN [TestColumn1] NVARCHAR(20) NOT NULL");
}
[Test]
public void CanAlterColumnToNullableWithCustomSchema()
{
var expression = GeneratorTestHelper.GetAlterColumnExpression();
expression.SchemaName = "TestSchema";
expression.Column.IsNullable = true;
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE [TestTable1] ALTER COLUMN [TestColumn1] NVARCHAR(20) NULL");
}
[Test]
public override void CanAlterColumnWithDefaultSchema()
{
//TODO: This will fail if there are any keys attached
var expression = GeneratorTestHelper.GetAlterColumnExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE [TestTable1] ALTER COLUMN [TestColumn1] NVARCHAR(20) NOT NULL");
}
[Test]
public void CanAlterColumnToNullableWithDefaultSchema()
{
//TODO: This will fail if there are any keys attached
var expression = GeneratorTestHelper.GetAlterColumnExpression();
expression.Column.IsNullable = true;
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE [TestTable1] ALTER COLUMN [TestColumn1] NVARCHAR(20) NULL");
}
[Test]
public override void CanCreateAutoIncrementColumnWithCustomSchema()
{
var expression = GeneratorTestHelper.GetAlterColumnAddAutoIncrementExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE [TestTable1] ALTER COLUMN [TestColumn1] INT NOT NULL IDENTITY(1,1)");
}
[Test]
public override void CanCreateAutoIncrementColumnWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetAlterColumnAddAutoIncrementExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE [TestTable1] ALTER COLUMN [TestColumn1] INT NOT NULL IDENTITY(1,1)");
}
[Test]
public override void CanCreateColumnWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateColumnExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE [TestTable1] ADD [TestColumn1] NVARCHAR(5) NOT NULL");
}
[Test]
public override void CanCreateColumnWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateColumnExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE [TestTable1] ADD [TestColumn1] NVARCHAR(5) NOT NULL");
}
[Test]
public override void CanCreateColumnWithSystemMethodAndCustomSchema()
{
var expressions = GeneratorTestHelper.GetCreateColumnWithSystemMethodExpression("TestSchema");
var result = string.Join(Environment.NewLine, expressions.Select(x => (string)Generator.Generate((dynamic)x)));
result.ShouldBe(
@"ALTER TABLE [TestTable1] ADD [TestColumn1] DATETIME" + Environment.NewLine +
"UPDATE [TestTable1] SET [TestColumn1] = GETDATE() WHERE 1 = 1");
}
[Test]
public override void CanCreateColumnWithSystemMethodAndDefaultSchema()
{
var expressions = GeneratorTestHelper.GetCreateColumnWithSystemMethodExpression();
var result = string.Join(Environment.NewLine, expressions.Select(x => (string)Generator.Generate((dynamic)x)));
result.ShouldBe(
@"ALTER TABLE [TestTable1] ADD [TestColumn1] DATETIME" + Environment.NewLine +
"UPDATE [TestTable1] SET [TestColumn1] = GETDATE() WHERE 1 = 1");
}
[Test]
public override void CanCreateDecimalColumnWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateDecimalColumnExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE [TestTable1] ADD [TestColumn1] NUMERIC(19,2) NOT NULL");
}
[Test]
public override void CanCreateDecimalColumnWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateDecimalColumnExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE [TestTable1] ADD [TestColumn1] NUMERIC(19,2) NOT NULL");
}
[Test]
public override void CanDropColumnWithCustomSchema()
{
//This does not work if column in used in constraint, index etc.
var expression = GeneratorTestHelper.GetDeleteColumnExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE [TestTable1] DROP COLUMN [TestColumn1];");
}
[Test]
public override void CanDropColumnWithDefaultSchema()
{
//This does not work if column in used in constraint, index etc.
var expression = GeneratorTestHelper.GetDeleteColumnExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE [TestTable1] DROP COLUMN [TestColumn1];");
}
[Test]
public override void CanDropMultipleColumnsWithCustomSchema()
{
//This does not work if it is a primary key
var expression = GeneratorTestHelper.GetDeleteColumnExpression(new[] { "TestColumn1", "TestColumn2" });
expression.SchemaName = "TestSchema";
Assert.Throws<DatabaseOperationNotSupportedException>(() => Generator.Generate(expression));
}
[Test]
public override void CanDropMultipleColumnsWithDefaultSchema()
{
//This does not work if it is a primary key
var expression = GeneratorTestHelper.GetDeleteColumnExpression(new[] { "TestColumn1", "TestColumn2" });
Assert.Throws<DatabaseOperationNotSupportedException>(() => Generator.Generate(expression));
}
[Test]
public override void CanRenameColumnWithCustomSchema()
{
var expression = GeneratorTestHelper.GetRenameColumnExpression();
expression.SchemaName = "TestSchema";
Assert.Throws<DatabaseOperationNotSupportedException>(() => Generator.Generate(expression));
}
[Test]
public override void CanRenameColumnWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetRenameColumnExpression();
Assert.Throws<DatabaseOperationNotSupportedException>(() => Generator.Generate(expression));
}
}
}
| |
// 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.Globalization;
namespace System.Globalization
{
internal partial class FormatProvider
{
private static class TimeSpanFormat
{
// auto-generated
private static String IntToString(int n, int digits)
{
return n.ToString(new string('0', digits));
}
internal static readonly FormatLiterals PositiveInvariantFormatLiterals = TimeSpanFormat.FormatLiterals.InitInvariant(false /*isNegative*/);
internal static readonly FormatLiterals NegativeInvariantFormatLiterals = TimeSpanFormat.FormatLiterals.InitInvariant(true /*isNegative*/);
internal enum Pattern
{
None = 0,
Minimum = 1,
Full = 2,
}
//
// Format
//
// Actions: Main method called from TimeSpan.ToString
//
internal static String Format(TimeSpan value, String format, IFormatProvider formatProvider)
{
if (format == null || format.Length == 0)
format = "c";
// standard formats
if (format.Length == 1)
{
char f = format[0];
if (f == 'c' || f == 't' || f == 'T')
return FormatStandard(value, true, format, Pattern.Minimum);
if (f == 'g' || f == 'G')
{
Pattern pattern;
DateTimeFormatInfo dtfi = DateTimeFormatInfo.GetInstance(formatProvider);
if (value._ticks < 0)
format = dtfi.FullTimeSpanNegativePattern;
else
format = dtfi.FullTimeSpanPositivePattern;
if (f == 'g')
pattern = Pattern.Minimum;
else
pattern = Pattern.Full;
return FormatStandard(value, false, format, pattern);
}
throw new FormatException(SR.Format_InvalidString);
}
return FormatCustomized(value, format, DateTimeFormatInfo.GetInstance(formatProvider));
}
//
// FormatStandard
//
// Actions: Format the TimeSpan instance using the specified format.
//
private static String FormatStandard(TimeSpan value, bool isInvariant, String format, Pattern pattern)
{
StringBuilder sb = StringBuilderCache.Acquire(InternalGloablizationHelper.StringBuilderDefaultCapacity);
int day = (int)(value.Ticks / TimeSpan.TicksPerDay);
long time = value.Ticks % TimeSpan.TicksPerDay;
if (value.Ticks < 0)
{
day = -day;
time = -time;
}
int hours = (int)(time / TimeSpan.TicksPerHour % 24);
int minutes = (int)(time / TimeSpan.TicksPerMinute % 60);
int seconds = (int)(time / TimeSpan.TicksPerSecond % 60);
int fraction = (int)(time % TimeSpan.TicksPerSecond);
FormatLiterals literal;
if (isInvariant)
{
if (value.Ticks < 0)
literal = NegativeInvariantFormatLiterals;
else
literal = PositiveInvariantFormatLiterals;
}
else
{
literal = new FormatLiterals();
literal.Init(format, pattern == Pattern.Full);
}
if (fraction != 0)
{ // truncate the partial second to the specified length
fraction = (int)((long)fraction / (long)Math.Pow(10, DateTimeFormat.MaxSecondsFractionDigits - literal.ff));
}
// Pattern.Full: [-]dd.hh:mm:ss.fffffff
// Pattern.Minimum: [-][d.]hh:mm:ss[.fffffff]
sb.Append(literal.Start); // [-]
if (pattern == Pattern.Full || day != 0)
{ //
sb.Append(day); // [dd]
sb.Append(literal.DayHourSep); // [.]
} //
sb.Append(IntToString(hours, literal.hh)); // hh
sb.Append(literal.HourMinuteSep); // :
sb.Append(IntToString(minutes, literal.mm)); // mm
sb.Append(literal.MinuteSecondSep); // :
sb.Append(IntToString(seconds, literal.ss)); // ss
if (!isInvariant && pattern == Pattern.Minimum)
{
int effectiveDigits = literal.ff;
while (effectiveDigits > 0)
{
if (fraction % 10 == 0)
{
fraction = fraction / 10;
effectiveDigits--;
}
else
{
break;
}
}
if (effectiveDigits > 0)
{
sb.Append(literal.SecondFractionSep); // [.FFFFFFF]
sb.Append((fraction).ToString(DateTimeFormat.fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture));
}
}
else if (pattern == Pattern.Full || fraction != 0)
{
sb.Append(literal.SecondFractionSep); // [.]
sb.Append(IntToString(fraction, literal.ff)); // [fffffff]
} //
sb.Append(literal.End); //
return StringBuilderCache.GetStringAndRelease(sb);
}
//
// FormatCustomized
//
// Actions: Format the TimeSpan instance using the specified format.
//
internal static String FormatCustomized(TimeSpan value, String format, DateTimeFormatInfo dtfi)
{
int day = (int)(value.Ticks / TimeSpan.TicksPerDay);
long time = value.Ticks % TimeSpan.TicksPerDay;
if (value.Ticks < 0)
{
day = -day;
time = -time;
}
int hours = (int)(time / TimeSpan.TicksPerHour % 24);
int minutes = (int)(time / TimeSpan.TicksPerMinute % 60);
int seconds = (int)(time / TimeSpan.TicksPerSecond % 60);
int fraction = (int)(time % TimeSpan.TicksPerSecond);
long tmp = 0;
int i = 0;
int tokenLen;
StringBuilder result = StringBuilderCache.Acquire(InternalGloablizationHelper.StringBuilderDefaultCapacity);
while (i < format.Length)
{
char ch = format[i];
int nextChar;
switch (ch)
{
case 'h':
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 2)
throw new FormatException(SR.Format_InvalidString);
DateTimeFormat.FormatDigits(result, hours, tokenLen);
break;
case 'm':
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 2)
throw new FormatException(SR.Format_InvalidString);
DateTimeFormat.FormatDigits(result, minutes, tokenLen);
break;
case 's':
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 2)
throw new FormatException(SR.Format_InvalidString);
DateTimeFormat.FormatDigits(result, seconds, tokenLen);
break;
case 'f':
//
// The fraction of a second in single-digit precision. The remaining digits are truncated.
//
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits)
throw new FormatException(SR.Format_InvalidString);
tmp = (long)fraction;
tmp /= (long)Math.Pow(10, DateTimeFormat.MaxSecondsFractionDigits - tokenLen);
result.Append((tmp).ToString(DateTimeFormat.fixedNumberFormats[tokenLen - 1], CultureInfo.InvariantCulture));
break;
case 'F':
//
// Displays the most significant digit of the seconds fraction. Nothing is displayed if the digit is zero.
//
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits)
throw new FormatException(SR.Format_InvalidString);
tmp = (long)fraction;
tmp /= (long)Math.Pow(10, DateTimeFormat.MaxSecondsFractionDigits - tokenLen);
int effectiveDigits = tokenLen;
while (effectiveDigits > 0)
{
if (tmp % 10 == 0)
{
tmp = tmp / 10;
effectiveDigits--;
}
else
{
break;
}
}
if (effectiveDigits > 0)
{
result.Append((tmp).ToString(DateTimeFormat.fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture));
}
break;
case 'd':
//
// tokenLen == 1 : Day as digits with no leading zero.
// tokenLen == 2+: Day as digits with leading zero for single-digit days.
//
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 8)
throw new FormatException(SR.Format_InvalidString);
DateTimeFormat.FormatDigits(result, day, tokenLen, true);
break;
case '\'':
case '\"':
tokenLen = DateTimeFormat.ParseQuoteString(format, i, result);
break;
case '%':
// Optional format character.
// For example, format string "%d" will print day
// Most of the cases, "%" can be ignored.
nextChar = DateTimeFormat.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(TimeSpanFormat.FormatCustomized(value, ((char)nextChar).ToString(), dtfi));
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 example, "\d" will insert the character 'd' into the string.
//
nextChar = DateTimeFormat.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:
throw new FormatException(SR.Format_InvalidString);
}
i += tokenLen;
}
return StringBuilderCache.GetStringAndRelease(result);
}
internal struct FormatLiterals
{
internal String Start
{
get
{
return _literals[0];
}
}
internal String DayHourSep
{
get
{
return _literals[1];
}
}
internal String HourMinuteSep
{
get
{
return _literals[2];
}
}
internal String MinuteSecondSep
{
get
{
return _literals[3];
}
}
internal String SecondFractionSep
{
get
{
return _literals[4];
}
}
internal String End
{
get
{
return _literals[5];
}
}
internal String AppCompatLiteral;
internal int dd;
internal int hh;
internal int mm;
internal int ss;
internal int ff;
private String[] _literals;
/* factory method for static invariant FormatLiterals */
internal static FormatLiterals InitInvariant(bool isNegative)
{
FormatLiterals x = new FormatLiterals();
x._literals = new String[6];
x._literals[0] = isNegative ? "-" : String.Empty;
x._literals[1] = ".";
x._literals[2] = ":";
x._literals[3] = ":";
x._literals[4] = ".";
x._literals[5] = String.Empty;
x.AppCompatLiteral = ":."; // MinuteSecondSep+SecondFractionSep;
x.dd = 2;
x.hh = 2;
x.mm = 2;
x.ss = 2;
x.ff = DateTimeFormat.MaxSecondsFractionDigits;
return x;
}
// For the "v1" TimeSpan localized patterns, the data is simply literal field separators with
// the constants guaranteed to include DHMSF ordered greatest to least significant.
// Once the data becomes more complex than this we will need to write a proper tokenizer for
// parsing and formatting
internal void Init(String format, bool useInvariantFieldLengths)
{
_literals = new String[6];
for (int i = 0; i < _literals.Length; i++)
_literals[i] = String.Empty;
dd = 0;
hh = 0;
mm = 0;
ss = 0;
ff = 0;
StringBuilder sb = StringBuilderCache.Acquire(InternalGloablizationHelper.StringBuilderDefaultCapacity);
bool inQuote = false;
char quote = '\'';
int field = 0;
for (int i = 0; i < format.Length; i++)
{
switch (format[i])
{
case '\'':
case '\"':
if (inQuote && (quote == format[i]))
{
if (field >= 0 && field <= 5)
{
_literals[field] = sb.ToString();
sb.Length = 0;
inQuote = false;
}
else
{
return; // how did we get here?
}
}
else if (!inQuote)
{
/* we are at the start of a new quote block */
quote = format[i];
inQuote = true;
}
else
{
/* we were in a quote and saw the other type of quote character, so we are still in a quote */
}
break;
case '%':
goto default;
case '\\':
if (!inQuote)
{
i++; /* skip next character that is escaped by this backslash or percent sign */
break;
}
goto default;
case 'd':
if (!inQuote)
{
field = 1; // DayHourSep
dd++;
}
break;
case 'h':
if (!inQuote)
{
field = 2; // HourMinuteSep
hh++;
}
break;
case 'm':
if (!inQuote)
{
field = 3; // MinuteSecondSep
mm++;
}
break;
case 's':
if (!inQuote)
{
field = 4; // SecondFractionSep
ss++;
}
break;
case 'f':
case 'F':
if (!inQuote)
{
field = 5; // End
ff++;
}
break;
default:
sb.Append(format[i]);
break;
}
}
AppCompatLiteral = MinuteSecondSep + SecondFractionSep;
if (useInvariantFieldLengths)
{
dd = 2;
hh = 2;
mm = 2;
ss = 2;
ff = DateTimeFormat.MaxSecondsFractionDigits;
}
else
{
if (dd < 1 || dd > 2) dd = 2; // The DTFI property has a problem. let's try to make the best of the situation.
if (hh < 1 || hh > 2) hh = 2;
if (mm < 1 || mm > 2) mm = 2;
if (ss < 1 || ss > 2) ss = 2;
if (ff < 1 || ff > 7) ff = 7;
}
StringBuilderCache.Release(sb);
}
} //end of struct FormatLiterals
}
}
}
| |
// Code generated by a Template
using System;
using DNX.Helpers.Maths;
using DNX.Helpers.Validation;
using NUnit.Framework;
using Shouldly;
using Test.DNX.Helpers.Validation.TestsDataSource;
namespace Test.DNX.Helpers.Validation
{
[TestFixture]
public class GuardSByteTests
{
[TestCaseSource(typeof(GuardSByteTestsSource), "IsBetween_Default")]
public bool Guard_IsBetween_Default(sbyte value, sbyte min, sbyte max, string messageText)
{
try
{
// Act
Guard.IsBetween(() => value, min, max);
return true;
}
catch (ArgumentOutOfRangeException ex)
{
Assert.IsNotNull(messageText);
Assert.IsNotEmpty(messageText);
ex.Message.ShouldStartWith(messageText);
return false;
}
catch (Exception ex)
{
// Assert
Assert.Fail(ex.Message);
return false;
}
}
[TestCaseSource(typeof(GuardSByteTestsSource), "IsBetween_BoundsType")]
public bool Guard_IsBetween_BoundsType(sbyte value, sbyte min, sbyte max, IsBetweenBoundsType boundsType, string messageText)
{
try
{
// Act
Guard.IsBetween(() => value, min, max, boundsType);
return true;
}
catch (ArgumentOutOfRangeException ex)
{
Assert.IsNotNull(messageText);
Assert.IsNotEmpty(messageText);
ex.Message.ShouldStartWith(messageText);
return false;
}
catch (Exception ex)
{
// Assert
Assert.Fail(ex.Message);
return false;
}
}
[TestCaseSource(typeof(GuardSByteTestsSource), "IsBetween")]
public bool Guard_IsBetween(sbyte value, sbyte min, sbyte max, bool allowEitherOrder, IsBetweenBoundsType boundsType, string messageText)
{
try
{
// Act
Guard.IsBetween(() => value, min, max, allowEitherOrder, boundsType);
return true;
}
catch (ArgumentOutOfRangeException ex)
{
Assert.IsNotNull(messageText);
Assert.IsNotEmpty(messageText);
ex.Message.ShouldStartWith(messageText);
return false;
}
catch (Exception ex)
{
// Assert
Assert.Fail(ex.Message);
return false;
}
}
[TestCaseSource(typeof(GuardSByteTestsSource), "IsGreaterThan")]
public bool Guard_IsGreaterThan_Expr(sbyte value, sbyte min, string messageText)
{
try
{
// Act
Guard.IsGreaterThan(() => value, min);
return true;
}
catch (ArgumentOutOfRangeException ex)
{
Assert.IsNotNull(messageText);
Assert.IsNotEmpty(messageText);
ex.Message.ShouldStartWith(messageText);
return false;
}
catch (Exception ex)
{
// Assert
Assert.Fail(ex.Message);
return false;
}
}
[TestCaseSource(typeof(GuardSByteTestsSource), "IsGreaterThan")]
public bool Guard_IsGreaterThan_Value(sbyte actualValue, sbyte min, string messageText)
{
try
{
// Act
sbyte value = min;
Guard.IsGreaterThan(() => value, actualValue, min);
return true;
}
catch (ArgumentOutOfRangeException ex)
{
Assert.IsNotNull(messageText);
Assert.IsNotEmpty(messageText);
ex.Message.ShouldStartWith(messageText);
return false;
}
catch (Exception ex)
{
// Assert
Assert.Fail(ex.Message);
return false;
}
}
[TestCaseSource(typeof(GuardSByteTestsSource), "IsGreaterThanOrEqualTo")]
public bool Guard_IsGreaterThanOrEqualTo_Expr(sbyte value, sbyte min, string messageText)
{
try
{
// Act
Guard.IsGreaterThanOrEqualTo(() => value, min);
return true;
}
catch (ArgumentOutOfRangeException ex)
{
Assert.IsNotNull(messageText);
Assert.IsNotEmpty(messageText);
ex.Message.ShouldStartWith(messageText);
return false;
}
catch (Exception ex)
{
// Assert
Assert.Fail(ex.Message);
return false;
}
}
[TestCaseSource(typeof(GuardSByteTestsSource), "IsGreaterThanOrEqualTo")]
public bool Guard_IsGreaterThanOrEqualTo_Value(sbyte actualValue, sbyte min, string messageText)
{
try
{
// Act
sbyte value = min;
Guard.IsGreaterThanOrEqualTo(() => value, actualValue, min);
return true;
}
catch (ArgumentOutOfRangeException ex)
{
Assert.IsNotNull(messageText);
Assert.IsNotEmpty(messageText);
ex.Message.ShouldStartWith(messageText);
return false;
}
catch (Exception ex)
{
// Assert
Assert.Fail(ex.Message);
return false;
}
}
[TestCaseSource(typeof(GuardSByteTestsSource), "IsLessThan")]
public bool Guard_IsLessThan_Expr(sbyte value, sbyte max, string messageText)
{
try
{
// Act
Guard.IsLessThan(() => value, max);
return true;
}
catch (ArgumentOutOfRangeException ex)
{
Assert.IsNotNull(messageText);
Assert.IsNotEmpty(messageText);
ex.Message.ShouldStartWith(messageText);
return false;
}
catch (Exception ex)
{
// Assert
Assert.Fail(ex.Message);
return false;
}
}
[TestCaseSource(typeof(GuardSByteTestsSource), "IsLessThan")]
public bool Guard_IsLessThan_Value(sbyte actualValue, sbyte max, string messageText)
{
try
{
// Act
sbyte value = max;
Guard.IsLessThan(() => value, actualValue, max);
return true;
}
catch (ArgumentOutOfRangeException ex)
{
Assert.IsNotNull(messageText);
Assert.IsNotEmpty(messageText);
ex.Message.ShouldStartWith(messageText);
return false;
}
catch (Exception ex)
{
// Assert
Assert.Fail(ex.Message);
return false;
}
}
[TestCaseSource(typeof(GuardSByteTestsSource), "IsLessThanOrEqualTo")]
public bool Guard_IsLessThanOrEqualTo_Expr(sbyte value, sbyte max, string messageText)
{
try
{
// Act
Guard.IsLessThanOrEqualTo(() => value, max);
return true;
}
catch (ArgumentOutOfRangeException ex)
{
Assert.IsNotNull(messageText);
Assert.IsNotEmpty(messageText);
ex.Message.ShouldStartWith(messageText);
return false;
}
catch (Exception ex)
{
// Assert
Assert.Fail(ex.Message);
return false;
}
}
[TestCaseSource(typeof(GuardSByteTestsSource), "IsLessThanOrEqualTo")]
public bool Guard_IsLessThanOrEqualTo_Value(sbyte actualValue, sbyte max, string messageText)
{
try
{
// Act
sbyte value = max;
Guard.IsLessThanOrEqualTo(() => value, actualValue, max);
return true;
}
catch (ArgumentOutOfRangeException ex)
{
Assert.IsNotNull(messageText);
Assert.IsNotEmpty(messageText);
ex.Message.ShouldStartWith(messageText);
return false;
}
catch (Exception ex)
{
// Assert
Assert.Fail(ex.Message);
return false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Caliburn.Micro
{
public static class ActivityLocator
{
const string DefaultViewSuffix = "Activity";
static readonly ILog Log = LogManager.GetLog(typeof(ActivityLocator));
//These fields are used for configuring the default type mappings. They can be changed using ConfigureTypeMappings().
static string defaultSubNsViews;
static string defaultSubNsViewModels;
static bool useNameSuffixesInMappings;
static string nameFormat;
static string viewModelSuffix;
static readonly List<string> ViewSuffixList = new List<string>();
static bool includeViewSuffixInVmNames;
///<summary>
/// Used to transform names.
///</summary>
public static NameTransformer NameTransformer = new NameTransformer();
/// <summary>
/// Separator used when resolving View names for context instances.
/// </summary>
public static string ContextSeparator = ".";
static ActivityLocator() {
var configuration = new TypeMappingConfiguration
{
DefaultSubNamespaceForViews = "Activities",
IncludeViewSuffixInViewModelNames = false
};
configuration.ViewSuffixList.Add("Activity");
ConfigureTypeMappings(configuration);
}
/// <summary>
/// Specifies how type mappings are created, including default type mappings. Calling this method will
/// clear all existing name transformation rules and create new default type mappings according to the
/// configuration.
/// </summary>
/// <param name="config">An instance of TypeMappingConfiguration that provides the settings for configuration</param>
public static void ConfigureTypeMappings(TypeMappingConfiguration config)
{
if (String.IsNullOrEmpty(config.DefaultSubNamespaceForViews))
{
throw new ArgumentException("DefaultSubNamespaceForViews field cannot be blank.");
}
if (String.IsNullOrEmpty(config.DefaultSubNamespaceForViewModels))
{
throw new ArgumentException("DefaultSubNamespaceForViewModels field cannot be blank.");
}
if (String.IsNullOrEmpty(config.NameFormat))
{
throw new ArgumentException("NameFormat field cannot be blank.");
}
NameTransformer.Clear();
ViewSuffixList.Clear();
defaultSubNsViews = config.DefaultSubNamespaceForViews;
defaultSubNsViewModels = config.DefaultSubNamespaceForViewModels;
nameFormat = config.NameFormat;
useNameSuffixesInMappings = config.UseNameSuffixesInMappings;
viewModelSuffix = config.ViewModelSuffix;
ViewSuffixList.AddRange(config.ViewSuffixList);
includeViewSuffixInVmNames = config.IncludeViewSuffixInViewModelNames;
SetAllDefaults();
}
private static void SetAllDefaults()
{
if (useNameSuffixesInMappings)
{
//Add support for all view suffixes
ViewSuffixList.Apply(AddDefaultTypeMapping);
}
else
{
AddSubNamespaceMapping(defaultSubNsViewModels, defaultSubNsViews);
}
}
/// <summary>
/// Adds a default type mapping using the standard namespace mapping convention
/// </summary>
/// <param name="viewSuffix">Suffix for type name. Should be "View" or synonym of "View". (Optional)</param>
public static void AddDefaultTypeMapping(string viewSuffix = DefaultViewSuffix)
{
if (!useNameSuffixesInMappings)
{
return;
}
//Check for <Namespace>.<BaseName><ViewSuffix> construct
AddNamespaceMapping(String.Empty, String.Empty, viewSuffix);
//Check for <Namespace>.ViewModels.<NameSpace>.<BaseName><ViewSuffix> construct
AddSubNamespaceMapping(defaultSubNsViewModels, defaultSubNsViews, viewSuffix);
}
/// <summary>
/// This method registers a View suffix or synonym so that View Context resolution works properly.
/// It is automatically called internally when calling AddNamespaceMapping(), AddDefaultTypeMapping(),
/// or AddTypeMapping(). It should not need to be called explicitly unless a rule that handles synonyms
/// is added directly through the NameTransformer.
/// </summary>
/// <param name="viewSuffix">Suffix for type name. Should be "View" or synonym of "View".</param>
public static void RegisterViewSuffix(string viewSuffix)
{
if (ViewSuffixList.Count(s => s == viewSuffix) == 0)
{
ViewSuffixList.Add(viewSuffix);
}
}
/// <summary>
/// Adds a standard type mapping based on namespace RegEx replace and filter patterns
/// </summary>
/// <param name="nsSourceReplaceRegEx">RegEx replace pattern for source namespace</param>
/// <param name="nsSourceFilterRegEx">RegEx filter pattern for source namespace</param>
/// <param name="nsTargetsRegEx">Array of RegEx replace values for target namespaces</param>
/// <param name="viewSuffix">Suffix for type name. Should be "View" or synonym of "View". (Optional)</param>
public static void AddTypeMapping(string nsSourceReplaceRegEx, string nsSourceFilterRegEx, string[] nsTargetsRegEx, string viewSuffix = DefaultViewSuffix)
{
RegisterViewSuffix(viewSuffix);
var replist = new List<string>();
var repsuffix = useNameSuffixesInMappings ? viewSuffix : String.Empty;
const string basegrp = "${basename}";
foreach (var t in nsTargetsRegEx)
{
replist.Add(t + String.Format(nameFormat, basegrp, repsuffix));
}
var rxbase = RegExHelper.GetNameCaptureGroup("basename");
var suffix = String.Empty;
if (useNameSuffixesInMappings)
{
suffix = viewModelSuffix;
if (!viewModelSuffix.Contains(viewSuffix) && includeViewSuffixInVmNames)
{
suffix = viewSuffix + suffix;
}
}
var rxsrcfilter = String.IsNullOrEmpty(nsSourceFilterRegEx)
? null
: String.Concat(nsSourceFilterRegEx, String.Format(nameFormat, RegExHelper.NameRegEx, suffix), "$");
var rxsuffix = RegExHelper.GetCaptureGroup("suffix", suffix);
NameTransformer.AddRule(
String.Concat(nsSourceReplaceRegEx, String.Format(nameFormat, rxbase, rxsuffix), "$"),
replist.ToArray(),
rxsrcfilter
);
}
/// <summary>
/// Adds a standard type mapping based on namespace RegEx replace and filter patterns
/// </summary>
/// <param name="nsSourceReplaceRegEx">RegEx replace pattern for source namespace</param>
/// <param name="nsSourceFilterRegEx">RegEx filter pattern for source namespace</param>
/// <param name="nsTargetRegEx">RegEx replace value for target namespace</param>
/// <param name="viewSuffix">Suffix for type name. Should be "View" or synonym of "View". (Optional)</param>
public static void AddTypeMapping(string nsSourceReplaceRegEx, string nsSourceFilterRegEx, string nsTargetRegEx, string viewSuffix = DefaultViewSuffix)
{
AddTypeMapping(nsSourceReplaceRegEx, nsSourceFilterRegEx, new[] { nsTargetRegEx }, viewSuffix);
}
/// <summary>
/// Adds a standard type mapping based on simple namespace mapping
/// </summary>
/// <param name="nsSource">Namespace of source type</param>
/// <param name="nsTargets">Namespaces of target type as an array</param>
/// <param name="viewSuffix">Suffix for type name. Should be "View" or synonym of "View". (Optional)</param>
public static void AddNamespaceMapping(string nsSource, string[] nsTargets, string viewSuffix = DefaultViewSuffix)
{
//need to terminate with "." in order to concatenate with type name later
var nsencoded = RegExHelper.NamespaceToRegEx(nsSource + ".");
//Start pattern search from beginning of string ("^")
//unless original string was blank (i.e. special case to indicate "append target to source")
if (!String.IsNullOrEmpty(nsSource))
{
nsencoded = "^" + nsencoded;
}
//Capture namespace as "origns" in case we need to use it in the output in the future
var nsreplace = RegExHelper.GetCaptureGroup("origns", nsencoded);
var nsTargetsRegEx = nsTargets.Select(t => t + ".").ToArray();
AddTypeMapping(nsreplace, null, nsTargetsRegEx, viewSuffix);
}
/// <summary>
/// Adds a standard type mapping based on simple namespace mapping
/// </summary>
/// <param name="nsSource">Namespace of source type</param>
/// <param name="nsTarget">Namespace of target type</param>
/// <param name="viewSuffix">Suffix for type name. Should be "View" or synonym of "View". (Optional)</param>
public static void AddNamespaceMapping(string nsSource, string nsTarget, string viewSuffix = DefaultViewSuffix)
{
AddNamespaceMapping(nsSource, new[] { nsTarget }, viewSuffix);
}
/// <summary>
/// Adds a standard type mapping by substituting one subnamespace for another
/// </summary>
/// <param name="nsSource">Subnamespace of source type</param>
/// <param name="nsTargets">Subnamespaces of target type as an array</param>
/// <param name="viewSuffix">Suffix for type name. Should be "View" or synonym of "View". (Optional)</param>
public static void AddSubNamespaceMapping(string nsSource, string[] nsTargets, string viewSuffix = DefaultViewSuffix)
{
//need to terminate with "." in order to concatenate with type name later
var nsencoded = RegExHelper.NamespaceToRegEx(nsSource + ".");
string rxbeforetgt, rxaftersrc, rxaftertgt;
var rxbeforesrc = rxbeforetgt = rxaftersrc = rxaftertgt = String.Empty;
if (!String.IsNullOrEmpty(nsSource))
{
if (!nsSource.StartsWith("*"))
{
rxbeforesrc = RegExHelper.GetNamespaceCaptureGroup("nsbefore");
rxbeforetgt = @"${nsbefore}";
}
if (!nsSource.EndsWith("*"))
{
rxaftersrc = RegExHelper.GetNamespaceCaptureGroup("nsafter");
rxaftertgt = "${nsafter}";
}
}
var rxmid = RegExHelper.GetCaptureGroup("subns", nsencoded);
var nsreplace = String.Concat(rxbeforesrc, rxmid, rxaftersrc);
var nsTargetsRegEx = nsTargets.Select(t => String.Concat(rxbeforetgt, t, ".", rxaftertgt)).ToArray();
AddTypeMapping(nsreplace, null, nsTargetsRegEx, viewSuffix);
}
/// <summary>
/// Adds a standard type mapping by substituting one subnamespace for another
/// </summary>
/// <param name="nsSource">Subnamespace of source type</param>
/// <param name="nsTarget">Subnamespace of target type</param>
/// <param name="viewSuffix">Suffix for type name. Should be "View" or synonym of "View". (Optional)</param>
public static void AddSubNamespaceMapping(string nsSource, string nsTarget, string viewSuffix = DefaultViewSuffix)
{
AddSubNamespaceMapping(nsSource, new[] { nsTarget }, viewSuffix);
}
/// <summary>
/// Transforms a ViewModel type name into all of its possible View type names. Optionally accepts an instance
/// of context object
/// </summary>
/// <returns>Enumeration of transformed names</returns>
/// <remarks>Arguments:
/// typeName = The name of the ViewModel type being resolved to its companion View.
/// context = An instance of the context or null.
/// </remarks>
public static Func<string, object, IEnumerable<string>> TransformName = (typeName, context) =>
{
Func<string, string> getReplaceString;
if (context == null)
{
getReplaceString = r => r;
return NameTransformer.Transform(typeName, getReplaceString);
}
var contextstr = ContextSeparator + context;
string grpsuffix = String.Empty;
if (useNameSuffixesInMappings)
{
//Create RegEx for matching any of the synonyms registered
var synonymregex = "(" + String.Join("|", ViewSuffixList.ToArray()) + ")";
grpsuffix = RegExHelper.GetCaptureGroup("suffix", synonymregex);
}
const string grpbase = @"\${basename}";
var patternregex = String.Format(nameFormat, grpbase, grpsuffix) + "$";
//Strip out any synonym by just using contents of base capture group with context string
var replaceregex = "${basename}" + contextstr;
//Strip out the synonym
getReplaceString = r => Regex.Replace(r, patternregex, replaceregex);
//Return only the names for the context
return NameTransformer.Transform(typeName, getReplaceString).Where(n => n.EndsWith(contextstr));
};
/// <summary>
/// Locates the view type based on the specified model type.
/// </summary>
/// <returns>The view.</returns>
/// <remarks>
/// Pass the model type, display location (or null) and the context instance (or null) as parameters and receive a view type.
/// </remarks>
public static Func<Type, object, Type> LocateTypeForModelType = (modelType, context) =>
{
var viewTypeName = modelType.FullName;
viewTypeName = viewTypeName.Substring(
0,
viewTypeName.IndexOf('`') < 0
? viewTypeName.Length
: viewTypeName.IndexOf('`')
);
var viewTypeList = TransformName(viewTypeName, context);
var viewType = AssemblySource.FindTypeByNames(viewTypeList);
if (viewType == null)
{
Log.Warn("View not found. Searched: {0}.", string.Join(", ", viewTypeList.ToArray()));
}
return viewType;
};
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Runtime.InteropServices;
namespace Trionic5Controls
{
public partial class SurfaceGraphViewer : DevExpress.XtraEditors.XtraUserControl
{
[DllImport("user32.dll", EntryPoint = "CreateIconIndirect")]
private static extern IntPtr CreateIconIndirect(IntPtr iconInfo);
private struct IconInfo
{
public bool fIcon;
public Int32 xHotspot;
public Int32 yHotspot;
public IntPtr hbmMask;
public IntPtr hbmColor;
}
Surface3DRenderer sr;
private bool m_IsDragging = false;
private Point m_p = new Point();
/* private int pov_x = -20;
private int pov_y = 35;
private int pov_z = 40;
private int pan_x = 0;
private int pan_y = 0;*/
PointF m_lastMouseHoverPoint = new PointF();
private bool m_ShowinBlue = false;
public bool ShowinBlue
{
get { return m_ShowinBlue; }
set
{
m_ShowinBlue = value;
sr.ShowinBlue = value;
}
}
private int pov_x = 30;
public int Pov_x
{
get { return pov_x; }
set { pov_x = value; }
}
private int pov_y = 56;
public int Pov_y
{
get { return pov_y; }
set { pov_y = value; }
}
private int pov_z = 21;
public int Pov_z
{
get { return pov_z; }
set { pov_z = value; }
}
private int pan_x = 45;
public int Pan_x
{
get { return pan_x; }
set { pan_x = value; }
}
private int pan_y = 77;
public int Pan_y
{
get { return pan_y; }
set { pan_y = value; }
}
private double pov_d = 0.6;
private bool m_isRedWhite = false;
public bool IsRedWhite
{
get { return m_isRedWhite; }
set
{
m_isRedWhite = value;
sr.IsRedWhite = m_isRedWhite;
}
}
public double Pov_d
{
get { return pov_d; }
set { pov_d = value; }
}
private int m_map_length = 0;
public int Map_length
{
get { return m_map_length; }
set { m_map_length = value; }
}
private string m_map_name = string.Empty;
public string Map_name
{
get { return m_map_name; }
set
{
m_map_name = value;
}
}
private int m_numberOfColumns = 8;
public int NumberOfColumns
{
get { return m_numberOfColumns; }
set
{
m_numberOfColumns = value;
if (m_numberOfColumns == 1)
{
pan_x = 0;
pan_y = 10;
pov_x = 70;
pov_y = 0;
pov_z = 0;
pov_d = 0.2;
}
}
}
private bool m_isSixteenbit = false;
public bool IsSixteenbit
{
get { return m_isSixteenbit; }
set { m_isSixteenbit = value; }
}
private int[] x_axis;
public int[] X_axis
{
get { return x_axis; }
set { x_axis = value; }
}
private int[] y_axis;
public int[] Y_axis
{
get { return y_axis; }
set { y_axis = value; }
}
private int[] z_axis;
public int[] Z_axis
{
get { return z_axis; }
set { z_axis = value; }
}
private string x_axis_descr = string.Empty;
public string X_axis_descr
{
get { return x_axis_descr; }
set { x_axis_descr = value; }
}
private string y_axis_descr = string.Empty;
public string Y_axis_descr
{
get { return y_axis_descr; }
set { y_axis_descr = value; }
}
private string z_axis_descr = string.Empty;
public string Z_axis_descr
{
get { return z_axis_descr; }
set { z_axis_descr = value; }
}
private byte[] m_map_content;
public byte[] Map_content
{
get { return m_map_content; }
set
{
m_map_content = value;
}
}
private byte[] m_map_original_content;
public byte[] Map_original_content
{
get { return m_map_original_content; }
set
{
m_map_original_content = value;
}
}
private byte[] m_map_compare_content;
public byte[] Map_compare_content
{
get { return m_map_compare_content; }
set
{
m_map_compare_content = value;
}
}
private bool m_isUpsideDown = false;
public bool IsUpsideDown
{
get { return m_isUpsideDown; }
set { m_isUpsideDown = value; }
}
public void NormalizeData()
{
// omzetten naar datatable
// wat is de maximale waarde in de tabel?
int byteoffset = 0;
int maxvalue = 0;
if (m_isSixteenbit)
{
for (int tt = 0; tt < m_map_content.Length; tt += 2)
{
int valtot = 0;
valtot = Convert.ToInt32((byte)m_map_content.GetValue(byteoffset++)) * 256;
valtot += Convert.ToInt32((byte)m_map_content.GetValue(byteoffset++));
if (valtot > 0xF000)
{
valtot = 0x10000 - valtot;
valtot = -valtot;
}
if (m_map_name == "TargetAFR" || m_map_name == "FeedbackAFR" || m_map_name == "FeedbackvsTargetAFR" || m_map_name == "IdleTargetAFR" || m_map_name == "IdleFeedbackAFR" || m_map_name == "IdleFeedbackvsTargetAFR")
{
if (valtot > 200)
{
valtot = 256 - valtot;
valtot = -valtot;
}
}
if (valtot > maxvalue) maxvalue = valtot;
}
}
else
{
for (int tt = 0; tt < m_map_content.Length; tt++)
{
int valtot = Convert.ToInt32((byte)m_map_content.GetValue(byteoffset++));
if (valtot > maxvalue) maxvalue = valtot;
}
}
byteoffset = 0;
if (m_map_compare_content != null)
{
if (m_isSixteenbit)
{
for (int tt = 0; tt < m_map_compare_content.Length; tt += 2)
{
int valtot = 0;
valtot = Convert.ToInt32((byte)m_map_compare_content.GetValue(byteoffset++)) * 256;
valtot += Convert.ToInt32((byte)m_map_compare_content.GetValue(byteoffset++));
if (valtot > 0xF000)
{
valtot = 0x10000 - valtot;
valtot = -valtot;
}
if (m_map_name == "TargetAFR" || m_map_name == "FeedbackAFR" || m_map_name == "FeedbackvsTargetAFR" || m_map_name == "IdleTargetAFR" || m_map_name == "IdleFeedbackAFR" || m_map_name == "IdleFeedbackvsTargetAFR")
{
if (valtot > 200)
{
valtot = 256 - valtot;
valtot = -valtot;
}
}
if (valtot > maxvalue) maxvalue = valtot;
}
}
else
{
for (int tt = 0; tt < m_map_compare_content.Length; tt++)
{
int valtot = Convert.ToInt32((byte)m_map_compare_content.GetValue(byteoffset++));
if (valtot > maxvalue) maxvalue = valtot;
}
}
}
if (m_map_original_content != null)
{
byteoffset = 0;
if (m_isSixteenbit)
{
for (int tt = 0; tt < m_map_original_content.Length; tt += 2)
{
int valtot = 0;
valtot = Convert.ToInt32((byte)m_map_original_content.GetValue(byteoffset++)) * 256;
valtot += Convert.ToInt32((byte)m_map_original_content.GetValue(byteoffset++));
if (valtot > 0xF000)
{
valtot = 0x10000 - valtot;
valtot = -valtot;
}
if (m_map_name == "TargetAFR" || m_map_name == "FeedbackAFR" || m_map_name == "FeedbackvsTargetAFR" || m_map_name == "IdleTargetAFR" || m_map_name == "IdleFeedbackAFR" || m_map_name == "IdleFeedbackvsTargetAFR")
{
if (valtot > 200)
{
valtot = 256 - valtot;
valtot = -valtot;
}
}
if (valtot > maxvalue) maxvalue = valtot;
}
}
else
{
for (int tt = 0; tt < m_map_original_content.Length; tt++)
{
int valtot = Convert.ToInt32((byte)m_map_original_content.GetValue(byteoffset++));
if (valtot > maxvalue) maxvalue = valtot;
}
}
}
byteoffset = 0;
float percentagetoscale = (float)((double)m_numberOfColumns / (double)maxvalue);
sr.Correction_percentage = percentagetoscale;
m_mapdata = new DataTable();
m_mapcomparedata = new DataTable();
m_maporiginaldata = new DataTable();
for (int i = 0; i < m_numberOfColumns; i++)
{
m_mapdata.Columns.Add(i.ToString(), Type.GetType("System.Double"));
m_mapcomparedata.Columns.Add(i.ToString(), Type.GetType("System.Double"));
m_maporiginaldata.Columns.Add(i.ToString(), Type.GetType("System.Double"));
}
int numberofrows = m_map_length / m_numberOfColumns;
if (m_isSixteenbit) numberofrows /= 2;
byteoffset = 0;
for (int j = 0; j < numberofrows; j++)
{
object[] arr = new object[m_numberOfColumns];
for (int cc = 0; cc < m_numberOfColumns; cc++)
{
if (m_isSixteenbit)
{
double valtot = 0;
valtot = Convert.ToInt32((byte)m_map_content.GetValue(byteoffset++)) * 256;
valtot += Convert.ToInt32((byte)m_map_content.GetValue(byteoffset++));
if (valtot > 0xF000)
{
valtot = 0x10000 - valtot;
valtot = -valtot;
}
if (m_map_name == "TargetAFR" || m_map_name == "FeedbackAFR" || m_map_name == "FeedbackvsTargetAFR" || m_map_name == "IdleTargetAFR" || m_map_name == "IdleFeedbackAFR" || m_map_name == "IdleFeedbackvsTargetAFR")
{
if (valtot > 200)
{
valtot = 256 - valtot;
valtot = -valtot;
}
}
valtot *= percentagetoscale;
arr.SetValue((double)valtot, cc);
}
else
{
try
{
double valtot = 0;
valtot = Convert.ToDouble((byte)m_map_content.GetValue(byteoffset++));
valtot *= percentagetoscale;
arr.SetValue(valtot, cc);
}
catch (Exception E)
{
Console.WriteLine(E.Message);
}
}
}
if (!m_isUpsideDown)
{
m_mapdata.Rows.Add(arr);
}
else
{
System.Data.DataRow r = m_mapdata.NewRow();
r.ItemArray = arr;
m_mapdata.Rows.InsertAt(r, 0);
}
// moet insert op pos 0 zijn om te flippen!
/* if (m_isUpsideDown)
{
System.Data.DataRow r = dt.NewRow();
r.ItemArray = objarr;
dt.Rows.InsertAt(r, 0);
}
else
{
dt.Rows.Add(objarr);
}*/
}
// for original data
if (m_map_original_content != null)
{
byteoffset = 0;
for (int j = 0; j < numberofrows; j++)
{
object[] arr = new object[m_numberOfColumns];
for (int cc = 0; cc < m_numberOfColumns; cc++)
{
if (m_isSixteenbit)
{
double valtot = 0;
valtot = Convert.ToInt32((byte)m_map_original_content.GetValue(byteoffset++)) * 256;
valtot += Convert.ToInt32((byte)m_map_original_content.GetValue(byteoffset++));
if (valtot > 0xF000)
{
valtot = 0x10000 - valtot;
valtot = -valtot;
}
if (m_map_name == "TargetAFR" || m_map_name == "FeedbackAFR" || m_map_name == "FeedbackvsTargetAFR" || m_map_name == "IdleTargetAFR" || m_map_name == "IdleFeedbackAFR" || m_map_name == "IdleFeedbackvsTargetAFR")
{
if (valtot > 200)
{
valtot = 256 - valtot;
valtot = -valtot;
}
}
valtot *= percentagetoscale;
arr.SetValue((double)valtot, cc);
}
else
{
try
{
double valtot = 0;
valtot = Convert.ToDouble((byte)m_map_original_content.GetValue(byteoffset++));
valtot *= percentagetoscale;
arr.SetValue(valtot, cc);
}
catch (Exception E)
{
Console.WriteLine(E.Message);
}
}
}
if (!m_isUpsideDown)
{
m_maporiginaldata.Rows.Add(arr);
}
else
{
System.Data.DataRow r = m_maporiginaldata.NewRow();
r.ItemArray = arr;
m_maporiginaldata.Rows.InsertAt(r, 0);
}
}
}
// for compare data
if (m_map_compare_content != null)
{
byteoffset = 0;
for (int j = 0; j < numberofrows; j++)
{
object[] arr = new object[m_numberOfColumns];
for (int cc = 0; cc < m_numberOfColumns; cc++)
{
if (m_isSixteenbit)
{
double valtot = 0;
valtot = Convert.ToInt32((byte)m_map_compare_content.GetValue(byteoffset++)) * 256;
valtot += Convert.ToInt32((byte)m_map_compare_content.GetValue(byteoffset++));
if (valtot > 0xF000)
{
valtot = 0x10000 - valtot;
valtot = -valtot;
}
if (m_map_name == "TargetAFR" || m_map_name == "FeedbackAFR" || m_map_name == "FeedbackvsTargetAFR" || m_map_name == "IdleTargetAFR" || m_map_name == "IdleFeedbackAFR" || m_map_name == "IdleFeedbackvsTargetAFR")
{
if (valtot > 200)
{
valtot = 256 - valtot;
valtot = -valtot;
}
}
valtot *= percentagetoscale;
arr.SetValue((double)valtot, cc);
}
else
{
try
{
double valtot = 0;
valtot = Convert.ToDouble((byte)m_map_compare_content.GetValue(byteoffset++));
valtot *= percentagetoscale;
arr.SetValue(valtot, cc);
}
catch (Exception E)
{
Console.WriteLine(E.Message);
}
}
}
if (!m_isUpsideDown)
{
m_mapcomparedata.Rows.Add(arr);
}
else
{
System.Data.DataRow r = m_mapcomparedata.NewRow();
r.ItemArray = arr;
m_mapcomparedata.Rows.InsertAt(r, 0);
}
}
}
sr.Mapdata = m_mapdata;
sr.Mapcomparedata = m_mapcomparedata;
sr.Maporiginaldata = m_maporiginaldata;
sr.StartPoint = new PointF(0, 0);
sr.EndPoint = new PointF(m_mapdata.Columns.Count - 1, m_mapdata.Rows.Count - 1);
sr.X_axisvalues = x_axis;
sr.Y_axisvalues = y_axis;
sr.Xaxis_descr = x_axis_descr;
sr.Yaxis_descr = Y_axis_descr;
sr.Zaxis_descr = z_axis_descr;
//frmTableDebugger tabdebugger = new frmTableDebugger();
//tabdebugger.ShowTable(m_mapdata);
//tabdebugger.Show();
Invalidate();
}
private DataTable m_mapdata = new DataTable();
private DataTable m_mapcomparedata = new DataTable();
private DataTable m_maporiginaldata = new DataTable();
public DataTable Mapdata
{
get { return m_mapdata; }
set
{
m_mapdata = value;
sr.Mapdata = m_mapdata;
sr.StartPoint = new PointF(0, 0);
sr.EndPoint = new PointF(m_mapdata.Columns.Count - 1, m_mapdata.Rows.Count - 1);
Invalidate();
}
}
public delegate void GraphChangedEvent(object sender, GraphChangedEventArgs e);
public event SurfaceGraphViewer.GraphChangedEvent onGraphChanged;
private void CastGraphChangedEvent()
{
//pov_x, pov_y, pov_z, pan_x, pan_y,pov_d
if (onGraphChanged != null)
{
if (this.Visible)
{
onGraphChanged(this, new GraphChangedEventArgs(pov_x, pov_y, pov_z, pan_x, pan_y, pov_d));
}
}
}
public class GraphChangedEventArgs : System.EventArgs
{
//pov_x, pov_y, pov_z, pan_x, pan_y,pov_d
private int _pov_x;
public int Pov_x
{
get { return _pov_x; }
set { _pov_x = value; }
}
private int _pov_y;
public int Pov_y
{
get { return _pov_y; }
set { _pov_y = value; }
}
private int _pov_z;
public int Pov_z
{
get { return _pov_z; }
set { _pov_z = value; }
}
private int _pan_x;
public int Pan_x
{
get { return _pan_x; }
set { _pan_x = value; }
}
private int _pan_y;
public int Pan_y
{
get { return _pan_y; }
set { _pan_y = value; }
}
private double _pov_d;
public double Pov_d
{
get { return _pov_d; }
set { _pov_d = value; }
}
public GraphChangedEventArgs(int povx, int povy, int povz, int panx, int pany, double povd)
{
this._pan_x = panx;
this._pan_y = pany;
this._pov_d = povd;
this._pov_x = povx;
this._pov_y = povy;
this._pov_z = povz;
}
}
public void SetView(int povx, int povy, int povz, int panx, int pany, double povd)
{
this.pov_x = povx;
this.pov_y = povy;
this.pov_z = povz;
this.pan_x = panx;
this.pan_y = pany;
this.pov_d = povd;
sr.ReCalculateTransformationsCoeficients(pov_x, pov_y, pov_z, pan_x, pan_y, ClientRectangle.Width, ClientRectangle.Height, pov_d, 0, 0);
Invalidate();
}
private void SurfaceGraphMouseWheel(object sender, System.Windows.Forms.MouseEventArgs e)
{
int delta = e.Delta;
if(e.Delta > 0xff000000) delta = (int)(0x100000000- (long)delta);
pov_d += (delta * 0.0001);
sr.ReCalculateTransformationsCoeficients(pov_x, pov_y, pov_z, pan_x, pan_y, ClientRectangle.Width, ClientRectangle.Height, pov_d, 0, 0);
CastGraphChangedEvent();
Invalidate();
}
public SurfaceGraphViewer()
{
InitializeComponent();
this.MouseWheel += new System.Windows.Forms.MouseEventHandler(this.SurfaceGraphMouseWheel);
sr = new Surface3DRenderer(pov_x, pov_y, pov_z, pan_x, pan_y, ClientRectangle.Width, ClientRectangle.Height, pov_d, 0, 0);
sr.ColorSchema = new ColorSchema(0);
sr.Density = 1;
ResizeRedraw = true;
DoubleBuffered = true;
}
private void frm3DSurfaceGraphViewer_Paint(object sender, PaintEventArgs e)
{
e.Graphics.Clear(BackColor);
if (m_numberOfColumns == 1)
{
sr.RenderGraph(e.Graphics);
}
else
{
sr.RenderSurface(e.Graphics, m_lastMouseHoverPoint);
}
}
private void frm3DSurfaceGraphViewer_Resize(object sender, EventArgs e)
{
if (this.Visible)
{
if (sr != null)
{
sr.ReCalculateTransformationsCoeficients(pov_x, pov_y, pov_z, pan_x, pan_y, ClientRectangle.Width, ClientRectangle.Height, pov_d, 0, 0);
CastGraphChangedEvent();
}
}
}
private void frm3DSurfaceGraphViewer_MouseDown(object sender, MouseEventArgs e)
{
/*if (e.Button == MouseButtons.Left)
{
// rotate
this.Cursor = GenerateCursor("Turn");
}
else if (e.Button == MouseButtons.Right)
{
// pan
this.Cursor = GenerateCursor("Pan");
}
m_IsDragging = true;
m_p = e.Location;
//Invalidate();*/
double d = 0.0;
PointF p = new PointF();
bool b = sr.GetMousePoint(e.X, e.Y, out p, out d);
string s = b.ToString() + " | " + p.ToString() + " | " + d.ToString();
// if (b) System.Diagnostics.Debug.Write("\nMouseDown: " + s + "\n");
if (e.Button == MouseButtons.Left)
{
// rotate
this.Cursor = GenerateCursor("Turn");
}
else if (e.Button == MouseButtons.Right)
{
// pan
this.Cursor = GenerateCursor("Pan");
}
m_IsDragging = true;
m_p = e.Location;
}
private void frm3DSurfaceGraphViewer_MouseUp(object sender, MouseEventArgs e)
{
m_IsDragging = false;
this.Cursor = Cursors.Default;
}
private void frm3DSurfaceGraphViewer_MouseMove(object sender, MouseEventArgs e)
{
/*if (m_IsDragging)
{
if (e.Button == MouseButtons.Left)
{
int deltay = m_p.X - e.Location.X;
int deltax = m_p.Y - e.Location.Y;
//PointF f = sr.Project(0, 0, 0);
pov_y += deltay / 2;
pov_x -= deltay / 2;
//pov_z -= deltay / 2;
// pov_y += deltax / 2;
//int deltaz = m_p.Y - e.Location.Y;
pov_z -= deltax / 2;
}
// else if (e.Button == MouseButtons.Right)
//{
//int deltaz = m_p.Y - e.Location.Y;
//pov_z -= deltaz / 2;
//}
else if (e.Button == MouseButtons.Right)
{
int deltax = m_p.X - e.Location.X;
int deltay = m_p.Y - e.Location.Y;
pan_x -= deltax / 2;
pan_y -= deltay / 2;
}
sr.ReCalculateTransformationsCoeficients(pov_x, pov_y, pov_z, pan_x, pan_y, ClientRectangle.Width, ClientRectangle.Height, pov_d, 0, 0);
CastGraphChangedEvent();
Invalidate();
m_p = e.Location;
}
else
{
// waarden van punten weergeven als in de buurt
//PointF tableposition = new Point(0,0);
//double val = 0;
//if (sr.GetMousePoint(e.X, e.Y, out tableposition, out val))
//{
//Console.WriteLine("Position = " + e.X.ToString() + ":" + e.Y.ToString() + " tablepos = " + tableposition.X.ToString() + ":" + tableposition.Y.ToString() + " value = " + val.ToString());
// m_lastMouseHoverPoint = new PointF((float)e.X, (float)e.Y);
//toolTipController1.ShowHint("Mouse hit : " + m_lastMouseHoverPoint.X.ToString() + ":" + m_lastMouseHoverPoint.Y.ToString(), PointToClient(e.Location));
//}
}*/
if (m_IsDragging)
{
if (e.Button == MouseButtons.Left)
{
int deltay = m_p.X - e.Location.X;
int deltax = m_p.Y - e.Location.Y;
pov_y += deltay / 2;
pov_x -= deltay / 2;
pov_z -= deltax / 2;
}
else if (e.Button == MouseButtons.Right)
{
int deltax = m_p.X - e.Location.X;
int deltay = m_p.Y - e.Location.Y;
pan_x -= deltax / 2;
pan_y -= deltay / 2;
}
else if (e.Button == MouseButtons.Middle)
{
try
{
MapViewer mv = ((MapViewer)this.ParentForm.Controls.Find("MapViewer", true)[0]);
int pos = (lastPointY * this.Mapdata.Columns.Count) + lastPointX;
//TODO: make this work for 2 bytes maps as well (16 bits)
if (m_p.Y - e.Location.Y > 0)
{
if ((int)mv.Map_content[pos] != 255)
mv.Map_content[pos] = (byte)((int)mv.Map_content[pos] + 1);
}
else
{
if ((int)mv.Map_content[pos] != 0)
mv.Map_content[pos] = (byte)((int)mv.Map_content[pos] - 1);
}
// save user's xyz view of graph so we can set it back after the tableview "resets" the layout
int __pov_x = pov_x, __pov_y = pov_y, __pov_z = pov_z;
int __pan_x = pan_x, __pan_y = pan_y;
double __pov_d = pov_d;
// refresh datatable
mv.ReShowTable();
pov_x = __pov_x;
pov_y = __pov_y;
pov_d = __pov_d;
pan_x = __pan_x;
pan_y = __pan_y;
}
catch { }
}
}
else
{
double d = 0.0;
PointF p = new PointF();
bool b = sr.GetMousePoint(e.X, e.Y, out p, out d);
if (b && !m_IsDragging)
{
lastPointX = sr.Mapdata.Columns.Count - (int)p.Y - 1;
lastPointY = sr.Mapdata.Rows.Count - (int)p.X - 1;
sr.HighlightSelectionInGraph(lastPointX, lastPointY);
}
}
sr.ReCalculateTransformationsCoeficients(pov_x, pov_y, pov_z, pan_x, pan_y, ClientRectangle.Width, ClientRectangle.Height, pov_d, 0, 0);
CastGraphChangedEvent();
Invalidate();
m_p = e.Location;
}
int lastPointX = 0;
int lastPointY = 0;
private void SurfaceGraphViewer_DoubleClick(object sender, EventArgs e)
{
int hlpr = pov_x;
pov_x = pov_y;
pov_y =-hlpr;
sr.ReCalculateTransformationsCoeficients(pov_x, pov_y, pov_z, pan_x, pan_y, this.ClientRectangle.Width, this.ClientRectangle.Height, pov_d, 0, 0);
CastGraphChangedEvent();
Invalidate();
//frmTableDebugger tabdebugger = new frmTableDebugger();
//tabdebugger.ShowTable(m_mapdata);
//tabdebugger.Show();
}
private void SurfaceGraphViewer_Load(object sender, EventArgs e)
{
}
private void spinEdit1_ValueChanged(object sender, EventArgs e)
{
/* pov_x = Convert.ToInt32( spinEdit1.EditValue);
pov_y = Convert.ToInt32(spinEdit2.EditValue);
pov_z = Convert.ToInt32(spinEdit3.EditValue);
sr.ReCalculateTransformationsCoeficients(pov_x, pov_y, pov_z, pan_x, pan_y, this.ClientRectangle.Width, this.ClientRectangle.Height, pov_d, 0, 0);
CastGraphChangedEvent();
Invalidate();*/
}
private void spinEdit4_ValueChanged(object sender, EventArgs e)
{
/* pov_d = Convert.ToDouble(spinEdit4.EditValue);
sr.ReCalculateTransformationsCoeficients(pov_x, pov_y, pov_z, pan_x, pan_y, this.ClientRectangle.Width, this.ClientRectangle.Height, pov_d, 0, 0);
CastGraphChangedEvent();
Invalidate();*/
}
private void spinEdit5_EditValueChanged(object sender, EventArgs e)
{
/* sr.ColorSchema = new ColorSchema(Convert.ToDouble(spinEdit5.EditValue));
Invalidate();*/
}
private void SurfaceGraphViewer_Scroll(object sender, ScrollEventArgs e)
{
}
private Cursor GenerateCursor(string text)
{
Bitmap imgColor = new Bitmap(32, 32, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
Color color = Color.MidnightBlue;
SolidBrush brush = new SolidBrush(color);
SolidBrush brushMask = new SolidBrush(Color.White);
string s = text;
System.Drawing.Font fnt = new Font(FontFamily.GenericSerif, 10, FontStyle.Bold);
using (Graphics g = Graphics.FromImage(imgColor))
{
SizeF size = g.MeasureString(s, fnt);
if (size.Width > 32) size.Width = 32;
if (size.Height > 32) size.Height = 32;
g.FillRectangle(brushMask, 0, 0, 32, 32);
g.DrawString(s, fnt, brush, (32 - size.Width) / 2, (32 - size.Height) / 2);
g.Flush();
//g.DrawRectangle(Pens.OrangeRed, new Rectangle(1, 1, 30, 30));
}
imgColor.MakeTransparent(Color.White);
IconInfo ii = new IconInfo();
ii.fIcon = false;
ii.xHotspot = 16;
ii.yHotspot = 16;
ii.hbmMask = imgColor.GetHbitmap();
ii.hbmColor = imgColor.GetHbitmap();
unsafe
{
IntPtr iiPtr = new IntPtr(&ii);
IntPtr curPtr = CreateIconIndirect(iiPtr);
return new Cursor(curPtr);
}
}
private void SurfaceGraphViewer_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Add)
{
pov_d += 0.01;
sr.ReCalculateTransformationsCoeficients(pov_x, pov_y, pov_z, pan_x, pan_y, ClientRectangle.Width, ClientRectangle.Height, pov_d, 0, 0);
CastGraphChangedEvent();
Invalidate();
}
else if (e.KeyCode == Keys.Subtract)
{
pov_d -= 0.01;
sr.ReCalculateTransformationsCoeficients(pov_x, pov_y, pov_z, pan_x, pan_y, ClientRectangle.Width, ClientRectangle.Height, pov_d, 0, 0);
CastGraphChangedEvent();
Invalidate();
}
else if ((int)e.KeyCode == 104)
{
pan_y -= 10;
sr.ReCalculateTransformationsCoeficients(pov_x, pov_y, pov_z, pan_x, pan_y, ClientRectangle.Width, ClientRectangle.Height, pov_d, 0, 0);
CastGraphChangedEvent();
Invalidate();
}
else if ((int)e.KeyCode == 98)
{
pan_y += 10;
sr.ReCalculateTransformationsCoeficients(pov_x, pov_y, pov_z, pan_x, pan_y, ClientRectangle.Width, ClientRectangle.Height, pov_d, 0, 0);
CastGraphChangedEvent();
Invalidate();
}
else if ((int)e.KeyCode == 102)
{
pan_x += 10;
sr.ReCalculateTransformationsCoeficients(pov_x, pov_y, pov_z, pan_x, pan_y, ClientRectangle.Width, ClientRectangle.Height, pov_d, 0, 0);
CastGraphChangedEvent();
Invalidate();
}
else if ((int)e.KeyCode == 100)
{
pan_x -= 10;
sr.ReCalculateTransformationsCoeficients(pov_x, pov_y, pov_z, pan_x, pan_y, ClientRectangle.Width, ClientRectangle.Height, pov_d, 0, 0);
CastGraphChangedEvent();
Invalidate();
}
else if (e.KeyCode == Keys.Left)
{
pov_x -= 1;
pov_y += 1;
sr.ReCalculateTransformationsCoeficients(pov_x, pov_y, pov_z, pan_x, pan_y, ClientRectangle.Width, ClientRectangle.Height, pov_d, 0, 0);
CastGraphChangedEvent();
Invalidate();
}
else if (e.KeyCode == Keys.Right)
{
pov_x += 1;
pov_y -= 1;
sr.ReCalculateTransformationsCoeficients(pov_x, pov_y, pov_z, pan_x, pan_y, ClientRectangle.Width, ClientRectangle.Height, pov_d, 0, 0);
CastGraphChangedEvent();
Invalidate();
}
else if (e.KeyCode == Keys.Up)
{
pov_z -= 1;
sr.ReCalculateTransformationsCoeficients(pov_x, pov_y, pov_z, pan_x, pan_y, ClientRectangle.Width, ClientRectangle.Height, pov_d, 0, 0);
CastGraphChangedEvent();
Invalidate();
}
else if (e.KeyCode == Keys.Down)
{
pov_z += 1;
sr.ReCalculateTransformationsCoeficients(pov_x, pov_y, pov_z, pan_x, pan_y, ClientRectangle.Width, ClientRectangle.Height, pov_d, 0, 0);
CastGraphChangedEvent();
Invalidate();
}
}
private void SurfaceGraphViewer_KeyPress(object sender, KeyPressEventArgs e)
{
}
public void ZoomIn()
{
pov_d += 0.01;
sr.ReCalculateTransformationsCoeficients(pov_x, pov_y, pov_z, pan_x, pan_y, ClientRectangle.Width, ClientRectangle.Height, pov_d, 0, 0);
CastGraphChangedEvent();
Invalidate();
}
public void ZoomOut()
{
pov_d -= 0.01;
sr.ReCalculateTransformationsCoeficients(pov_x, pov_y, pov_z, pan_x, pan_y, ClientRectangle.Width, ClientRectangle.Height, pov_d, 0, 0);
CastGraphChangedEvent();
Invalidate();
}
public void TurnLeft()
{
pov_x += 1;
pov_y -= 1;
sr.ReCalculateTransformationsCoeficients(pov_x, pov_y, pov_z, pan_x, pan_y, ClientRectangle.Width, ClientRectangle.Height, pov_d, 0, 0);
CastGraphChangedEvent();
Invalidate();
}
public void TurnRight()
{
pov_x -= 1;
pov_y += 1;
sr.ReCalculateTransformationsCoeficients(pov_x, pov_y, pov_z, pan_x, pan_y, ClientRectangle.Width, ClientRectangle.Height, pov_d, 0, 0);
CastGraphChangedEvent();
Invalidate();
}
public void RefreshView()
{
sr.ReCalculateTransformationsCoeficients(pov_x, pov_y, pov_z, pan_x, pan_y, ClientRectangle.Width, ClientRectangle.Height, pov_d, 0, 0);
Invalidate();
}
private int m_tpsindex = -1;
private int m_rpmindex = -1;
internal void HighlightInGraph(int tpsindex, int rpmindex)
{
if (tpsindex < 0 || rpmindex < 0)
{
sr.ClearHighlightInGraph();
m_tpsindex = -1;
m_rpmindex = -1;
}
if (tpsindex != m_tpsindex || rpmindex != m_rpmindex)
{
m_rpmindex = rpmindex;
m_tpsindex = tpsindex;
sr.HighlightInGraph(tpsindex, rpmindex);
RefreshView();
}
}
private int m_tpsselectionindex = -1;
private int m_rpmselectionindex = -1;
internal void HighlightSelectionInGraph(int tpsindex, int rpmindex)
{
if (tpsindex < 0 || rpmindex < 0)
{
sr.ClearSelectionHighlightInGraph();
m_tpsselectionindex = -1;
m_rpmselectionindex = -1;
}
if (tpsindex != m_tpsselectionindex || rpmindex != m_rpmselectionindex)
{
m_rpmselectionindex = rpmindex;
m_tpsselectionindex = tpsindex;
sr.HighlightSelectionInGraph(tpsindex, rpmindex);
RefreshView();
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
namespace Microsoft.DotNet.Build.Tasks
{
/// <summary>
/// Resolves the assets out of packages in the project.lock.json
/// </summary>
public sealed class PrereleaseResolveNuGetPackageAssets : Task
{
internal const string NuGetPackageIdMetadata = "NuGetPackageId";
internal const string NuGetPackageVersionMetadata = "NuGetPackageVersion";
internal const string ReferenceImplementationMetadata = "Implementation";
internal const string ReferenceImageRuntimeMetadata = "ImageRuntime";
internal const string ReferenceWinMDFileMetadata = "WinMDFile";
internal const string ReferenceWinMDFileTypeMetadata = "WinMDFileType";
internal const string WinMDFileTypeManaged = "Managed";
internal const string WinMDFileTypeNative = "Native";
internal const string NuGetAssetTypeCompile = "compile";
internal const string NuGetAssetTypeNative = "native";
internal const string NuGetAssetTypeRuntime = "runtime";
internal const string NuGetAssetTypeResource = "resource";
private readonly List<ITaskItem> _analyzers = new List<ITaskItem>();
private readonly List<ITaskItem> _copyLocalItems = new List<ITaskItem>();
private readonly List<ITaskItem> _references = new List<ITaskItem>();
private readonly List<ITaskItem> _referencedPackages = new List<ITaskItem>();
#region UnitTestSupport
private readonly DirectoryExists _directoryExists = new DirectoryExists(Directory.Exists);
private readonly FileExists _fileExists = new FileExists(File.Exists);
private readonly TryGetRuntimeVersion _tryGetRuntimeVersion = new TryGetRuntimeVersion(TryGetRuntimeVersion);
internal PrereleaseResolveNuGetPackageAssets(DirectoryExists directoryExists, FileExists fileExists, TryGetRuntimeVersion tryGetRuntimeVersion)
: this()
{
if (directoryExists != null)
{
_directoryExists = directoryExists;
}
if (fileExists != null)
{
_fileExists = fileExists;
}
if (tryGetRuntimeVersion != null)
{
_tryGetRuntimeVersion = tryGetRuntimeVersion;
}
}
#endregion
/// <summary>
/// Creates a new <see cref="PrereleaseResolveNuGetPackageAssets"/>.
/// </summary>
public PrereleaseResolveNuGetPackageAssets()
{
Log.TaskResources = Strings.ResourceManager;
}
/// <summary>
/// The full paths to resolved analyzers.
/// </summary>
[Output]
public ITaskItem[] ResolvedAnalyzers
{
get { return _analyzers.ToArray(); }
}
/// <summary>
/// The full paths to resolved run-time resources.
/// </summary>
[Output]
public ITaskItem[] ResolvedCopyLocalItems
{
get { return _copyLocalItems.ToArray(); }
}
/// <summary>
/// The full paths to resolved build-time dependencies. Contains standard metadata for Reference items.
/// </summary>
[Output]
public ITaskItem[] ResolvedReferences
{
get { return _references.ToArray(); }
}
/// <summary>
/// The names of NuGet packages directly referenced by this project.
/// </summary>
[Output]
public ITaskItem[] ReferencedPackages
{
get { return _referencedPackages.ToArray(); }
}
/// <summary>
/// The target monikers to use when selecting assets from packages. The first one found in the lock file is used.
/// </summary>
[Required]
public ITaskItem[] TargetMonikers
{
get; set;
}
[Required]
public string ProjectLockFile
{
get; set;
}
public string NuGetPackagesDirectory
{
get; set;
}
public string RuntimeIdentifier
{
get; set;
}
public bool AllowFallbackOnTargetSelection
{
get; set;
}
public string ProjectLanguage
{
get; set;
}
public bool IncludeFrameworkReferences
{
get; set;
}
/// <summary>
/// Performs the NuGet package resolution.
/// </summary>
public override bool Execute()
{
try
{
ExecuteCore();
return true;
}
catch (ExceptionFromResource e)
{
Log.LogErrorFromResources(e.ResourceName, e.MessageArgs);
return false;
}
catch (Exception e)
{
Log.LogErrorFromException(e);
return false;
}
}
private void ExecuteCore()
{
if (!_fileExists(ProjectLockFile))
{
throw new ExceptionFromResource("LockFileNotFound", ProjectLockFile);
}
JObject lockFile;
using (var streamReader = new StreamReader(ProjectLockFile))
{
lockFile = JObject.Load(new JsonTextReader(streamReader));
}
GetReferences(lockFile);
GetCopyLocalItems(lockFile);
GetAnalyzers(lockFile);
GetReferencedPackages(lockFile);
}
private void GetReferences(JObject lockFile)
{
var target = GetTargetOrAttemptFallback(lockFile, needsRuntimeIdentifier: false);
var frameworkReferences = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var fileNamesOfRegularReferences = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var package in target)
{
var packageNameParts = package.Key.Split('/');
var packageName = packageNameParts[0];
var packageVersion = packageNameParts[1];
Log.LogMessageFromResources(MessageImportance.Low, "ResolvedReferencesFromPackage", packageName);
foreach (var referenceItem in CreateItems(packageName, packageVersion, package.Value, NuGetAssetTypeCompile))
{
_references.Add(referenceItem);
fileNamesOfRegularReferences.Add(Path.GetFileNameWithoutExtension(referenceItem.ItemSpec));
}
if (IncludeFrameworkReferences)
{
var frameworkAssembliesArray = package.Value["frameworkAssemblies"] as JArray;
if (frameworkAssembliesArray != null)
{
foreach (var frameworkAssembly in frameworkAssembliesArray.OfType<JToken>())
{
frameworkReferences.Add((string)frameworkAssembly);
}
}
}
}
foreach (var frameworkReference in frameworkReferences.Except(fileNamesOfRegularReferences, StringComparer.OrdinalIgnoreCase))
{
_references.Add(new TaskItem(frameworkReference));
}
}
private void GetCopyLocalItems(JObject lockFile)
{
// If we have no runtime identifier, we're not copying implementations
if (string.IsNullOrEmpty(RuntimeIdentifier))
{
return;
}
// We'll use as a fallback just the target moniker if the user didn't have the right runtime identifier in their lock file.
var target = GetTargetOrAttemptFallback(lockFile, needsRuntimeIdentifier: true);
HashSet<string> candidateNativeImplementations = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
List<ITaskItem> runtimeWinMDItems = new List<ITaskItem>();
foreach (var package in target)
{
var packageNameParts = package.Key.Split('/');
var packageName = packageNameParts[0];
var packageVersion = packageNameParts[1];
Log.LogMessageFromResources(MessageImportance.Low, "ResolvedReferencesFromPackage", packageName);
foreach(var nativeItem in CreateItems(packageName, packageVersion, package.Value, NuGetAssetTypeNative))
{
if (Path.GetExtension(nativeItem.ItemSpec).Equals(".dll", StringComparison.OrdinalIgnoreCase))
{
candidateNativeImplementations.Add(Path.GetFileNameWithoutExtension(nativeItem.ItemSpec));
}
_copyLocalItems.Add(nativeItem);
}
foreach (var runtimeItem in CreateItems(packageName, packageVersion, package.Value, NuGetAssetTypeRuntime))
{
if (Path.GetExtension(runtimeItem.ItemSpec).Equals(".winmd", StringComparison.OrdinalIgnoreCase))
{
runtimeWinMDItems.Add(runtimeItem);
}
_copyLocalItems.Add(runtimeItem);
}
foreach (var resourceItem in CreateItems(packageName, packageVersion, package.Value, NuGetAssetTypeResource))
{
_copyLocalItems.Add(resourceItem);
}
}
SetWinMDMetadata(runtimeWinMDItems, candidateNativeImplementations);
}
private void GetAnalyzers(JObject lockFile)
{
// For analyzers, analyzers could be provided in runtime implementation packages. This might be reasonable -- imagine a gatekeeper
// scenario where somebody has a library but on .NET Native might have some specific restrictions that need to be enforced.
var target = GetTargetOrAttemptFallback(lockFile, needsRuntimeIdentifier: !string.IsNullOrEmpty(RuntimeIdentifier));
var libraries = (JObject)lockFile["libraries"];
foreach (var package in target.Children())
{
var name = (package is JProperty) ? ((JProperty)package).Name : null;
var packageNameParts = name != null ? name.Split('/') : null;
if (packageNameParts == null)
{
continue;
}
var packageId = packageNameParts[0];
var packageVersion = packageNameParts[1];
var librariesPackage = libraries[name];
foreach (var file in librariesPackage["files"].Children()
.Select(x => x.ToString())
.Where(x => x.StartsWith("analyzers")))
{
if (Path.GetExtension(file).Equals(".dll", StringComparison.OrdinalIgnoreCase))
{
string path;
if (TryGetFile(packageId, packageVersion, file, out path))
{
var analyzer = new TaskItem(path);
analyzer.SetMetadata(NuGetPackageIdMetadata, packageId);
analyzer.SetMetadata(NuGetPackageVersionMetadata, packageVersion);
_analyzers.Add(analyzer);
}
}
}
}
}
private void SetWinMDMetadata(IEnumerable<ITaskItem> runtimeWinMDs, ICollection<string> candidateImplementations)
{
foreach(var winMD in runtimeWinMDs.Where(w => _fileExists(w.ItemSpec)))
{
string imageRuntimeVersion = _tryGetRuntimeVersion(winMD.ItemSpec);
if (String.IsNullOrEmpty(imageRuntimeVersion))
continue;
// RAR sets ImageRuntime for everything but the only dependencies we're aware of are
// for WinMDs
winMD.SetMetadata(ReferenceImageRuntimeMetadata, imageRuntimeVersion);
bool isWinMD, isManaged;
TryParseRuntimeVersion(imageRuntimeVersion, out isWinMD, out isManaged);
if (isWinMD)
{
winMD.SetMetadata(ReferenceWinMDFileMetadata, "true");
if (isManaged)
{
winMD.SetMetadata(ReferenceWinMDFileTypeMetadata, WinMDFileTypeManaged);
}
else
{
winMD.SetMetadata(ReferenceWinMDFileTypeMetadata, WinMDFileTypeNative);
// Normally RAR will expect the native DLL to be next to the WinMD, but that doesn't
// work well for nuget packages since compile time assets cannot be architecture specific.
// We also explicitly set all compile time assets to not copy local so we need to
// make sure that this metadata is set on the runtime asset.
// Examine all runtime assets that are native winmds and add Implementation metadata
// We intentionally permit this to cross package boundaries to support cases where
// folks want to split their architecture specific implementations into runtime
// specific packages.
// Sample layout
// lib\netcore50\Contoso.Controls.winmd
// lib\netcore50\Contoso.Controls.xml
// runtimes\win10-arm\native\Contoso.Controls.dll
// runtimes\win10-x64\native\Contoso.Controls.dll
// runtimes\win10-x86\native\Contoso.Controls.dll
string fileName = Path.GetFileNameWithoutExtension(winMD.ItemSpec);
// determine if we have a Native WinMD that could be satisfied by this native dll.
if (candidateImplementations.Contains(fileName))
{
winMD.SetMetadata(ReferenceImplementationMetadata, fileName + ".dll");
}
}
}
}
}
private bool TryGetFile(string packageName, string packageVersion, string file, out string path)
{
if (IsFileValid(file, "C#", "VB"))
{
path = GetPath(packageName, packageVersion, file);
return true;
}
else if (IsFileValid(file, "VB", "C#"))
{
path = GetPath(packageName, packageVersion, file);
return true;
}
path = null;
return false;
}
private bool IsFileValid(string file, string expectedLanguage, string unExpectedLanguage)
{
var expectedProjectLanguage = expectedLanguage;
expectedLanguage = expectedLanguage == "C#" ? "cs" : expectedLanguage;
unExpectedLanguage = unExpectedLanguage == "C#" ? "cs" : unExpectedLanguage;
return (ProjectLanguage.Equals(expectedProjectLanguage, StringComparison.OrdinalIgnoreCase)) &&
(file.Split('/').Any(x => x.Equals(ProjectLanguage, StringComparison.OrdinalIgnoreCase)) ||
!file.Split('/').Any(x => x.Equals(unExpectedLanguage, StringComparison.OrdinalIgnoreCase)));
}
private string GetPath(string packageName, string packageVersion, string file)
{
return Path.Combine(GetNuGetPackagePath(packageName, packageVersion), file.Replace('/', '\\'));
}
/// <summary>
/// Fetches the right target from the targets section in a lock file, or attempts to find a "best match" if allowed. The "best match" logic
/// is there to allow a design time build for the IDE to generally work even if something isn't quite right. Throws an exception
/// if either the preferred isn't there and fallbacks aren't allowed, or fallbacks are allowed but nothing at all could be found.
/// </summary>
/// <param name="lockFile">The lock file JSON.</param>
/// <param name="needsRuntimeIdentifier">Whether we must find targets that include the runtime identifier or one without the runtime identifier.</param>
private JObject GetTargetOrAttemptFallback(JObject lockFile, bool needsRuntimeIdentifier)
{
var targets = (JObject)lockFile["targets"];
foreach (var preferredTargetMoniker in TargetMonikers)
{
var preferredTargetMonikerWithOptionalRuntimeIdentifier = GetTargetMonikerWithOptionalRuntimeIdentifier(preferredTargetMoniker, needsRuntimeIdentifier);
var target = (JObject)targets[preferredTargetMonikerWithOptionalRuntimeIdentifier];
if (target != null)
{
return target;
}
}
var preferredForErrorMessages = GetTargetMonikerWithOptionalRuntimeIdentifier(TargetMonikers.First(), needsRuntimeIdentifier);
if (!AllowFallbackOnTargetSelection)
{
// If we're not falling back then abort the build
throw new ExceptionFromResource("MissingEntryInLockFile", preferredForErrorMessages);
}
// We are allowing fallback, so we'll still give a warning but allow us to continue
// In production ResolveNuGetPackageAssets, this call is LogWarningFromResources.
// In our current use in dotnet\buildtools, we rely on the fallback behavior, so we just log
// this as a message.
Log.LogMessageFromResources("MissingEntryInLockFile", preferredForErrorMessages);
foreach (var fallback in TargetMonikers)
{
var target = (JObject)targets[GetTargetMonikerWithOptionalRuntimeIdentifier(fallback, needsRuntimeIdentifier: false)];
if (target != null)
{
return target;
}
}
// Anything goes
var enumerableTargets = targets.Cast<KeyValuePair<string, JToken>>();
var firstTarget = (JObject)enumerableTargets.FirstOrDefault().Value;
if (firstTarget == null)
{
throw new ExceptionFromResource("NoTargetsInLockFile");
}
return firstTarget;
}
private string GetTargetMonikerWithOptionalRuntimeIdentifier(ITaskItem preferredTargetMoniker, bool needsRuntimeIdentifier)
{
return needsRuntimeIdentifier ? preferredTargetMoniker.ItemSpec + "/" + RuntimeIdentifier : preferredTargetMoniker.ItemSpec;
}
private IEnumerable<ITaskItem> CreateItems(string packageId, string packageVersion, JToken packageObject, string key)
{
var values = packageObject[key] as JObject;
var items = new List<ITaskItem>();
if (values == null)
{
return items;
}
var nugetPackage = GetNuGetPackagePath(packageId, packageVersion);
foreach (string file in values.Properties().Select(p => p.Name))
{
if (Path.GetFileName(file) == "_._")
{
continue;
}
var sanitizedFile = file.Replace('/', '\\');
var nugetPath = Path.Combine(nugetPackage, sanitizedFile);
var item = new TaskItem(nugetPath);
item.SetMetadata(NuGetPackageIdMetadata, packageId);
item.SetMetadata(NuGetPackageVersionMetadata, packageVersion);
item.SetMetadata("Private", "false");
string targetPath = TryGetTargetPath(sanitizedFile);
if (targetPath != null)
{
var destinationSubDirectory = Path.GetDirectoryName(targetPath);
if (!string.IsNullOrEmpty(destinationSubDirectory))
{
item.SetMetadata("DestinationSubDirectory", destinationSubDirectory + "\\");
}
item.SetMetadata("TargetPath", targetPath);
}
items.Add(item);
}
return items;
}
private static string TryGetTargetPath(string file)
{
var foldersAndFile = file.Split('\\').ToArray();
for (int i = foldersAndFile.Length - 1; i > -1; i--)
{
if (CultureStringUtilities.IsValidCultureString(foldersAndFile[i]))
{
return Path.Combine(foldersAndFile.Skip(i).ToArray());
}
}
// There is no culture-specific directory, so it'll go in the root
return null;
}
private void GetReferencedPackages(JObject lockFile)
{
var projectFileDependencyGroups = (JObject)lockFile["projectFileDependencyGroups"];
var projectFileDependencies = (JArray)projectFileDependencyGroups[""];
foreach (var packageDependency in projectFileDependencies.Select(v => (string)v))
{
int firstSpace = packageDependency.IndexOf(' ');
if (firstSpace > -1)
{
_referencedPackages.Add(new TaskItem(packageDependency.Substring(0, firstSpace)));
}
}
}
private sealed class ExceptionFromResource : Exception
{
public string ResourceName { get; private set; }
public object[] MessageArgs { get; private set; }
public ExceptionFromResource(string resourceName, params object[] messageArgs)
{
ResourceName = resourceName;
MessageArgs = messageArgs;
}
}
private string GetNuGetPackagePath(string packageId, string packageVersion)
{
string packagesFolder = GetNuGetPackagesPath();
string packagePath = Path.Combine(packagesFolder, packageId, packageVersion);
if (!_directoryExists(packagePath))
{
throw new ExceptionFromResource("PackageFolderNotFound", packageId, packageVersion, packagesFolder);
}
return packagePath;
}
private string GetNuGetPackagesPath()
{
if (!string.IsNullOrEmpty(NuGetPackagesDirectory))
{
return NuGetPackagesDirectory;
}
string packagesFolder = Environment.GetEnvironmentVariable("NUGET_PACKAGES");
if (!string.IsNullOrEmpty(packagesFolder))
{
return packagesFolder;
}
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".nuget", "packages");
}
/// <summary>
/// Parse the imageRuntimeVersion from COR header
/// </summary>
private void TryParseRuntimeVersion(string imageRuntimeVersion, out bool isWinMD, out bool isManaged)
{
if (!String.IsNullOrEmpty(imageRuntimeVersion))
{
isWinMD = imageRuntimeVersion.IndexOf("WindowsRuntime", StringComparison.OrdinalIgnoreCase) >= 0;
isManaged = imageRuntimeVersion.IndexOf("CLR", StringComparison.OrdinalIgnoreCase) >= 0;
}
else
{
isWinMD = isManaged = false;
}
}
/// <summary>
/// Given a path get the CLR runtime version of the file
/// </summary>
/// <param name="path">path to the file</param>
/// <returns>The CLR runtime version or empty if the path does not exist.</returns>
private static string TryGetRuntimeVersion(string path)
{
StringBuilder runtimeVersion = null;
uint hresult = 0;
uint actualBufferSize = 0;
int bufferLength = 11; // 11 is the length of a runtime version and null terminator v2.0.50727/0
do
{
runtimeVersion = new StringBuilder(bufferLength);
hresult = NativeMethods.GetFileVersion(path, runtimeVersion, bufferLength, out actualBufferSize);
bufferLength = bufferLength * 2;
} while (hresult == NativeMethods.ERROR_INSUFFICIENT_BUFFER);
if (hresult == NativeMethods.S_OK && runtimeVersion != null)
{
return runtimeVersion.ToString();
}
else
{
return String.Empty;
}
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// 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.Management.Automation;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using System.Xml;
using Microsoft.Azure.Commands.RecoveryServices.SiteRecovery.Properties;
using Microsoft.Azure.Commands.ResourceManager.Common;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Job = Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models.Job;
namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery
{
/// <summary>
/// The base class for all Windows Azure Recovery Services commands
/// </summary>
public abstract class SiteRecoveryCmdletBase : AzureRMCmdlet
{
/// <summary>
/// Recovery Services client.
/// </summary>
private PSRecoveryServicesClient recoveryServicesClient;
/// <summary>
/// Recovery Services client.
/// </summary>
private PSAsrComputeManagementClient computeManagementClient;
/// <summary>
/// Gets or sets a value indicating whether stop processing has been triggered.
/// </summary>
internal bool StopProcessingFlag { get; set; }
/// <summary>
/// Gets Recovery Services client.
/// </summary>
internal PSRecoveryServicesClient RecoveryServicesClient
{
get
{
if (this.recoveryServicesClient == null)
{
this.recoveryServicesClient = new PSRecoveryServicesClient(this.DefaultProfile);
}
return this.recoveryServicesClient;
}
}
internal PSAsrComputeManagementClient ComputeManagementClient
{
get
{
if (this.computeManagementClient == null)
{
this.computeManagementClient = new PSAsrComputeManagementClient(this.DefaultProfile);
}
return this.computeManagementClient;
}
}
/// <summary>
/// Overriding base implementation go execute cmdlet.
/// </summary>
public override void ExecuteCmdlet()
{
try
{
base.ExecuteCmdlet();
this.ExecuteSiteRecoveryCmdlet();
}
catch (Exception ex)
{
this.HandleException(ex);
}
}
/// <summary>
/// Virtual method to be implemented by Site Recovery cmdlets.
/// </summary>
public virtual void ExecuteSiteRecoveryCmdlet()
{
// Do Nothing
}
/// <summary>
/// Exception handler.
/// </summary>
/// <param name="ex">Exception to handle.</param>
public void HandleException(
Exception ex)
{
var clientRequestIdMsg = string.Empty;
if (this.recoveryServicesClient != null)
{
clientRequestIdMsg = "ClientRequestId: " +
this.recoveryServicesClient.ClientRequestId +
"\n";
}
var cloudException = ex as CloudException;
if ((cloudException != null) &&
(cloudException.Body != null) &&
(cloudException.Response != null))
{
try
{
if (cloudException.Message != null)
{
var error =
SafeJsonConvert.DeserializeObject<ARMError>(
cloudException.Response.Content);
;
var exceptionMessage = new StringBuilder();
exceptionMessage.Append(Resources.CloudExceptionDetails);
if (error.Error.Details != null)
{
foreach (var detail in error.Error.Details)
{
if (!string.IsNullOrEmpty(detail.ErrorCode))
exceptionMessage.AppendLine("ErrorCode: " + detail.ErrorCode);
if (!string.IsNullOrEmpty(detail.Message))
exceptionMessage.AppendLine("Message: " + detail.Message);
if (!string.IsNullOrEmpty(detail.PossibleCauses))
exceptionMessage.AppendLine(
"Possible Causes: " + detail.PossibleCauses);
if (!string.IsNullOrEmpty(detail.RecommendedAction))
exceptionMessage.AppendLine(
"Recommended Action: " + detail.RecommendedAction);
if (!string.IsNullOrEmpty(detail.ClientRequestId))
exceptionMessage.AppendLine(
"ClientRequestId: " + detail.ClientRequestId);
if (!string.IsNullOrEmpty(detail.ActivityId))
exceptionMessage.AppendLine("ActivityId: " + detail.ActivityId);
exceptionMessage.AppendLine();
}
}
else
{
if (!string.IsNullOrEmpty(error.Error.ErrorCode))
exceptionMessage.AppendLine("ErrorCode: " + error.Error.ErrorCode);
if (!string.IsNullOrEmpty(error.Error.Message))
exceptionMessage.AppendLine("Message: " + error.Error.Message);
}
throw new InvalidOperationException(exceptionMessage.ToString());
}
throw new Exception(
string.Format(
Resources.InvalidCloudExceptionErrorMessage,
clientRequestIdMsg + ex.Message),
ex);
}
catch (XmlException)
{
throw new XmlException(
string.Format(
Resources.InvalidCloudExceptionErrorMessage,
cloudException.Message),
cloudException);
}
catch (SerializationException)
{
throw new SerializationException(
string.Format(
Resources.InvalidCloudExceptionErrorMessage,
clientRequestIdMsg + cloudException.Message),
cloudException);
}
catch (JsonReaderException)
{
throw new JsonReaderException(
string.Format(
Resources.InvalidCloudExceptionErrorMessage,
clientRequestIdMsg + cloudException.Message),
cloudException);
}
}
if (ex.Message != null)
{
throw new Exception(
string.Format(
Resources.InvalidCloudExceptionErrorMessage,
clientRequestIdMsg + ex.Message),
ex);
}
}
/// <summary>
/// Waits for the job to complete.
/// </summary>
/// <param name="jobId">Id of the job to wait for.</param>
/// <returns>Final job response</returns>
public Job WaitForJobCompletion(
string jobId)
{
Job job = null;
do
{
Thread.Sleep(PSRecoveryServicesClient.TimeToSleepBeforeFetchingJobDetailsAgain);
job = this.RecoveryServicesClient.GetAzureSiteRecoveryJobDetails(jobId);
this.WriteProgress(
new ProgressRecord(
0,
Resources.WaitingForCompletion,
job.Properties.State));
}
while (!((job.Properties.State == TaskStatus.Cancelled) ||
(job.Properties.State == TaskStatus.Failed) ||
(job.Properties.State == TaskStatus.Suspended) ||
(job.Properties.State == TaskStatus.Succeeded) ||
this.StopProcessingFlag));
return job;
}
/// <summary>
/// Handles interrupts.
/// </summary>
protected override void StopProcessing()
{
// Ctrl + C and etc
base.StopProcessing();
this.StopProcessingFlag = true;
}
/// <summary>
/// Validates if the usage by ID is allowed or not.
/// </summary>
/// <param name="replicationProvider">Replication provider.</param>
/// <param name="paramName">Parameter name.</param>
protected void ValidateUsageById(
string replicationProvider,
string paramName)
{
if (replicationProvider != Constants.HyperVReplica2012)
{
throw new Exception(
string.Format(
"Call using ID based parameter {0} is not supported for this provider. Please use its corresponding full object parameter instead",
paramName));
}
this.WriteWarningWithTimestamp(
string.Format(
Resources.IDBasedParamUsageNotSupportedFromNextRelease,
paramName));
}
}
}
| |
// SharpMath - C# Mathematical Library
// Copyright (c) 2014 Morten Bakkedal
// This code is published under the MIT License.
using System;
namespace SharpMath.Optimization.DualNumbers
{
/// <summary>
/// Computes the inverse of a <see cref="DualMatrix" /> by keeping track of the gradient and Hessian throughout the Cholesky decomposition.
/// </summary>
public sealed class DualCholeskyDecomposition
{
private DualCholeskyDecomposition()
{
}
public static void InverseDeterminant(DualMatrix matrix, out DualMatrix inverse, out DualNumber determinant)
{
int n = matrix.Rows;
if (matrix.Columns != n)
{
throw new ArgumentException("The matrix is not a square matrix.");
}
DualNumber[,] a = matrix.ToArray();
if (!spdmatrixcholesky(ref a, n, false))
{
throw new ArithmeticException();
}
determinant = spdmatrixcholeskydet(ref a, n);
int info = 0;
spdmatrixcholeskyinverse(ref a, n, false, ref info);
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
a[i, j] = a[j, i];
}
}
inverse = new DualMatrix(a);
}
public static DualMatrix Inverse(DualMatrix matrix)
{
int n = matrix.Rows;
if (matrix.Columns != n)
{
throw new ArgumentException("The matrix is not a square matrix.");
}
DualNumber[,] a = matrix.ToArray();
int info = 0;
spdmatrixinverse(ref a, n, false, ref info);
if (info != 1)
{
throw new ArithmeticException();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
a[i, j] = a[j, i];
}
}
return new DualMatrix(a);
}
/*************************************************************************
Copyright (c) 2005-2007, Sergey Bochkanov (ALGLIB project).
>>> SOURCE LICENSE >>>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation (www.fsf.org); either version 2 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
A copy of the GNU General Public License is available at
http://www.fsf.org/licensing/licenses
>>> END OF LICENSE >>>
*************************************************************************/
private static DualNumber spdmatrixdet(DualNumber[,] a, int n, bool isupper)
{
DualNumber result = 0;
a = (DualNumber[,])a.Clone();
if (!spdmatrixcholesky(ref a, n, isupper))
{
result = -1;
}
else
{
result = spdmatrixcholeskydet(ref a, n);
}
return result;
}
private static void spdmatrixinverse(ref DualNumber[,] a, int n, bool isupper, ref int info)
{
if (n < 1)
{
info = -1;
return;
}
info = 1;
if (spdmatrixcholesky(ref a, n, isupper))
{
spdmatrixcholeskyinverse(ref a, n, isupper, ref info);
}
else
{
info = -3;
}
}
private static DualNumber spdmatrixcholeskydet(ref DualNumber[,] a, int n)
{
DualNumber result = 0;
int i = 0;
result = 1;
for (i = 0; i <= n - 1; i++)
{
result = result * DualNumber.Sqr(a[i, i]);
}
return result;
}
private static bool spdmatrixcholesky(ref DualNumber[,] a, int n, bool isupper)
{
bool result = new bool();
DualNumber[] tmp = new DualNumber[0];
if (n < 1)
{
result = false;
return result;
}
tmp = new DualNumber[2 * n];
result = spdmatrixcholeskyrec(ref a, 0, n, isupper, ref tmp);
return result;
}
private static bool spdmatrixcholeskyrec(ref DualNumber[,] a, int offs, int n, bool isupper, ref DualNumber[] tmp)
{
bool result = new bool();
//int n1 = 0;
//int n2 = 0;
//
// check N
//
if (n < 1)
{
result = false;
return result;
}
//
// special cases
//
if (n == 1)
{
if (a[offs, offs].Value > 0.0)
{
a[offs, offs] = DualNumber.Sqrt(a[offs, offs]);
result = true;
}
else
{
result = false;
}
return result;
}
//if (n <= ablas.ablasblocksize(ref a))
{
result = spdmatrixcholesky2(ref a, offs, n, isupper, ref tmp);
return result;
}
}
private static bool spdmatrixcholesky2(ref DualNumber[,] aaa, int offs, int n, bool isupper, ref DualNumber[] tmp)
{
bool result = new bool();
int i = 0;
int j = 0;
//int k = 0;
//int j1 = 0;
//int j2 = 0;
DualNumber ajj = 0;
DualNumber v = 0;
//double r = 0;
int i_ = 0;
int i1_ = 0;
result = true;
if (n < 0)
{
result = false;
return result;
}
//
// Quick return if possible
//
if (n == 0)
{
return result;
}
if (isupper)
{
throw new NotImplementedException();
}
else
{
//
// Compute the Cholesky factorization A = L*L'.
//
for (j = 0; j <= n - 1; j++)
{
//
// Compute L(J+1,J+1) and test for non-positive-definiteness.
//
v = 0.0;
for (i_ = offs; i_ <= offs + j - 1; i_++)
{
v += aaa[offs + j, i_] * aaa[offs + j, i_];
}
ajj = aaa[offs + j, offs + j] - v;
if (ajj.Value <= 0.0)
{
aaa[offs + j, offs + j] = ajj;
result = false;
return result;
}
ajj = DualNumber.Sqrt(ajj);
aaa[offs + j, offs + j] = ajj;
//
// Compute elements J+1:N of column J.
//
if (j < n - 1)
{
if (j > 0)
{
i1_ = (offs) - (0);
for (i_ = 0; i_ <= j - 1; i_++)
{
tmp[i_] = aaa[offs + j, i_ + i1_];
}
rmatrixmv(n - j - 1, j, ref aaa, offs + j + 1, offs, 0, ref tmp, 0, ref tmp, n);
for (i = 0; i <= n - j - 2; i++)
{
aaa[offs + j + 1 + i, offs + j] = (aaa[offs + j + 1 + i, offs + j] - tmp[n + i]) / ajj;
}
}
else
{
for (i = 0; i <= n - j - 2; i++)
{
aaa[offs + j + 1 + i, offs + j] = aaa[offs + j + 1 + i, offs + j] / ajj;
}
}
}
}
}
return result;
}
private static void rmatrixmv(int m, int n, ref DualNumber[,] a, int ia, int ja, int opa, ref DualNumber[] x, int ix, ref DualNumber[] y, int iy)
{
int i = 0;
DualNumber v = 0;
int i_ = 0;
int i1_ = 0;
if (m == 0)
{
return;
}
if (n == 0)
{
for (i = 0; i <= m - 1; i++)
{
y[iy + i] = 0;
}
return;
}
//if (ablasf.rmatrixmvf(m, n, ref a, ia, ja, opa, ref x, ix, ref y, iy))
//{
// return;
//}
if (opa == 0)
{
//
// y = A*x
//
for (i = 0; i <= m - 1; i++)
{
i1_ = (ix) - (ja);
v = 0.0;
for (i_ = ja; i_ <= ja + n - 1; i_++)
{
v += a[ia + i, i_] * x[i_ + i1_];
}
y[iy + i] = v;
}
return;
}
if (opa == 1)
{
throw new NotImplementedException();
}
}
private static void spdmatrixcholeskyinverse(ref DualNumber[,] a, int n, bool isupper, ref int info)
{
//int i = 0;
//int j = 0;
//int k = 0;
//double v = 0;
//double ajj = 0;
//double aii = 0;
DualNumber[] tmp = new DualNumber[0];
//int info2 = 0;
//matinvreport rep2 = new matinvreport();
if (n < 1)
{
info = -1;
return;
}
info = 1;
//
// calculate condition numbers
//
//rep.r1 = rcond.spdmatrixcholeskyrcond(ref a, n, isupper);
//rep.rinf = rep.r1;
//if ((double)(rep.r1) < (double)(rcond.rcondthreshold()) | (double)(rep.rinf) < (double)(rcond.rcondthreshold()))
//{
// if (isupper)
// {
// throw new NotImplementedException();
// }
// else
// {
// for (i = 0; i <= n - 1; i++)
// {
// for (j = 0; j <= i; j++)
// {
// a[i, j] = 0;
// }
// }
// }
// rep.r1 = 0;
// rep.rinf = 0;
// info = -3;
// return;
//}
//
// Inverse
//
tmp = new DualNumber[n];
spdmatrixcholeskyinverserec(ref a, 0, n, isupper, ref tmp);
}
private static void spdmatrixcholeskyinverserec(ref DualNumber[,] a, int offs, int n, bool isupper, ref DualNumber[] tmp)
{
int i = 0;
int j = 0;
DualNumber v = 0;
//int n1 = 0;
//int n2 = 0;
int info2 = 0;
//matinvreport rep2 = new matinvreport();
int i_ = 0;
int i1_ = 0;
if (n < 1)
{
return;
}
//
// Base case
//
//if (n <= ablas.ablasblocksize(ref a))
{
rmatrixtrinverserec(ref a, offs, n, isupper, false, ref tmp, ref info2);
if (isupper)
{
throw new NotImplementedException();
}
else
{
//
// Compute the product L' * L
// NOTE: we never assume that diagonal of L is real
//
for (i = 0; i <= n - 1; i++)
{
if (i == 0)
{
//
// 1x1 matrix
//
a[offs + i, offs + i] = DualNumber.Sqr(a[offs + i, offs + i]);
}
else
{
//
// (I+1)x(I+1) matrix,
//
// ( A11^H A21^H ) ( A11 ) ( A11^H*A11+A21^H*A21 A21^H*A22 )
// ( ) * ( ) = ( )
// ( A22^H ) ( A21 A22 ) ( A22^H*A21 A22^H*A22 )
//
// A11 is IxI, A22 is 1x1.
//
i1_ = (offs) - (0);
for (i_ = 0; i_ <= i - 1; i_++)
{
tmp[i_] = a[offs + i, i_ + i1_];
}
for (j = 0; j <= i - 1; j++)
{
v = a[offs + i, offs + j];
i1_ = (0) - (offs);
for (i_ = offs; i_ <= offs + j; i_++)
{
a[offs + j, i_] = a[offs + j, i_] + v * tmp[i_ + i1_];
}
}
v = a[offs + i, offs + i];
for (i_ = offs; i_ <= offs + i - 1; i_++)
{
a[offs + i, i_] = v * a[offs + i, i_];
}
a[offs + i, offs + i] = DualNumber.Sqr(a[offs + i, offs + i]);
}
}
}
return;
}
}
private static void rmatrixtrinverserec(ref DualNumber[,] a, int offs, int n, bool isupper, bool isunit, ref DualNumber[] tmp, ref int info)
{
//int n1 = 0;
//int n2 = 0;
int i = 0;
int j = 0;
DualNumber v = 0;
DualNumber ajj = 0;
int i_ = 0;
int i1_ = 0;
if (n < 1)
{
info = -1;
return;
}
//
// Base case
//
//if (n <= ablas.ablasblocksize(ref a))
{
if (isupper)
{
throw new NotImplementedException();
}
else
{
//
// Compute inverse of lower triangular matrix.
//
for (j = n - 1; j >= 0; j--)
{
if (!isunit)
{
if (a[offs + j, offs + j].Value == 0.0)
{
info = -3;
return;
}
a[offs + j, offs + j] = 1 / a[offs + j, offs + j];
ajj = -a[offs + j, offs + j];
}
else
{
ajj = -1;
}
if (j < n - 1)
{
//
// Compute elements j+1:n of j-th column.
//
i1_ = (offs + j + 1) - (j + 1);
for (i_ = j + 1; i_ <= n - 1; i_++)
{
tmp[i_] = a[i_ + i1_, offs + j];
}
for (i = j + 1; i <= n - 1; i++)
{
if (i > j + 1)
{
i1_ = (j + 1) - (offs + j + 1);
v = 0.0;
for (i_ = offs + j + 1; i_ <= offs + i - 1; i_++)
{
v += a[offs + i, i_] * tmp[i_ + i1_];
}
}
else
{
v = 0;
}
if (!isunit)
{
a[offs + i, offs + j] = v + a[offs + i, offs + i] * tmp[i];
}
else
{
a[offs + i, offs + j] = v + tmp[i];
}
}
for (i_ = offs + j + 1; i_ <= offs + n - 1; i_++)
{
a[i_, offs + j] = ajj * a[i_, offs + j];
}
}
}
}
return;
}
}
}
}
| |
//
// 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 Hyak.Common;
using Microsoft.Azure.Management.Sql.LegacySdk;
using Microsoft.Azure.Management.Sql.LegacySdk.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Sql.LegacySdk
{
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// Service Objectives. Contains operations to: Retrieve service
/// objectives.
/// </summary>
internal partial class ServiceObjectiveOperations : IServiceOperations<SqlManagementClient>, IServiceObjectiveOperations
{
/// <summary>
/// Initializes a new instance of the ServiceObjectiveOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ServiceObjectiveOperations(SqlManagementClient client)
{
this._client = client;
}
private SqlManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.SqlManagementClient.
/// </summary>
public SqlManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Returns information about an Azure SQL Database Server Service
/// Objectives.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Server.
/// </param>
/// <param name='serviceObjectiveName'>
/// Required. The name of the service objective to retrieve.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a Get Azure Sql Database Service
/// Objective request.
/// </returns>
public async Task<ServiceObjectiveGetResponse> GetAsync(string resourceGroupName, string serverName, string serviceObjectiveName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (serviceObjectiveName == null)
{
throw new ArgumentNullException("serviceObjectiveName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("serviceObjectiveName", serviceObjectiveName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/serviceObjectives/";
url = url + Uri.EscapeDataString(serviceObjectiveName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServiceObjectiveGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServiceObjectiveGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ServiceObjective serviceObjectiveInstance = new ServiceObjective();
result.ServiceObjective = serviceObjectiveInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ServiceObjectiveProperties propertiesInstance = new ServiceObjectiveProperties();
serviceObjectiveInstance.Properties = propertiesInstance;
JToken serviceObjectiveNameValue = propertiesValue["serviceObjectiveName"];
if (serviceObjectiveNameValue != null && serviceObjectiveNameValue.Type != JTokenType.Null)
{
string serviceObjectiveNameInstance = ((string)serviceObjectiveNameValue);
propertiesInstance.ServiceObjectiveName = serviceObjectiveNameInstance;
}
JToken isDefaultValue = propertiesValue["isDefault"];
if (isDefaultValue != null && isDefaultValue.Type != JTokenType.Null)
{
bool isDefaultInstance = ((bool)isDefaultValue);
propertiesInstance.IsDefault = isDefaultInstance;
}
JToken isSystemValue = propertiesValue["isSystem"];
if (isSystemValue != null && isSystemValue.Type != JTokenType.Null)
{
bool isSystemInstance = ((bool)isSystemValue);
propertiesInstance.IsSystem = isSystemInstance;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
JToken enabledValue = propertiesValue["enabled"];
if (enabledValue != null && enabledValue.Type != JTokenType.Null)
{
bool enabledInstance = ((bool)enabledValue);
propertiesInstance.Enabled = enabledInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
serviceObjectiveInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
serviceObjectiveInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
serviceObjectiveInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
serviceObjectiveInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
serviceObjectiveInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Returns information about an Azure SQL Database Server Service
/// Objectives.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Server.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a Get Azure Sql Database Service
/// Objectives request.
/// </returns>
public async Task<ServiceObjectiveListResponse> ListAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/serviceObjectives";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServiceObjectiveListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServiceObjectiveListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
ServiceObjective serviceObjectiveInstance = new ServiceObjective();
result.ServiceObjectives.Add(serviceObjectiveInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ServiceObjectiveProperties propertiesInstance = new ServiceObjectiveProperties();
serviceObjectiveInstance.Properties = propertiesInstance;
JToken serviceObjectiveNameValue = propertiesValue["serviceObjectiveName"];
if (serviceObjectiveNameValue != null && serviceObjectiveNameValue.Type != JTokenType.Null)
{
string serviceObjectiveNameInstance = ((string)serviceObjectiveNameValue);
propertiesInstance.ServiceObjectiveName = serviceObjectiveNameInstance;
}
JToken isDefaultValue = propertiesValue["isDefault"];
if (isDefaultValue != null && isDefaultValue.Type != JTokenType.Null)
{
bool isDefaultInstance = ((bool)isDefaultValue);
propertiesInstance.IsDefault = isDefaultInstance;
}
JToken isSystemValue = propertiesValue["isSystem"];
if (isSystemValue != null && isSystemValue.Type != JTokenType.Null)
{
bool isSystemInstance = ((bool)isSystemValue);
propertiesInstance.IsSystem = isSystemInstance;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
JToken enabledValue = propertiesValue["enabled"];
if (enabledValue != null && enabledValue.Type != JTokenType.Null)
{
bool enabledInstance = ((bool)enabledValue);
propertiesInstance.Enabled = enabledInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
serviceObjectiveInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
serviceObjectiveInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
serviceObjectiveInstance.Type = typeInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
serviceObjectiveInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
serviceObjectiveInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB.Bson.Serialization.Attributes;
namespace Qupid.Mongo
{
public class QupidCollection
{
public string Name { get; set; }
public string Database { get; set; }
public List<QupidIndex> Indices { get; set; }
public List<QupidProperty> Properties { get; set; }
public Dictionary<string, string> ShortToLongProperties { get; set; }
public Dictionary<string, string> LongToShortProperties { get; set; }
public long NumberOfRows { get; set; }
public Type BaseDataType { get; set; }
public QupidCollection()
{
}
public QupidCollection(Type baseType, string databaseName, string collectionName)
{
Name = collectionName;
Database = databaseName;
BaseDataType = baseType;
Properties = InspectTypeForMongoAttributes(baseType);
ShortToLongProperties = Properties.ToDictionary(p => p.ShortName, p => p.LongName);
LongToShortProperties = Properties.ToDictionary(p => p.LongName, p => p.ShortName);
Indices = new List<QupidIndex>();
}
public QupidProperty GetProperty(string longPath)
{
var strBld = new StringBuilder();
string[] pieces = longPath.Split('.');
var curQupidProp = (QupidProperty)null;
var propertyContext = Properties;
var conversionDict = LongToShortProperties;
for (int depth = 0; depth < pieces.Length; depth++)
{
string result;
if (!conversionDict.TryGetValue(pieces[depth], out result)) break;
strBld.AppendFormat("{0}.", result);
curQupidProp = propertyContext.FirstOrDefault(p => p.LongName.ToLowerInvariant().Equals(pieces[depth].ToLowerInvariant()));
if (curQupidProp == null) break;
if (curQupidProp.HasSubProperties)
{
propertyContext = curQupidProp.Properties;
conversionDict = curQupidProp.LongToShortProperties;
}
}
return curQupidProp;
}
public IEnumerable<QupidProperty> GetAllReferencedProperties(string longPath)
{
var propertyContext = Properties;
foreach (var piece in longPath.Split('.'))
{
if (piece == "*")
{
// we have reached the star piece, return all sub-properties of the current property context
return propertyContext.Where(qp => !qp.HasSubProperties);
}
var nestedProp = FetchProperty(propertyContext, piece);
if (nestedProp == null)
{
return null;
}
propertyContext = nestedProp.Properties;
}
// we shouldn't ever reach this case
return null;
}
public string ConvertToShortPath(string longPath)
{
var strBld = new StringBuilder();
string[] pieces = longPath.Split('.');
var propertyContext = Properties;
var conversionDict = LongToShortProperties;
for (int depth = 0; depth < pieces.Length; depth++)
{
string result;
if (!conversionDict.TryGetValue(pieces[depth], out result)) break;
strBld.AppendFormat("{0}.", result);
var curQupidProp = propertyContext.FirstOrDefault(p => p.LongName.ToLowerInvariant().Equals(pieces[depth].ToLowerInvariant()));
if (curQupidProp == null) break;
if (curQupidProp.HasSubProperties)
{
propertyContext = curQupidProp.Properties;
conversionDict = curQupidProp.LongToShortProperties;
}
}
if (strBld.Length > 0)
{
//if we built something - remove the trailing '.'
strBld = strBld.Remove(strBld.Length - 1, 1);
}
else
{
// otherwise return null
return null;
}
return strBld.ToString();
}
public string ConvertToLongPath(string shortPath)
{
StringBuilder strBld = new StringBuilder();
string[] pieces = shortPath.Split('.');
var propertyContext = Properties;
var conversionDict = ShortToLongProperties;
for (int depth = 0; depth < pieces.Length; depth++)
{
string result;
if (!conversionDict.TryGetValue(pieces[depth], out result)) break;
strBld.AppendFormat("{0}.", result);
var curQupidProp = propertyContext.FirstOrDefault(p => p.ShortName.ToLowerInvariant().Equals(pieces[depth].ToLowerInvariant()));
if (curQupidProp == null) break;
if (curQupidProp.HasSubProperties)
{
propertyContext = curQupidProp.Properties;
conversionDict = curQupidProp.ShortToLongProperties;
}
}
//if we built something - remove the trailing '.'
if (strBld.Length > 0)
{
strBld = strBld.Remove(strBld.Length - 1, 1);
}
else
{
return shortPath; //else just return the input
}
return strBld.ToString();
}
public override bool Equals(object obj)
{
if (!(obj is QupidCollection))
{
return false;
}
var qc = (QupidCollection) obj;
return qc.Database.Equals(Database, StringComparison.OrdinalIgnoreCase) && qc.Name.Equals(Name, StringComparison.OrdinalIgnoreCase);
}
public override int GetHashCode()
{
return Database.GetHashCode() + Name.GetHashCode();
}
public override string ToString()
{
return Name;
}
protected List<QupidProperty> InspectTypeForMongoAttributes(Type baseDataType)
{
var properties = new List<QupidProperty>();
foreach (var prop in baseDataType.GetProperties().OrderBy(p => p.Name))
{
var attr = prop.GetCustomAttributes(false).FirstOrDefault(p => p.GetType() == typeof(BsonElementAttribute) || p.GetType() == typeof(BsonIdAttribute));
if (attr == null) continue;
var newProp = new QupidProperty
{
IsList = prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(List<>),
IsNullable =
prop.PropertyType.IsGenericType &&
prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>),
IsEnum = prop.PropertyType.IsEnum,
LongName = prop.Name,
ShortName = (attr is BsonElementAttribute)
? ((BsonElementAttribute)attr).ElementName
: "_id",
};
Type propType;
if (newProp.IsList || newProp.IsNullable)
{
propType = prop.PropertyType.GetGenericArguments()[0];
}
else
{
propType = prop.PropertyType;
}
if (newProp.IsEnum)
{
newProp.EnumValues = Enum.GetNames(propType).ToList();
}
newProp.Type = propType.Name;
newProp.HasSubProperties = DetectSubElements(propType);
if (newProp.HasSubProperties)
{
newProp.Properties = InspectTypeForMongoAttributes(propType);
newProp.ShortToLongProperties = newProp.Properties.ToDictionary(p => p.ShortName, p => p.LongName);
newProp.LongToShortProperties = newProp.Properties.ToDictionary(p => p.LongName, p => p.ShortName);
}
properties.Add(newProp);
}
return properties;
}
private QupidProperty FetchProperty(IEnumerable<QupidProperty> props, string longName)
{
var fetchedProperty = props.FirstOrDefault(p => p.LongName.ToLowerInvariant().Equals(longName.ToLowerInvariant()));
return fetchedProperty;
}
private static bool DetectSubElements(Type propType)
{
return propType.GetProperties().Any(p => p.GetCustomAttributes(false).Any(p2 => p2.GetType() == typeof(BsonElementAttribute)));
}
}
}
| |
//
// Authors:
// Atsushi Enomoto
//
// Copyright 2007 Novell (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace System.Xml.Linq
{
[XmlSchemaProvider (null, IsAny = true)]
internal class XElement : XContainer, IXmlSerializable
{
static IEnumerable <XElement> emptySequence =
new List <XElement> ();
public static IEnumerable <XElement> EmptySequence {
get { return emptySequence; }
}
XName name;
XAttribute attr_first, attr_last;
bool explicit_is_empty = true;
public XElement (XName name, object content)
{
if (name == null)
throw new ArgumentNullException ("name");
this.name = name;
Add (content);
}
public XElement (XElement other)
{
if (other == null)
throw new ArgumentNullException ("other");
name = other.name;
Add (other.Attributes ());
Add (other.Nodes ());
}
public XElement (XName name)
{
if (name == null)
throw new ArgumentNullException ("name");
this.name = name;
}
public XElement (XName name, params object [] content)
{
if (name == null)
throw new ArgumentNullException ("name");
this.name = name;
Add (content);
}
public XElement (XStreamingElement other)
{
if (other == null)
throw new ArgumentNullException ("other");
this.name = other.Name;
Add (other.Contents);
}
public static explicit operator bool (XElement element)
{
if (element == null)
throw new ArgumentNullException ("element");
return XUtil.ConvertToBoolean (element.Value);
}
public static explicit operator bool? (XElement element)
{
if (element == null)
return null;
return element.Value == null ? (bool?) null : XUtil.ConvertToBoolean (element.Value);
}
public static explicit operator DateTime (XElement element)
{
if (element == null)
throw new ArgumentNullException ("element");
return XUtil.ToDateTime (element.Value);
}
public static explicit operator DateTime? (XElement element)
{
if (element == null)
return null;
return element.Value == null ? (DateTime?) null : XUtil.ToDateTime (element.Value);
}
#if !TARGET_JVM // Same as for System.Xml.XmlConvert.ToDateTimeOffset
public static explicit operator DateTimeOffset (XElement element)
{
if (element == null)
throw new ArgumentNullException ("element");
return XmlConvert.ToDateTimeOffset (element.Value);
}
public static explicit operator DateTimeOffset? (XElement element)
{
if (element == null)
return null;
return element.Value == null ? (DateTimeOffset?) null : XmlConvert.ToDateTimeOffset (element.Value);
}
#endif
public static explicit operator decimal (XElement element)
{
if (element == null)
throw new ArgumentNullException ("element");
return XmlConvert.ToDecimal (element.Value);
}
public static explicit operator decimal? (XElement element)
{
if (element == null)
return null;
return element.Value == null ? (decimal?) null : XmlConvert.ToDecimal (element.Value);
}
public static explicit operator double (XElement element)
{
if (element == null)
throw new ArgumentNullException ("element");
return XmlConvert.ToDouble (element.Value);
}
public static explicit operator double? (XElement element)
{
if (element == null)
return null;
return element.Value == null ? (double?) null : XmlConvert.ToDouble (element.Value);
}
public static explicit operator float (XElement element)
{
if (element == null)
throw new ArgumentNullException ("element");
return XmlConvert.ToSingle (element.Value);
}
public static explicit operator float? (XElement element)
{
if (element == null)
return null;
return element.Value == null ? (float?) null : XmlConvert.ToSingle (element.Value);
}
public static explicit operator Guid (XElement element)
{
if (element == null)
throw new ArgumentNullException ("element");
return XmlConvert.ToGuid (element.Value);
}
public static explicit operator Guid? (XElement element)
{
if (element == null)
return null;
return element.Value == null ? (Guid?) null : XmlConvert.ToGuid (element.Value);
}
public static explicit operator int (XElement element)
{
if (element == null)
throw new ArgumentNullException ("element");
return XmlConvert.ToInt32 (element.Value);
}
public static explicit operator int? (XElement element)
{
if (element == null)
return null;
return element.Value == null ? (int?) null : XmlConvert.ToInt32 (element.Value);
}
public static explicit operator long (XElement element)
{
if (element == null)
throw new ArgumentNullException ("element");
return XmlConvert.ToInt64 (element.Value);
}
public static explicit operator long? (XElement element)
{
if (element == null)
return null;
return element.Value == null ? (long?) null : XmlConvert.ToInt64 (element.Value);
}
public static explicit operator uint (XElement element)
{
if (element == null)
throw new ArgumentNullException ("element");
return XmlConvert.ToUInt32 (element.Value);
}
public static explicit operator uint? (XElement element)
{
if (element == null)
return null;
return element.Value == null ? (uint?) null : XmlConvert.ToUInt32 (element.Value);
}
public static explicit operator ulong (XElement element)
{
if (element == null)
throw new ArgumentNullException ("element");
return XmlConvert.ToUInt64 (element.Value);
}
public static explicit operator ulong? (XElement element)
{
if (element == null)
return null;
return element.Value == null ? (ulong?) null : XmlConvert.ToUInt64 (element.Value);
}
public static explicit operator TimeSpan (XElement element)
{
if (element == null)
throw new ArgumentNullException ("element");
return XmlConvert.ToTimeSpan (element.Value);
}
public static explicit operator TimeSpan? (XElement element)
{
if (element == null)
return null;
return element.Value == null ? (TimeSpan?) null : XmlConvert.ToTimeSpan (element.Value);
}
public static explicit operator string (XElement element)
{
if (element == null)
return null;
return element.Value;
}
public XAttribute FirstAttribute {
get { return attr_first; }
internal set { attr_first = value; }
}
public XAttribute LastAttribute {
get { return attr_last; }
internal set { attr_last = value; }
}
public bool HasAttributes {
get { return attr_first != null; }
}
public bool HasElements {
get {
foreach (object o in Nodes ())
if (o is XElement)
return true;
return false;
}
}
public bool IsEmpty {
get { return !Nodes ().GetEnumerator ().MoveNext () && explicit_is_empty; }
internal set { explicit_is_empty = value; }
}
public XName Name {
get { return name; }
set {
if (value == null)
throw new ArgumentNullException ("Name");
OnNameChanging (this);
name = value;
OnNameChanged (this);
}
}
public override XmlNodeType NodeType {
get { return XmlNodeType.Element; }
}
public string Value {
get {
StringBuilder sb = null;
foreach (XNode n in Nodes ()) {
if (sb == null)
sb = new StringBuilder ();
if (n is XText)
sb.Append (((XText) n).Value);
else if (n is XElement)
sb.Append (((XElement) n).Value);
}
return sb == null ? String.Empty : sb.ToString ();
}
set {
RemoveNodes ();
Add (value);
}
}
IEnumerable <XElement> GetAncestorList (XName name, bool getMeIn)
{
List <XElement> list = new List <XElement> ();
if (getMeIn)
list.Add (this);
for (XElement el = Parent as XElement; el != null; el = el.Parent as XElement)
if (name == null || el.Name == name)
list.Add (el);
return list;
}
public XAttribute Attribute (XName name)
{
foreach (XAttribute a in Attributes ())
if (a.Name == name)
return a;
return null;
}
public IEnumerable <XAttribute> Attributes ()
{
XAttribute next;
for (XAttribute a = attr_first; a != null; a = next) {
next = a.NextAttribute;
yield return a;
}
}
// huh?
public IEnumerable <XAttribute> Attributes (XName name)
{
foreach (XAttribute a in Attributes ())
if (a.Name == name)
yield return a;
}
static void DefineDefaultSettings (XmlReaderSettings settings, LoadOptions options)
{
settings.ProhibitDtd = false;
settings.IgnoreWhitespace = (options & LoadOptions.PreserveWhitespace) == 0;
}
static XmlReaderSettings CreateDefaultSettings (LoadOptions options)
{
var settings = new XmlReaderSettings ();
DefineDefaultSettings (settings, options);
return settings;
}
public static XElement Load (string uri)
{
return Load (uri, LoadOptions.None);
}
public static XElement Load (string uri, LoadOptions options)
{
XmlReaderSettings s = CreateDefaultSettings (options);
using (XmlReader r = XmlReader.Create (uri, s)) {
return LoadCore (r, options);
}
}
public static XElement Load (TextReader textReader)
{
return Load (textReader, LoadOptions.None);
}
public static XElement Load (TextReader textReader, LoadOptions options)
{
XmlReaderSettings s = CreateDefaultSettings (options);
using (XmlReader r = XmlReader.Create (textReader, s)) {
return LoadCore (r, options);
}
}
public static XElement Load (XmlReader reader)
{
return Load (reader, LoadOptions.None);
}
public static XElement Load (XmlReader reader, LoadOptions options)
{
XmlReaderSettings s = reader.Settings != null ? reader.Settings.Clone () : new XmlReaderSettings ();
DefineDefaultSettings (s, options);
using (XmlReader r = XmlReader.Create (reader, s)) {
return LoadCore (r, options);
}
}
#if NET_4_0
public static XElement Load (Stream stream)
{
return Load (stream, LoadOptions.None);
}
public static XElement Load (Stream stream, LoadOptions options)
{
XmlReaderSettings s = new XmlReaderSettings ();
DefineDefaultSettings (s, options);
using (XmlReader r = XmlReader.Create (stream, s)) {
return LoadCore (r, options);
}
}
#endif
internal static XElement LoadCore (XmlReader r, LoadOptions options)
{
r.MoveToContent ();
if (r.NodeType != XmlNodeType.Element)
throw new InvalidOperationException ("The XmlReader must be positioned at an element");
XName name = XName.Get (r.LocalName, r.NamespaceURI);
XElement e = new XElement (name);
e.FillLineInfoAndBaseUri (r, options);
if (r.MoveToFirstAttribute ()) {
do {
// not sure how current Orcas behavior makes sense here though ...
if (r.LocalName == "xmlns" && r.NamespaceURI == XNamespace.Xmlns.NamespaceName)
e.SetAttributeValue (XNamespace.None.GetName ("xmlns"), r.Value);
else
e.SetAttributeValue (XName.Get (r.LocalName, r.NamespaceURI), r.Value);
e.LastAttribute.FillLineInfoAndBaseUri (r, options);
} while (r.MoveToNextAttribute ());
r.MoveToElement ();
}
if (!r.IsEmptyElement) {
r.Read ();
e.ReadContentFrom (r, options);
r.ReadEndElement ();
e.explicit_is_empty = false;
} else {
e.explicit_is_empty = true;
r.Read ();
}
return e;
}
public static XElement Parse (string text)
{
return Parse (text, LoadOptions.None);
}
public static XElement Parse (string text, LoadOptions options)
{
return Load (new StringReader (text), options);
}
public void RemoveAll ()
{
RemoveAttributes ();
RemoveNodes ();
}
public void RemoveAttributes ()
{
while (attr_first != null)
attr_last.Remove ();
}
public void Save (string fileName)
{
Save (fileName, SaveOptions.None);
}
public void Save (string fileName, SaveOptions options)
{
XmlWriterSettings s = new XmlWriterSettings ();
if ((options & SaveOptions.DisableFormatting) == SaveOptions.None)
s.Indent = true;
#if NET_4_0
if ((options & SaveOptions.OmitDuplicateNamespaces) == SaveOptions.OmitDuplicateNamespaces)
s.NamespaceHandling |= NamespaceHandling.OmitDuplicates;
#endif
using (XmlWriter w = XmlWriter.Create (fileName, s)) {
Save (w);
}
}
public void Save (TextWriter textWriter)
{
Save (textWriter, SaveOptions.None);
}
public void Save (TextWriter textWriter, SaveOptions options)
{
XmlWriterSettings s = new XmlWriterSettings ();
if ((options & SaveOptions.DisableFormatting) == SaveOptions.None)
s.Indent = true;
#if NET_4_0
if ((options & SaveOptions.OmitDuplicateNamespaces) == SaveOptions.OmitDuplicateNamespaces)
s.NamespaceHandling |= NamespaceHandling.OmitDuplicates;
#endif
using (XmlWriter w = XmlWriter.Create (textWriter, s)) {
Save (w);
}
}
public void Save (XmlWriter writer)
{
WriteTo (writer);
}
#if NET_4_0
public void Save (Stream stream)
{
Save (stream, SaveOptions.None);
}
public void Save (Stream stream, SaveOptions options)
{
XmlWriterSettings s = new XmlWriterSettings ();
if ((options & SaveOptions.DisableFormatting) == SaveOptions.None)
s.Indent = true;
if ((options & SaveOptions.OmitDuplicateNamespaces) == SaveOptions.OmitDuplicateNamespaces)
s.NamespaceHandling |= NamespaceHandling.OmitDuplicates;
using (var writer = XmlWriter.Create (stream, s)){
Save (writer);
}
}
#endif
public IEnumerable <XElement> AncestorsAndSelf ()
{
return GetAncestorList (null, true);
}
public IEnumerable <XElement> AncestorsAndSelf (XName name)
{
return GetAncestorList (name, true);
}
public IEnumerable <XElement> DescendantsAndSelf ()
{
List <XElement> list = new List <XElement> ();
list.Add (this);
list.AddRange (Descendants ());
return list;
}
public IEnumerable <XElement> DescendantsAndSelf (XName name)
{
List <XElement> list = new List <XElement> ();
if (name == this.name)
list.Add (this);
list.AddRange (Descendants (name));
return list;
}
public IEnumerable <XNode> DescendantNodesAndSelf ()
{
yield return this;
foreach (XNode node in DescendantNodes ())
yield return node;
}
public void SetAttributeValue (XName name, object value)
{
XAttribute a = Attribute (name);
if (value == null) {
if (a != null)
a.Remove ();
} else {
if (a == null) {
SetAttributeObject (new XAttribute (name, value));
}
else
a.Value = XUtil.ToString (value);
}
}
void SetAttributeObject (XAttribute a)
{
OnAddingObject (a);
a = (XAttribute) XUtil.GetDetachedObject (a);
a.SetOwner (this);
if (attr_first == null) {
attr_first = a;
attr_last = a;
} else {
attr_last.NextAttribute = a;
a.PreviousAttribute = attr_last;
attr_last = a;
}
OnAddedObject (a);
}
string LookupPrefix (string ns, XmlWriter w)
{
string prefix = ns.Length > 0 ? GetPrefixOfNamespace (ns) ?? w.LookupPrefix (ns) : String.Empty;
foreach (XAttribute a in Attributes ()) {
if (a.IsNamespaceDeclaration && a.Value == ns) {
if (a.Name.Namespace == XNamespace.Xmlns)
prefix = a.Name.LocalName;
// otherwise xmlns="..."
break;
}
}
return prefix;
}
static string CreateDummyNamespace (ref int createdNS, IEnumerable<XAttribute> atts, bool isAttr)
{
if (!isAttr && atts.All (a => a.Name.LocalName != "xmlns" || a.Name.NamespaceName == XNamespace.Xmlns.NamespaceName))
return String.Empty;
string p = null;
do {
p = "p" + (++createdNS);
// check conflict
if (atts.All (a => a.Name.LocalName != p || a.Name.NamespaceName == XNamespace.Xmlns.NamespaceName))
break;
} while (true);
return p;
}
public override void WriteTo (XmlWriter writer)
{
// some people expect the same prefix output as in input,
// in the loss of performance... see bug #466423.
string prefix = LookupPrefix (name.NamespaceName, writer);
int createdNS = 0;
if (prefix == null)
prefix = CreateDummyNamespace (ref createdNS, Attributes (), false);
writer.WriteStartElement (prefix, name.LocalName, name.Namespace.NamespaceName);
foreach (XAttribute a in Attributes ()) {
if (a.IsNamespaceDeclaration) {
if (a.Name.Namespace == XNamespace.Xmlns)
writer.WriteAttributeString ("xmlns", a.Name.LocalName, XNamespace.Xmlns.NamespaceName, a.Value);
else
writer.WriteAttributeString ("xmlns", a.Value);
} else {
string apfix = LookupPrefix (a.Name.NamespaceName, writer);
if (apfix == null)
apfix = CreateDummyNamespace (ref createdNS, Attributes (), true);
writer.WriteAttributeString (apfix, a.Name.LocalName, a.Name.Namespace.NamespaceName, a.Value);
}
}
foreach (XNode node in Nodes ())
node.WriteTo (writer);
if (explicit_is_empty)
writer.WriteEndElement ();
else
writer.WriteFullEndElement ();
}
public XNamespace GetDefaultNamespace ()
{
for (XElement el = this; el != null; el = el.Parent)
foreach (XAttribute a in el.Attributes ())
if (a.IsNamespaceDeclaration && a.Name.Namespace == XNamespace.None)
return XNamespace.Get (a.Value);
return XNamespace.None; // nothing is declared.
}
public XNamespace GetNamespaceOfPrefix (string prefix)
{
for (XElement el = this; el != null; el = el.Parent)
foreach (XAttribute a in el.Attributes ())
if (a.IsNamespaceDeclaration && (prefix.Length == 0 && a.Name.LocalName == "xmlns" || a.Name.LocalName == prefix))
return XNamespace.Get (a.Value);
return XNamespace.None; // nothing is declared.
}
public string GetPrefixOfNamespace (XNamespace ns)
{
foreach (string prefix in GetPrefixOfNamespaceCore (ns))
if (GetNamespaceOfPrefix (prefix) == ns)
return prefix;
return null; // nothing is declared
}
IEnumerable<string> GetPrefixOfNamespaceCore (XNamespace ns)
{
for (XElement el = this; el != null; el = el.Parent)
foreach (XAttribute a in el.Attributes ())
if (a.IsNamespaceDeclaration && a.Value == ns.NamespaceName)
yield return a.Name.Namespace == XNamespace.None ? String.Empty : a.Name.LocalName;
}
public void ReplaceAll (object content)
{
RemoveNodes ();
Add (content);
}
public void ReplaceAll (params object [] content)
{
RemoveNodes ();
Add (content);
}
public void ReplaceAttributes (object content)
{
RemoveAttributes ();
Add (content);
}
public void ReplaceAttributes (params object [] content)
{
RemoveAttributes ();
Add (content);
}
public void SetElementValue (XName name, object value)
{
var element = Element (name);
if (element == null && value != null) {
Add (new XElement (name, value));
} else if (element != null && value == null) {
element.Remove ();
} else
element.SetValue (value);
}
public void SetValue (object value)
{
if (value == null)
throw new ArgumentNullException ("value");
if (value is XAttribute || value is XDocument || value is XDeclaration || value is XDocumentType)
throw new ArgumentException (String.Format ("Node type {0} is not allowed as element value", value.GetType ()));
RemoveNodes ();
foreach (object o in XUtil.ExpandArray (value))
Add (o);
}
internal override bool OnAddingObject (object o, bool rejectAttribute, XNode refNode, bool addFirst)
{
if (o is XDocument || o is XDocumentType || o is XDeclaration || (rejectAttribute && o is XAttribute))
throw new ArgumentException (String.Format ("A node of type {0} cannot be added as a content", o.GetType ()));
XAttribute a = o as XAttribute;
if (a != null) {
foreach (XAttribute ia in Attributes ())
if (a.Name == ia.Name)
throw new InvalidOperationException (String.Format ("Duplicate attribute: {0}", a.Name));
SetAttributeObject (a);
return true;
}
else if (o is string && refNode is XText) {
((XText) refNode).Value += o as string;
return true;
}
else
return false;
}
void IXmlSerializable.WriteXml (XmlWriter writer)
{
Save (writer);
}
void IXmlSerializable.ReadXml (XmlReader reader)
{
ReadContentFrom (reader, LoadOptions.None);
}
XmlSchema IXmlSerializable.GetSchema ()
{
return null;
}
}
}
| |
using System;
using System.Collections.Generic;
using QuickGraph.Algorithms.Services;
namespace QuickGraph.Algorithms.Search
{
/// <summary>
/// A depth first search algorithm for implicit directed graphs
/// </summary>
/// <reference-ref
/// idref="gross98graphtheory"
/// chapter="4.2"
/// />
#if !SILVERLIGHT
[Serializable]
#endif
public sealed class ImplicitDepthFirstSearchAlgorithm<TVertex, TEdge> :
RootedAlgorithmBase<TVertex,IIncidenceGraph<TVertex,TEdge>>,
IVertexPredecessorRecorderAlgorithm<TVertex,TEdge>,
IVertexTimeStamperAlgorithm<TVertex,TEdge>,
ITreeBuilderAlgorithm<TVertex,TEdge>
where TEdge : IEdge<TVertex>
{
private int maxDepth = int.MaxValue;
private IDictionary<TVertex, GraphColor> vertexColors = new Dictionary<TVertex, GraphColor>();
public ImplicitDepthFirstSearchAlgorithm(
IIncidenceGraph<TVertex, TEdge> visitedGraph)
: this(null, visitedGraph)
{ }
public ImplicitDepthFirstSearchAlgorithm(
IAlgorithmComponent host,
IIncidenceGraph<TVertex,TEdge> visitedGraph)
:base(host, visitedGraph)
{}
/// <summary>
/// Gets the vertex color map
/// </summary>
/// <value>
/// Vertex color (<see cref="GraphColor"/>) dictionary
/// </value>
public IDictionary<TVertex,GraphColor> VertexColors
{
get
{
return this.vertexColors;
}
}
/// <summary>
/// Gets or sets the maximum exploration depth, from
/// the start vertex.
/// </summary>
/// <remarks>
/// Defaulted at <c>int.MaxValue</c>.
/// </remarks>
/// <value>
/// Maximum exploration depth.
/// </value>
public int MaxDepth
{
get
{
return this.maxDepth;
}
set
{
this.maxDepth = value;
}
}
/// <summary>
/// Invoked on the source vertex once before the start of the search.
/// </summary>
public event VertexAction<TVertex> StartVertex;
/// <summary>
/// Raises the <see cref="StartVertex"/> event.
/// </summary>
/// <param name="v">vertex that raised the event</param>
private void OnStartVertex(TVertex v)
{
var eh = this.StartVertex;
if (eh != null)
eh(v);
}
/// <summary>
/// Invoked when a vertex is encountered for the first time.
/// </summary>
public event VertexAction<TVertex> DiscoverVertex;
/// <summary>
/// Raises the <see cref="DiscoverVertex"/> event.
/// </summary>
/// <param name="v">vertex that raised the event</param>
private void OnDiscoverVertex(TVertex v)
{
var eh = this.DiscoverVertex;
if (eh != null)
eh(v);
}
/// <summary>
/// Invoked on every out-edge of each vertex after it is discovered.
/// </summary>
public event EdgeAction<TVertex,TEdge> ExamineEdge;
/// <summary>
/// Raises the <see cref="ExamineEdge"/> event.
/// </summary>
/// <param name="e">edge that raised the event</param>
private void OnExamineEdge(TEdge e)
{
var eh = this.ExamineEdge;
if (eh != null)
eh(e);
}
/// <summary>
/// Invoked on each edge as it becomes a member of the edges that form
/// the search tree. If you wish to record predecessors, do so at this
/// event point.
/// </summary>
public event EdgeAction<TVertex, TEdge> TreeEdge;
/// <summary>
/// Raises the <see cref="TreeEdge"/> event.
/// </summary>
/// <param name="e">edge that raised the event</param>
private void OnTreeEdge(TEdge e)
{
var eh = this.TreeEdge;
if (eh != null)
eh(e);
}
/// <summary>
/// Invoked on the back edges in the graph.
/// </summary>
public event EdgeAction<TVertex, TEdge> BackEdge;
/// <summary>
/// Raises the <see cref="BackEdge"/> event.
/// </summary>
/// <param name="e">edge that raised the event</param>
private void OnBackEdge(TEdge e)
{
var eh = this.BackEdge;
if (eh != null)
eh(e);
}
/// <summary>
/// Invoked on forward or cross edges in the graph.
/// (In an undirected graph this method is never called.)
/// </summary>
public event EdgeAction<TVertex, TEdge> ForwardOrCrossEdge;
/// <summary>
/// Raises the <see cref="ForwardOrCrossEdge"/> event.
/// </summary>
/// <param name="e">edge that raised the event</param>
private void OnForwardOrCrossEdge(TEdge e)
{
var eh = this.ForwardOrCrossEdge;
if (eh != null)
eh(e);
}
/// <summary>
/// Invoked on a vertex after all of its out edges have been added to
/// the search tree and all of the adjacent vertices have been
/// discovered (but before their out-edges have been examined).
/// </summary>
public event VertexAction<TVertex> FinishVertex;
/// <summary>
/// Raises the <see cref="FinishVertex"/> event.
/// </summary>
/// <param name="v">vertex that raised the event</param>
private void OnFinishVertex(TVertex v)
{
var eh = this.FinishVertex;
if (eh != null)
eh(v);
}
protected override void InternalCompute()
{
TVertex rootVertex;
if (!this.TryGetRootVertex(out rootVertex))
throw new InvalidOperationException("root vertex not set");
this.Initialize();
this.Visit(rootVertex, 0);
}
protected override void Initialize()
{
base.Initialize();
this.VertexColors.Clear();
}
private void Visit(TVertex u, int depth)
{
if (depth > this.MaxDepth)
return;
VertexColors[u] = GraphColor.Gray;
OnDiscoverVertex(u);
var cancelManager = this.Services.CancelManager;
foreach (var e in VisitedGraph.OutEdges(u))
{
if (cancelManager.IsCancelling) return;
OnExamineEdge(e);
TVertex v = e.Target;
GraphColor c;
if (!this.VertexColors.TryGetValue(v, out c))
{
OnTreeEdge(e);
Visit(v, depth + 1);
}
else
{
if (c == GraphColor.Gray)
{
OnBackEdge(e);
}
else
{
OnForwardOrCrossEdge(e);
}
}
}
VertexColors[u] = GraphColor.Black;
OnFinishVertex(u);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.