context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// SPDX-License-Identifier: MIT
// Copyright wtfsckgh@gmail.com
// Copyright iced contributors
#if INSTR_INFO
using System.Runtime.CompilerServices;
using Iced.Intel.InstructionInfoInternal;
namespace Iced.Intel {
public static partial class InstructionInfoExtensions {
/// <summary>
/// Gets the encoding, eg. Legacy, 3DNow!, VEX, EVEX, XOP
/// </summary>
/// <param name="code">Code value</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static EncodingKind Encoding(this Code code) {
var data = InstrInfoTable.Data;
int index = (int)code * 2 + 1;
if ((uint)index >= (uint)data.Length)
ThrowHelper.ThrowArgumentOutOfRangeException_code();
return (EncodingKind)((data[index] >> (int)InfoFlags2.EncodingShift) & (uint)InfoFlags2.EncodingMask);
}
/// <summary>
/// Gets the CPU or CPUID feature flags
/// </summary>
/// <param name="code">Code value</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static CpuidFeature[] CpuidFeatures(this Code code) {
var data = InstrInfoTable.Data;
int index = (int)code * 2 + 1;
if ((uint)index >= (uint)data.Length)
ThrowHelper.ThrowArgumentOutOfRangeException_code();
var cpuidFeature = (CpuidFeatureInternal)((data[index] >> (int)InfoFlags2.CpuidFeatureInternalShift) & (uint)InfoFlags2.CpuidFeatureInternalMask);
return CpuidFeatureInternalData.ToCpuidFeatures[(int)cpuidFeature];
}
/// <summary>
/// Gets control flow info
/// </summary>
/// <param name="code">Code value</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static FlowControl FlowControl(this Code code) {
var data = InstrInfoTable.Data;
int index = (int)code * 2 + 1;
if ((uint)index >= (uint)data.Length)
ThrowHelper.ThrowArgumentOutOfRangeException_code();
return (FlowControl)((data[index] >> (int)InfoFlags2.FlowControlShift) & (uint)InfoFlags2.FlowControlMask);
}
/// <summary>
/// Checks if it's a privileged instruction (all CPL=0 instructions (except <c>VMCALL</c>) and IOPL instructions <c>IN</c>, <c>INS</c>, <c>OUT</c>, <c>OUTS</c>, <c>CLI</c>, <c>STI</c>)
/// </summary>
/// <param name="code">Code value</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsPrivileged(this Code code) {
var data = InstrInfoTable.Data;
int index = (int)code * 2 + 1;
if ((uint)index >= (uint)data.Length)
ThrowHelper.ThrowArgumentOutOfRangeException_code();
return (data[index] & (uint)InfoFlags2.Privileged) != 0;
}
/// <summary>
/// Checks if this is an instruction that implicitly uses the stack pointer (<c>SP</c>/<c>ESP</c>/<c>RSP</c>), eg. <c>CALL</c>, <c>PUSH</c>, <c>POP</c>, <c>RET</c>, etc.
/// See also <see cref="Instruction.StackPointerIncrement"/>
/// </summary>
/// <param name="code">Code value</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsStackInstruction(this Code code) {
var data = InstrInfoTable.Data;
int index = (int)code * 2 + 1;
if ((uint)index >= (uint)data.Length)
ThrowHelper.ThrowArgumentOutOfRangeException_code();
return (data[index] & (uint)InfoFlags2.StackInstruction) != 0;
}
/// <summary>
/// Checks if it's an instruction that saves or restores too many registers (eg. <c>FXRSTOR</c>, <c>XSAVE</c>, etc).
/// </summary>
/// <param name="code">Code value</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsSaveRestoreInstruction(this Code code) {
var data = InstrInfoTable.Data;
int index = (int)code * 2 + 1;
if ((uint)index >= (uint)data.Length)
ThrowHelper.ThrowArgumentOutOfRangeException_code();
return (data[index] & (uint)InfoFlags2.SaveRestore) != 0;
}
/// <summary>
/// Checks if it's a <c>Jcc NEAR</c> instruction
/// </summary>
/// <param name="code">Code value</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsJccNear(this Code code) =>
(uint)(code - Code.Jo_rel16) <= (uint)(Code.Jg_rel32_64 - Code.Jo_rel16);
/// <summary>
/// Checks if it's a <c>Jcc SHORT</c> instruction
/// </summary>
/// <param name="code">Code value</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsJccShort(this Code code) =>
(uint)(code - Code.Jo_rel8_16) <= (uint)(Code.Jg_rel8_64 - Code.Jo_rel8_16);
/// <summary>
/// Checks if it's a <c>JMP SHORT</c> instruction
/// </summary>
/// <param name="code">Code value</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsJmpShort(this Code code) =>
(uint)(code - Code.Jmp_rel8_16) <= (uint)(Code.Jmp_rel8_64 - Code.Jmp_rel8_16);
/// <summary>
/// Checks if it's a <c>JMP NEAR</c> instruction
/// </summary>
/// <param name="code">Code value</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsJmpNear(this Code code) =>
(uint)(code - Code.Jmp_rel16) <= (uint)(Code.Jmp_rel32_64 - Code.Jmp_rel16);
/// <summary>
/// Checks if it's a <c>JMP SHORT</c> or a <c>JMP NEAR</c> instruction
/// </summary>
/// <param name="code">Code value</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsJmpShortOrNear(this Code code) =>
(uint)(code - Code.Jmp_rel8_16) <= (uint)(Code.Jmp_rel8_64 - Code.Jmp_rel8_16) ||
(uint)(code - Code.Jmp_rel16) <= (uint)(Code.Jmp_rel32_64 - Code.Jmp_rel16);
/// <summary>
/// Checks if it's a <c>JMP FAR</c> instruction
/// </summary>
/// <param name="code">Code value</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsJmpFar(this Code code) =>
(uint)(code - Code.Jmp_ptr1616) <= (uint)(Code.Jmp_ptr1632 - Code.Jmp_ptr1616);
/// <summary>
/// Checks if it's a <c>CALL NEAR</c> instruction
/// </summary>
/// <param name="code">Code value</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsCallNear(this Code code) =>
(uint)(code - Code.Call_rel16) <= (uint)(Code.Call_rel32_64 - Code.Call_rel16);
/// <summary>
/// Checks if it's a <c>CALL FAR</c> instruction
/// </summary>
/// <param name="code">Code value</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsCallFar(this Code code) =>
(uint)(code - Code.Call_ptr1616) <= (uint)(Code.Call_ptr1632 - Code.Call_ptr1616);
/// <summary>
/// Checks if it's a <c>JMP NEAR reg/[mem]</c> instruction
/// </summary>
/// <param name="code">Code value</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsJmpNearIndirect(this Code code) =>
(uint)(code - Code.Jmp_rm16) <= (uint)(Code.Jmp_rm64 - Code.Jmp_rm16);
/// <summary>
/// Checks if it's a <c>JMP FAR [mem]</c> instruction
/// </summary>
/// <param name="code">Code value</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsJmpFarIndirect(this Code code) =>
(uint)(code - Code.Jmp_m1616) <= (uint)(Code.Jmp_m1664 - Code.Jmp_m1616);
/// <summary>
/// Checks if it's a <c>CALL NEAR reg/[mem]</c> instruction
/// </summary>
/// <param name="code">Code value</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsCallNearIndirect(this Code code) =>
(uint)(code - Code.Call_rm16) <= (uint)(Code.Call_rm64 - Code.Call_rm16);
/// <summary>
/// Checks if it's a <c>CALL FAR [mem]</c> instruction
/// </summary>
/// <param name="code">Code value</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsCallFarIndirect(this Code code) =>
(uint)(code - Code.Call_m1616) <= (uint)(Code.Call_m1664 - Code.Call_m1616);
/// <summary>
/// Gets the condition code if it's <c>Jcc</c>, <c>SETcc</c>, <c>CMOVcc</c> else <see cref="ConditionCode.None"/> is returned
/// </summary>
/// <param name="code">Code value</param>
/// <returns></returns>
[System.Obsolete("Use " + nameof(ConditionCode) + " instead of this method", true)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static ConditionCode GetConditionCode(this Code code) => code.ConditionCode();
/// <summary>
/// Gets the condition code if it's <c>Jcc</c>, <c>SETcc</c>, <c>CMOVcc</c>, <c>LOOPcc</c> else
/// <see cref="ConditionCode.None"/> is returned
/// </summary>
/// <param name="code">Code value</param>
/// <returns></returns>
public static ConditionCode ConditionCode(this Code code) {
uint t;
if ((t = (uint)(code - Code.Jo_rel16)) <= (uint)(Code.Jg_rel32_64 - Code.Jo_rel16) ||
(t = (uint)(code - Code.Jo_rel8_16)) <= (uint)(Code.Jg_rel8_64 - Code.Jo_rel8_16) ||
(t = (uint)(code - Code.Cmovo_r16_rm16)) <= (uint)(Code.Cmovg_r64_rm64 - Code.Cmovo_r16_rm16)) {
return (int)(t / 3) + Intel.ConditionCode.o;
}
t = (uint)(code - Code.Seto_rm8);
if (t <= (uint)(Code.Setg_rm8 - Code.Seto_rm8))
return (int)t + Intel.ConditionCode.o;
t = (uint)(code - Code.Loopne_rel8_16_CX);
if (t <= (uint)(Code.Loopne_rel8_64_RCX - Code.Loopne_rel8_16_CX)) {
return Intel.ConditionCode.ne;
}
t = (uint)(code - Code.Loope_rel8_16_CX);
if (t <= (uint)(Code.Loope_rel8_64_RCX - Code.Loope_rel8_16_CX)) {
return Intel.ConditionCode.e;
}
return Intel.ConditionCode.None;
}
}
}
#endif
| |
/* Copyright (c) 2006 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Google.GData.Client;
using Google.GData.Spreadsheets;
using System.Collections.Generic;
using System;
namespace Google.Spreadsheets
{
//////////////////////////////////////////////////////////////////////
/// <summary>the main object to access everything else with
///
/// </summary>
//////////////////////////////////////////////////////////////////////
public class Application
{
/// <summary>
/// the name of this application
/// </summary>
public static string Name = ".NETSDK Spreadsheets";
private static SpreadsheetsService service;
private static SpreadsheetEntry se;
private static WorksheetEntry we;
private static SpreadsheetFeed sf;
//private static string currentSpreadsheet; //not used //TODO determine if this is a bug
/// <summary>
/// default constructor for client login.
/// </summary>
/// <param name="user">the username to user</param>
/// <param name="password">the users password</param>
/// <returns></returns>
public Application(string user, string password)
{
Application.service = new SpreadsheetsService(Application.Name);
Application.service.setUserCredentials(user, password);
}
/// <summary>
/// constructor for webapplications. Obtain the token using the authsub
/// helper methods
/// </summary>
/// <param name="token">Your authentication token</param>
/// <returns></returns>
public Application(string token)
{
GAuthSubRequestFactory authFactory =
new GAuthSubRequestFactory("wise", Application.Name);
authFactory.Token = token;
Application.service = new SpreadsheetsService(authFactory.ApplicationName);
Application.service.RequestFactory = authFactory;
}
/// <summary>
/// this will reload the list of spreadsheets from the server and reset the
/// currently active spreadsheet/worksheet
/// </summary>
/// <returns></returns>
public void Refresh()
{
Application.sf = null;
Application.se = null;
Application.we = null;
}
/// <summary>
/// this returns a list of strings, with the names of each spreadsheet
/// this will do a roundtrip to the google servers to retrieve the list
/// of spreadsheets if not done yet
/// </summary>
/// <returns>List of strings</returns>
public List<string> Spreadsheets
{
get
{
List<string> results = new List<string>();
EnsureSpreadsheetFeed();
foreach (SpreadsheetEntry entry in Application.sf.Entries)
{
results.Add(entry.Title.Text);
}
return results;
}
}
/// <summary>
/// this will return the current spreadsheetname that is being worked on, or, if set
/// see if there is a spreadsheet of that name, and if so, make this the current spreadsheet
/// </summary>
/// <returns></returns>
public string CurrentSpreadsheet
{
get
{
if (Application.se != null)
{
return Application.se.Title.Text;
}
return null;
}
set
{
Application.se = null;
if (value == null)
{
return;
}
EnsureSpreadsheetFeed();
foreach (SpreadsheetEntry entry in Application.sf.Entries)
{
if (value.Equals(entry.Title.Text))
{
Application.se = entry;
break;
}
}
if (Application.se == null)
{
throw new ArgumentException(value + " was not a valid spreadsheet name");
}
}
}
/// <summary>
/// returns a list of Worksheet names for the currently set spreadsheet,
/// or NULL if no spreadsheet was set
/// </summary>
/// <returns>NULL for no spreadsheet, an empty list for no worksheets in the
/// spreadsheet or a list of names of the worksheets in the current spreadsheet</returns>
public List<string> WorkSheets
{
get
{
if (Application.se != null)
{
List<string> result = new List<string>();
WorksheetFeed feed = Application.se.Worksheets;
foreach (WorksheetEntry worksheet in feed.Entries)
{
result.Add(worksheet.Title.Text);
}
return result;
}
return null;
}
}
/// <summary>
/// this will return the current worksheetname that is being worked on, or, if set
/// see if there is a worksheet of that name, and if so, make this the current worksheet
/// Note that this requires that a current spreadsheet is set
/// </summary>
/// <returns></returns>
public string CurrentWorksheet
{
get
{
if (Application.we != null)
{
return Application.we.Title.Text;
}
return null;
}
set
{
Application.we = null;
if (value == null)
{
return;
}
if (Application.se != null)
{
WorksheetFeed feed = Application.se.Worksheets;
foreach (WorksheetEntry worksheet in feed.Entries)
{
if (value.Equals(worksheet.Title.Text))
{
Application.we = worksheet;
break;
}
}
}
else
{
throw new ArgumentException(value + " is invalid if no spreadsheet is set");
}
}
}
/// <summary>
/// get the whole spreadsheet as a range, one line is one row, one cell is
/// </summary>
/// <returns></returns>
public List<string> CompleteRange
{
get
{
if (this.CurrentWorksheet != null)
{
CellFeed cells = Application.we.QueryCellFeed(ReturnEmtpyCells.yes);
List<string> result = new List<string>();
foreach (CellEntry curCell in cells.Entries)
{
uint r = curCell.Cell.Row, c = curCell.Cell.Column;
result.Add("R" + r + "C" + c + " " + curCell.Cell.Value);
}
return result;
}
return null;
}
}
private void EnsureSpreadsheetFeed()
{
if (Application.sf == null)
{
SpreadsheetQuery query = new SpreadsheetQuery();
Application.sf = service.Query(query);
}
}
///
/// Parse a range given as, e.g., A2:D4 into numerical
/// coordinates. The letter indicates the column in use,
/// the number the row
///
public int[] ParseRangeString(String range)
{
int [] retArray = { -1, -1, -1, -1 };
range = range.ToUpper();
string []address = range.Split(':');
int count = 0;
foreach (string s in address )
{
string rowString=null;
string colString=null;
int rowStart = -1;
for (int i=0; i< s.Length; i++)
{
if (Char.IsDigit(s, i))
{
rowStart = i;
break;
}
}
if (rowStart > 0)
{
rowString = s.Substring(rowStart);
colString = s.Substring(0, rowStart);
}
// rowstring should be a numer, so that is easy
retArray[count+1] = Int32.Parse(rowString);
// colstring is a tad more complicated. a column addressed
// with DE for example is 26 * 4 + 5 ... and ZFE would be
// 26 * 26 * 26 + 6 * 26 + 5
// so we go from right to left
int colValue = 0;
for (int y=0, x = colString.Length-1; x >= 0; x--, y++)
{
char c = colString[x];
colValue += (c - 'A' + 1) * (int) Math.Pow(26, y);
}
retArray[count] = colValue;
count+=2;
}
return retArray;
}
}
//end of public class Application
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Reflection;
using Microsoft.CodeAnalysis;
namespace Microsoft.CodeAnalysis.Scripting
{
/// <summary>
/// A delegate that will run a script when invoked.
/// </summary>
/// <param name="globals">An object instance whose members can be accessed by the script as global variables.</param>
public delegate object ScriptRunner(object globals = null);
/// <summary>
/// A class that represents a script that you can run.
///
/// Create a script using a language specific script class such as CSharpScript or VisualBasicScript.
/// </summary>
public abstract class Script
{
private readonly string _code;
private readonly string _path;
private readonly ScriptOptions _options;
private readonly Type _globalsType;
private readonly Type _returnType;
private readonly Script _previous;
private ScriptBuilder _lazyBuilder;
private Compilation _lazyCompilation;
private Func<object[], object> _lazyExecutor;
private Func<ScriptExecutionState, object> _lazyAggrateScriptExecutor;
internal Script(string code, string path, ScriptOptions options, Type globalsType, Type returnType, ScriptBuilder builder, Script previous)
{
_code = code ?? "";
_path = path ?? "";
_options = options ?? ScriptOptions.Default;
_globalsType = globalsType;
_returnType = returnType ?? typeof(object);
_previous = previous;
if (_previous != null && builder != null && _previous._lazyBuilder != builder)
{
throw new ArgumentException("Incompatible script builder.");
}
_lazyBuilder = builder;
}
/// <summary>
/// A script that will run first when this script is run.
/// Any declarations made in the previous script can be referenced in this script.
/// The end state from running this script includes all declarations made by both scripts.
/// </summary>
public Script Previous
{
get { return _previous; }
}
/// <summary>
/// The options used by this script.
/// </summary>
public ScriptOptions Options
{
get { return _options; }
}
/// <summary>
/// The source code of the script.
/// </summary>
public string Code
{
get { return _code; }
}
/// <summary>
/// The path to the source if it originated from a file.
/// </summary>
public string Path
{
get { return _path; }
}
/// <summary>
/// The type of an object whose members can be accessed by the script as global variables.
/// </summary>
public Type GlobalsType
{
get { return _globalsType; }
}
/// <summary>
/// The expected return type of the script.
/// </summary>
public Type ReturnType
{
get { return _returnType; }
}
/// <summary>
/// The <see cref="ScriptBuilder"/> that will be used to build the script before running.
/// </summary>
internal ScriptBuilder Builder
{
get
{
if (_lazyBuilder == null)
{
ScriptBuilder tmp;
if (_previous != null)
{
tmp = _previous.Builder;
}
else
{
tmp = new ScriptBuilder();
}
Interlocked.CompareExchange(ref _lazyBuilder, tmp, null);
}
return _lazyBuilder;
}
}
/// <summary>
/// Creates a new version of this script with the specified options.
/// </summary>
public Script WithOptions(ScriptOptions options)
{
return this.With(options: options);
}
/// <summary>
/// Creates a new version of this script with the source code specified.
/// </summary>
/// <param name="code">The source code of the script.</param>
public Script WithCode(string code)
{
return this.With(code: code ?? "");
}
/// <summary>
/// Creates a new version of this script with the path specified.
/// The path is optional. It can be used to associate the script code with a file path.
/// </summary>
public Script WithPath(string path)
{
return this.With(path: path ?? "");
}
/// <summary>
/// Creates a new version of this script with the specified globals type.
/// The members of this type can be accessed by the script as global variables.
/// </summary>
/// <param name="globalsType">The type that defines members that can be accessed by the script.</param>
public Script WithGlobalsType(Type globalsType)
{
return this.With(globalsType: globalsType);
}
/// <summary>
/// Creates a new version of this script with the specified return type.
/// The default return type for a script is <see cref="System.Object"/>.
/// Specifying a return type may be necessary for proper understanding of some scripts.
/// </summary>
public Script WithReturnType(Type returnType)
{
return this.With(returnType: returnType);
}
/// <summary>
/// Creates a new version of this script with the previous script specified.
/// </summary>
public Script WithPrevious(Script script)
{
if (script != null)
{
return this.With(previous: script, globalsType: script.GlobalsType);
}
else
{
return this.With(previous: script);
}
}
/// <summary>
/// Creates a new version of this script with the <see cref="ScriptBuilder"/> specified.
/// </summary>
internal Script WithBuilder(ScriptBuilder builder)
{
return this.With(builder: builder);
}
private Script With(
Optional<string> code = default(Optional<string>),
Optional<string> path = default(Optional<string>),
Optional<ScriptOptions> options = default(Optional<ScriptOptions>),
Optional<Type> globalsType = default(Optional<Type>),
Optional<Type> returnType = default(Optional<Type>),
Optional<ScriptBuilder> builder = default(Optional<ScriptBuilder>),
Optional<Script> previous = default(Optional<Script>))
{
var newCode = code.HasValue ? code.Value : _code;
var newPath = path.HasValue ? path.Value : _path;
var newOptions = options.HasValue ? options.Value : _options;
var newGlobalsType = globalsType.HasValue ? globalsType.Value : _globalsType;
var newReturnType = returnType.HasValue ? returnType.Value : _returnType;
var newBuilder = builder.HasValue ? builder.Value : _lazyBuilder;
var newPrevious = previous.HasValue ? previous.Value : _previous;
if (ReferenceEquals(newCode, _code) &&
ReferenceEquals(newPath, _path) &&
newOptions == _options &&
newGlobalsType == _globalsType &&
newReturnType == _returnType &&
newBuilder == _lazyBuilder &&
newPrevious == this.Previous)
{
return this;
}
else
{
return this.Make(newCode, newPath, newOptions, newGlobalsType, newReturnType, newBuilder, newPrevious);
}
}
/// <summary>
/// Creates a new instance of a script of this type.
/// </summary>
internal abstract Script Make(string code, string path, ScriptOptions options, Type globalsType, Type returnType, ScriptBuilder builder, Script previous);
/// <summary>
/// Runs this script.
/// </summary>
/// <param name="globals">An object instance whose members can be accessed by the script as global variables,
/// or a <see cref="ScriptState"/> instance that was the output from a previously run script.</param>
/// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns>
public ScriptState Run(object globals = null)
{
var state = globals as ScriptState;
if (state != null)
{
if (state.Script == this)
{
// this state is already the output of running this script.
return state;
}
else if (this.Previous == null)
{
// if this script is unbound (no previous script) then run this script bound to the state's script
return this.WithPrevious(state.Script).Run(state);
}
else
{
// attempt to run script forward from the point after the specified state was computed.
ScriptExecutionState executionState;
object value;
if (this.TryRunFrom(state, out executionState, out value))
{
return new ScriptState(executionState, value, this);
}
else
{
throw new InvalidOperationException(ScriptingResources.StartingStateIncompatible);
}
}
}
else
{
if (_globalsType != null && globals == null)
{
throw new ArgumentNullException(nameof(globals));
}
else if (globals != null && _globalsType != null)
{
var runtimeType = globals.GetType().GetTypeInfo();
var globalsType = _globalsType.GetTypeInfo();
if (!globalsType.IsAssignableFrom(runtimeType))
{
throw new ArgumentException(string.Format(ScriptingResources.GlobalsNotAssignable, runtimeType, globalsType));
}
}
// make sure we are running from a script with matching globals type
if (globals != null && _globalsType == null)
{
return this.WithGlobalsType(globals.GetType()).Run(globals);
}
// run this script from the start with the specified globals
var executionState = ScriptExecutionState.Create(globals);
if (this.Previous == null)
{
// only single submission, so just execute it directly.
var executor = this.GetExecutor(CancellationToken.None);
var value = executionState.RunSubmission(executor);
return new ScriptState(executionState, value, this);
}
else
{
// otherwise run the aggregate script.
var executor = this.GetAggregateScriptExecutor(CancellationToken.None);
var value = executor(executionState);
return new ScriptState(executionState, value, this);
}
}
}
///<summary>
/// Continue running script from the point after the intermediate state was produced.
///</summary>
private bool TryRunFrom(ScriptState state, out ScriptExecutionState executionState, out object value)
{
if (state.Script == this)
{
value = state.ReturnValue;
executionState = state.ExecutionState.FreezeAndClone();
return true;
}
else if (_previous != null && _previous.TryRunFrom(state, out executionState, out value))
{
var executor = this.GetExecutor(CancellationToken.None);
value = executionState.RunSubmission(executor);
return true;
}
else
{
// couldn't find starting point to continue running from.
value = null;
executionState = null;
return false;
}
}
/// <summary>
/// Get's the <see cref="Compilation"/> that represents the semantics of the script.
/// </summary>
public Compilation GetCompilation()
{
if (_lazyCompilation == null)
{
var compilation = this.CreateCompilation();
Interlocked.CompareExchange(ref _lazyCompilation, compilation, null);
}
return _lazyCompilation;
}
/// <summary>
/// Forces the script through the build step.
/// If not called directly, the build step will occur on the first call to Run.
/// </summary>
public void Build()
{
this.GetExecutor(CancellationToken.None);
}
/// <summary>
/// Gets the references that need to be assigned to the compilation.
/// This can be different than the list of references defined by the <see cref="ScriptOptions"/> instance.
/// </summary>
protected ImmutableArray<MetadataReference> GetReferencesForCompilation()
{
var references = _options.References;
if (this.GlobalsType != null)
{
var globalsTypeAssembly = MetadataReference.CreateFromAssemblyInternal(this.GlobalsType.GetTypeInfo().Assembly);
if (!references.Contains(globalsTypeAssembly))
{
references = references.Add(globalsTypeAssembly);
}
}
if (_previous == null)
{
return references;
}
else
{
// TODO (tomat): RESOLVED? bound imports should be reused from previous submission instead of passing
// them to every submission in the chain. See bug #7802.
var compilation = _previous.GetCompilation();
return ImmutableArray.CreateRange(references.Union(compilation.References));
}
}
/// <summary>
/// Creates a <see cref="Compilation"/> instances based on script members.
/// </summary>
protected abstract Compilation CreateCompilation();
/// <summary>
/// Gets the executor that will run this portion of the script only. (does not include any previous scripts).
/// </summary>
private Func<object[], object> GetExecutor(CancellationToken cancellationToken)
{
if (_lazyExecutor == null)
{
var compilation = this.GetCompilation();
var diagnostics = DiagnosticBag.GetInstance();
try
{
// get compilation diagnostics first.
diagnostics.AddRange(compilation.GetParseDiagnostics());
if (diagnostics.HasAnyErrors())
{
CompilationError(diagnostics);
}
diagnostics.Clear();
var executor = this.Builder.Build(this, diagnostics, cancellationToken);
// emit can fail due to compilation errors or because there is nothing to emit:
if (diagnostics.HasAnyErrors())
{
CompilationError(diagnostics);
}
if (executor == null)
{
executor = (s) => null;
}
Interlocked.CompareExchange(ref _lazyExecutor, executor, null);
}
finally
{
diagnostics.Free();
}
}
return _lazyExecutor;
}
private void CompilationError(DiagnosticBag diagnostics)
{
var resolvedLocalDiagnostics = diagnostics.AsEnumerable();
var firstError = resolvedLocalDiagnostics.FirstOrDefault(d => d.Severity == DiagnosticSeverity.Error);
if (firstError != null)
{
throw new CompilationErrorException(FormatDiagnostic(firstError, CultureInfo.CurrentCulture),
(resolvedLocalDiagnostics.AsImmutable()));
}
}
protected abstract string FormatDiagnostic(Diagnostic diagnostic, CultureInfo culture);
/// <summary>
/// Creates a delegate that will execute this script when invoked.
/// </summary>
public ScriptRunner CreateDelegate(CancellationToken cancellationToken = default(CancellationToken))
{
var executor = this.GetAggregateScriptExecutor(cancellationToken);
return (globals) =>
{
var executionState = ScriptExecutionState.Create(globals);
return executor(executionState);
};
}
/// <summary>
/// Creates an executor that while run the entire aggregate script (all submissions).
/// </summary>
private Func<ScriptExecutionState, object> GetAggregateScriptExecutor(CancellationToken cancellationToken)
{
if (_lazyAggrateScriptExecutor == null)
{
Func<ScriptExecutionState, object> aggregateExecutor;
if (_previous == null)
{
// only one submission, just use the submission's entry point.
var executor = this.GetExecutor(cancellationToken);
aggregateExecutor = state => state.RunSubmission(executor);
}
else
{
// make a function to runs through all submissions in order.
var executors = new List<Func<object[], object>>();
this.GatherSubmissionExecutors(executors, cancellationToken);
aggregateExecutor = state =>
{
object result = null;
foreach (var exec in executors)
{
result = state.RunSubmission(exec);
}
return result;
};
}
Interlocked.CompareExchange(ref _lazyAggrateScriptExecutor, aggregateExecutor, null);
}
return _lazyAggrateScriptExecutor;
}
private void GatherSubmissionExecutors(List<Func<object[], object>> executors, CancellationToken cancellationToken)
{
if (_previous != null)
{
_previous.GatherSubmissionExecutors(executors, cancellationToken);
}
executors.Add(this.GetExecutor(cancellationToken));
}
}
}
| |
using UnityEngine;
using System;
namespace UnityStandardAssets.CinematicEffects
{
//Improvement ideas:
// In hdr do local tonemapping/inverse tonemapping to stabilize bokeh.
// Use rgba8 buffer in ldr / in some pass in hdr (in correlation to previous point and remapping coc from -1/0/1 to 0/0.5/1)
// Use temporal stabilisation.
// Add a mode to do bokeh texture in quarter res as well
// Support different near and far blur for the bokeh texture
// Try distance field for the bokeh texture.
// Try to separate the output of the blur pass to two rendertarget near+far, see the gain in quality vs loss in performance.
// Try swirl effect on the samples of the circle blur.
//References :
// This DOF implementation use ideas from public sources, a big thank to them :
// http://www.iryoku.com/next-generation-post-processing-in-call-of-duty-advanced-warfare
// http://www.crytek.com/download/Sousa_Graphics_Gems_CryENGINE3.pdf
// http://graphics.cs.williams.edu/papers/MedianShaderX6/
// http://http.developer.nvidia.com/GPUGems/gpugems_ch24.html
// http://vec3.ca/bicubic-filtering-in-fewer-taps/
[ExecuteInEditMode]
[AddComponentMenu("Image Effects/Other/DepthOfField")]
[RequireComponent(typeof(Camera))]
public class DepthOfField : MonoBehaviour
{
[AttributeUsage(AttributeTargets.Field)]
public sealed class GradientRangeAttribute : PropertyAttribute
{
public readonly float max;
public readonly float min;
// Attribute used to make a float or int variable in a script be restricted to a specific range.
public GradientRangeAttribute(float min, float max)
{
this.min = min;
this.max = max;
}
}
const float kMaxBlur = 35.0f;
private enum Passes
{
BlurAlphaWeighted = 0 ,
BoxBlur = 1 ,
DilateFgCocFromColor = 2 ,
DilateFgCoc = 3 ,
CaptureCoc = 4 ,
CaptureCocExplicit = 5 ,
VisualizeCoc = 6 ,
VisualizeCocExplicit = 7 ,
CocPrefilter = 8 ,
CircleBlur = 9 ,
CircleBlurWithDilatedFg = 10,
CircleBlurLowQuality = 11,
CircleBlowLowQualityWithDilatedFg = 12,
Merge = 13,
MergeExplicit = 14,
MergeBicubic = 15,
MergeExplicitBicubic = 16,
ShapeLowQuality = 17,
ShapeLowQualityDilateFg = 18,
ShapeLowQualityMerge = 19,
ShapeLowQualityMergeDilateFg = 20,
ShapeMediumQuality = 21,
ShapeMediumQualityDilateFg = 22,
ShapeMediumQualityMerge = 23,
ShapeMediumQualityMergeDilateFg = 24,
ShapeHighQuality = 25,
ShapeHighQualityDilateFg = 26,
ShapeHighQualityMerge = 27,
ShapeHighQualityMergeDilateFg = 28
}
public enum MedianPasses
{
Median3 = 0,
Median3X3 = 1
}
public enum BokehTexturesPasses
{
Apply = 0,
Collect = 1
}
public enum UIMode
{
Basic,
Advanced,
Explicit
}
public enum ApertureShape
{
Circular,
Hexagonal,
Octogonal
}
public enum FilterQuality
{
None,
Normal,
High
}
[Tooltip("Allow to view where the blur will be applied. Yellow for near blur, Blue for far blur.")]
public bool visualizeBluriness = false;
[Tooltip("When enabled quality settings can be hand picked, rather than being driven by the quality slider.")]
public bool customizeQualitySettings = false;
public bool prefilterBlur = true;
public FilterQuality medianFilter = FilterQuality.High;
public bool dilateNearBlur = true;
public bool highQualityUpsampling = true;
[GradientRange(0.0f, 100.0f)]
[Tooltip("Color represent relative performance. From green (faster) to yellow (slower).")]
public float quality = 100.0f;
[Range(0.0f, 1.0f)]
public float focusPlane = 0.225f;
[Range(0.0f, 1.0f)]
public float focusRange = 0.9f;
[Range(0.0f, 1.0f)]
public float nearPlane = 0.0f;
[Range(0.0f, kMaxBlur)]
public float nearRadius = 20.0f;
[Range(0.0f, 1.0f)]
public float farPlane = 1.0f;
[Range(0.0f, kMaxBlur)]
public float farRadius = 20.0f;
[Range(0.0f, kMaxBlur)]
public float radius = 20.0f;
[Range(0.5f, 4.0f)]
public float boostPoint = 0.75f;
[Range(0.0f, 1.0f)]
public float nearBoostAmount = 0.0f;
[Range(0.0f, 1.0f)]
public float farBoostAmount = 0.0f;
[Range(0.0f, 32.0f)]
public float fStops = 5.0f;
[Range(0.01f, 5.0f)]
public float textureBokehScale = 1.0f;
[Range(0.01f, 100.0f)]
public float textureBokehIntensity = 50.0f;
[Range(0.01f, 50.0f)]
public float textureBokehThreshold = 2.0f;
[Range(0.01f, 1.0f)]
public float textureBokehSpawnHeuristic = 0.15f;
public Transform focusTransform = null;
public Texture2D bokehTexture = null;
public ApertureShape apertureShape = ApertureShape.Circular;
[Range(0.0f, 179.0f)]
public float apertureOrientation = 0.0f;
[Tooltip("Use with care Bokeh texture are only available on shader model 5, and performance scale with the number of bokehs.")]
public bool useBokehTexture;
public UIMode uiMode = UIMode.Basic;
public Shader filmicDepthOfFieldShader;
public Shader medianFilterShader;
public Shader textureBokehShader;
[NonSerialized]
private RenderTexureUtility m_RTU = new RenderTexureUtility();
public Material filmicDepthOfFieldMaterial
{
get
{
if (m_FilmicDepthOfFieldMaterial == null)
m_FilmicDepthOfFieldMaterial = ImageEffectHelper.CheckShaderAndCreateMaterial(filmicDepthOfFieldShader);
return m_FilmicDepthOfFieldMaterial;
}
}
public Material medianFilterMaterial
{
get
{
if (m_MedianFilterMaterial == null)
m_MedianFilterMaterial = ImageEffectHelper.CheckShaderAndCreateMaterial(medianFilterShader);
return m_MedianFilterMaterial;
}
}
public Material textureBokehMaterial
{
get
{
if (m_TextureBokehMaterial == null)
m_TextureBokehMaterial = ImageEffectHelper.CheckShaderAndCreateMaterial(textureBokehShader);
return m_TextureBokehMaterial;
}
}
public ComputeBuffer computeBufferDrawArgs
{
get
{
if (m_ComputeBufferDrawArgs == null)
{
m_ComputeBufferDrawArgs = new ComputeBuffer(1, 16, ComputeBufferType.IndirectArguments);
var args = new int[4];
args[0] = 0;
args[1] = 1;
args[2] = 0;
args[3] = 0;
m_ComputeBufferDrawArgs.SetData(args);
}
return m_ComputeBufferDrawArgs;
}
}
public ComputeBuffer computeBufferPoints
{
get
{
if (m_ComputeBufferPoints == null)
{
m_ComputeBufferPoints = new ComputeBuffer(90000, 12 + 16, ComputeBufferType.Append);
}
return m_ComputeBufferPoints;
}
}
private ComputeBuffer m_ComputeBufferDrawArgs;
private ComputeBuffer m_ComputeBufferPoints;
private Material m_FilmicDepthOfFieldMaterial;
private Material m_MedianFilterMaterial;
private Material m_TextureBokehMaterial;
private float m_LastApertureOrientation;
private Vector4 m_OctogonalBokehDirection1;
private Vector4 m_OctogonalBokehDirection2;
private Vector4 m_OctogonalBokehDirection3;
private Vector4 m_OctogonalBokehDirection4;
private Vector4 m_HexagonalBokehDirection1;
private Vector4 m_HexagonalBokehDirection2;
private Vector4 m_HexagonalBokehDirection3;
protected void OnEnable()
{
if (filmicDepthOfFieldShader == null)
filmicDepthOfFieldShader = Shader.Find("Hidden/DepthOfField/DepthOfField");
if (medianFilterShader == null)
medianFilterShader = Shader.Find("Hidden/DepthOfField/MedianFilter");
if (textureBokehShader == null)
textureBokehShader = Shader.Find("Hidden/DepthOfField/BokehSplatting");
if (!ImageEffectHelper.IsSupported(filmicDepthOfFieldShader, true, true, this)
|| !ImageEffectHelper.IsSupported(medianFilterShader, true, true, this)
)
{
enabled = false;
Debug.LogWarning("The image effect " + ToString() + " has been disabled as it's not supported on the current platform.");
return;
}
if (ImageEffectHelper.supportsDX11)
{
if (!ImageEffectHelper.IsSupported(textureBokehShader, true, true, this))
{
enabled = false;
Debug.LogWarning("The image effect " + ToString() + " has been disabled as it's not supported on the current platform.");
return;
}
}
ComputeBlurDirections(true);
GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth;
}
protected void OnDisable()
{
ReleaseComputeResources();
if (m_FilmicDepthOfFieldMaterial)
DestroyImmediate(m_FilmicDepthOfFieldMaterial);
if (m_TextureBokehMaterial)
DestroyImmediate(m_TextureBokehMaterial);
if (m_MedianFilterMaterial)
DestroyImmediate(m_MedianFilterMaterial);
m_TextureBokehMaterial = null;
m_FilmicDepthOfFieldMaterial = null;
m_MedianFilterMaterial = null;
m_RTU.ReleaseAllTemporyRenderTexutres();
}
//-------------------------------------------------------------------//
// Main entry point //
//-------------------------------------------------------------------//
public void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (medianFilterMaterial == null || filmicDepthOfFieldMaterial == null)
{
Graphics.Blit(source, destination);
return;
}
if (visualizeBluriness)
{
Vector4 blurrinessParam;
Vector4 blurrinessCoe;
ComputeCocParameters(out blurrinessParam, out blurrinessCoe);
filmicDepthOfFieldMaterial.SetVector("_BlurParams", blurrinessParam);
filmicDepthOfFieldMaterial.SetVector("_BlurCoe", blurrinessCoe);
Graphics.Blit(null, destination, filmicDepthOfFieldMaterial, (uiMode == UIMode.Explicit) ? (int)Passes.VisualizeCocExplicit : (int)Passes.VisualizeCoc);
}
else
{
DoDepthOfField(source, destination);
}
m_RTU.ReleaseAllTemporyRenderTexutres();
}
private void DoDepthOfField(RenderTexture source, RenderTexture destination)
{
float radiusAdjustement = source.height / 720.0f;
float textureBokehScale = radiusAdjustement;
float textureBokehMaxRadius = Mathf.Max(nearRadius, farRadius) * textureBokehScale * 0.75f;
float nearBlurRadius = nearRadius * radiusAdjustement;
float farBlurRadius = farRadius * radiusAdjustement;
float maxBlurRadius = Mathf.Max(nearBlurRadius, farBlurRadius);
switch (apertureShape)
{
case ApertureShape.Hexagonal: maxBlurRadius *= 1.2f; break;
case ApertureShape.Octogonal: maxBlurRadius *= 1.15f; break;
}
if (maxBlurRadius < 0.5f)
{
Graphics.Blit(source, destination);
return;
}
//Quarter resolution
int rtW = source.width / 2;
int rtH = source.height / 2;
Vector4 blurrinessCoe = new Vector4(nearBlurRadius * 0.5f, farBlurRadius * 0.5f, 0.0f, 0.0f);
RenderTexture colorAndCoc = m_RTU.GetTemporaryRenderTexture(rtW, rtH);
RenderTexture colorAndCoc2 = m_RTU.GetTemporaryRenderTexture(rtW, rtH);
// Downsample to Color + COC buffer and apply boost
Vector4 cocParam;
Vector4 cocCoe;
ComputeCocParameters(out cocParam, out cocCoe);
filmicDepthOfFieldMaterial.SetVector("_BlurParams", cocParam);
filmicDepthOfFieldMaterial.SetVector("_BlurCoe", cocCoe);
filmicDepthOfFieldMaterial.SetVector("_BoostParams", new Vector4(nearBlurRadius * nearBoostAmount * -0.5f, farBlurRadius * farBoostAmount * 0.5f, boostPoint, 0.0f));
Graphics.Blit(source, colorAndCoc2, filmicDepthOfFieldMaterial, (uiMode == UIMode.Explicit) ? (int)Passes.CaptureCocExplicit : (int)Passes.CaptureCoc);
RenderTexture src = colorAndCoc2;
RenderTexture dst = colorAndCoc;
// Collect texture bokeh candidates and replace with a darker pixel
if (shouldPerformBokeh)
{
// Blur a bit so we can do a frequency check
RenderTexture blurred = m_RTU.GetTemporaryRenderTexture(rtW, rtH);
Graphics.Blit(src, blurred, filmicDepthOfFieldMaterial, (int)Passes.BoxBlur);
filmicDepthOfFieldMaterial.SetVector("_Offsets", new Vector4(0.0f, 1.5f, 0.0f, 1.5f));
Graphics.Blit(blurred, dst, filmicDepthOfFieldMaterial, (int)Passes.BlurAlphaWeighted);
filmicDepthOfFieldMaterial.SetVector("_Offsets", new Vector4(1.5f, 0.0f, 0.0f, 1.5f));
Graphics.Blit(dst, blurred, filmicDepthOfFieldMaterial, (int)Passes.BlurAlphaWeighted);
// Collect texture bokeh candidates and replace with a darker pixel
textureBokehMaterial.SetTexture("_BlurredColor", blurred);
textureBokehMaterial.SetFloat("_SpawnHeuristic", textureBokehSpawnHeuristic);
textureBokehMaterial.SetVector("_BokehParams", new Vector4(this.textureBokehScale * textureBokehScale, textureBokehIntensity, textureBokehThreshold, textureBokehMaxRadius));
Graphics.SetRandomWriteTarget(1, computeBufferPoints);
Graphics.Blit(src, dst, textureBokehMaterial, (int)BokehTexturesPasses.Collect);
Graphics.ClearRandomWriteTargets();
SwapRenderTexture(ref src, ref dst);
m_RTU.ReleaseTemporaryRenderTexture(blurred);
}
filmicDepthOfFieldMaterial.SetVector("_BlurParams", cocParam);
filmicDepthOfFieldMaterial.SetVector("_BlurCoe", blurrinessCoe);
filmicDepthOfFieldMaterial.SetVector("_BoostParams", new Vector4(nearBlurRadius * nearBoostAmount * -0.5f, farBlurRadius * farBoostAmount * 0.5f, boostPoint, 0.0f));
// Dilate near blur factor
RenderTexture blurredFgCoc = null;
if (dilateNearBlur)
{
RenderTexture blurredFgCoc2 = m_RTU.GetTemporaryRenderTexture(rtW, rtH, 0, RenderTextureFormat.RGHalf);
blurredFgCoc = m_RTU.GetTemporaryRenderTexture(rtW, rtH, 0, RenderTextureFormat.RGHalf);
filmicDepthOfFieldMaterial.SetVector("_Offsets", new Vector4(0.0f, nearBlurRadius * 0.75f, 0.0f, 0.0f));
Graphics.Blit(src, blurredFgCoc2, filmicDepthOfFieldMaterial, (int)Passes.DilateFgCocFromColor);
filmicDepthOfFieldMaterial.SetVector("_Offsets", new Vector4(nearBlurRadius * 0.75f, 0.0f, 0.0f, 0.0f));
Graphics.Blit(blurredFgCoc2, blurredFgCoc, filmicDepthOfFieldMaterial, (int)Passes.DilateFgCoc);
m_RTU.ReleaseTemporaryRenderTexture(blurredFgCoc2);
}
// Blur downsampled color to fill the gap between samples
if (prefilterBlur)
{
Graphics.Blit(src, dst, filmicDepthOfFieldMaterial, (int)Passes.CocPrefilter);
SwapRenderTexture(ref src, ref dst);
}
// Apply blur : Circle / Hexagonal or Octagonal (blur will create bokeh if bright pixel where not removed by "m_UseBokehTexture")
switch (apertureShape)
{
case ApertureShape.Circular: DoCircularBlur(blurredFgCoc, ref src, ref dst, maxBlurRadius); break;
case ApertureShape.Hexagonal: DoHexagonalBlur(blurredFgCoc, ref src, ref dst, maxBlurRadius); break;
case ApertureShape.Octogonal: DoOctogonalBlur(blurredFgCoc, ref src, ref dst, maxBlurRadius); break;
}
// Smooth result
switch (medianFilter)
{
case FilterQuality.Normal:
{
medianFilterMaterial.SetVector("_Offsets", new Vector4(1.0f, 0.0f, 0.0f, 0.0f));
Graphics.Blit(src, dst, medianFilterMaterial, (int)MedianPasses.Median3);
SwapRenderTexture(ref src, ref dst);
medianFilterMaterial.SetVector("_Offsets", new Vector4(0.0f, 1.0f, 0.0f, 0.0f));
Graphics.Blit(src, dst, medianFilterMaterial, (int)MedianPasses.Median3);
SwapRenderTexture(ref src, ref dst);
break;
}
case FilterQuality.High:
{
Graphics.Blit(src, dst, medianFilterMaterial, (int)MedianPasses.Median3X3);
SwapRenderTexture(ref src, ref dst);
break;
}
}
// Merge to full resolution (with boost) + upsampling (linear or bicubic)
filmicDepthOfFieldMaterial.SetVector("_BlurCoe", blurrinessCoe);
filmicDepthOfFieldMaterial.SetVector("_Convolved_TexelSize", new Vector4(src.width, src.height, 1.0f / src.width, 1.0f / src.height));
filmicDepthOfFieldMaterial.SetTexture("_SecondTex", src);
int mergePass = (uiMode == UIMode.Explicit) ? (int)Passes.MergeExplicit : (int)Passes.Merge;
if (highQualityUpsampling)
{
mergePass = (uiMode == UIMode.Explicit) ? (int)Passes.MergeExplicitBicubic : (int)Passes.MergeBicubic;
}
// Apply texture bokeh
if (shouldPerformBokeh)
{
RenderTexture tmp = m_RTU.GetTemporaryRenderTexture(source.height, source.width, 0, source.format);
Graphics.Blit(source, tmp, filmicDepthOfFieldMaterial, mergePass);
Graphics.SetRenderTarget(tmp);
ComputeBuffer.CopyCount(computeBufferPoints, computeBufferDrawArgs, 0);
textureBokehMaterial.SetBuffer("pointBuffer", computeBufferPoints);
textureBokehMaterial.SetTexture("_MainTex", bokehTexture);
textureBokehMaterial.SetVector("_Screen", new Vector3(1.0f / (1.0f * source.width), 1.0f / (1.0f * source.height), textureBokehMaxRadius));
textureBokehMaterial.SetPass((int)BokehTexturesPasses.Apply);
Graphics.DrawProceduralIndirect(MeshTopology.Points, computeBufferDrawArgs, 0);
Graphics.Blit(tmp, destination);// hackaround for DX11 flipfun (OPTIMIZEME)
}
else
{
Graphics.Blit(source, destination, filmicDepthOfFieldMaterial, mergePass);
}
}
//-------------------------------------------------------------------//
// Blurs //
//-------------------------------------------------------------------//
private void DoHexagonalBlur(RenderTexture blurredFgCoc, ref RenderTexture src, ref RenderTexture dst, float maxRadius)
{
ComputeBlurDirections(false);
int blurPass;
int blurPassMerge;
GetDirectionalBlurPassesFromRadius(blurredFgCoc, maxRadius, out blurPass, out blurPassMerge);
filmicDepthOfFieldMaterial.SetTexture("_SecondTex", blurredFgCoc);
RenderTexture tmp = m_RTU.GetTemporaryRenderTexture(src.width, src.height, 0, src.format);
filmicDepthOfFieldMaterial.SetVector("_Offsets", m_HexagonalBokehDirection1);
Graphics.Blit(src, tmp, filmicDepthOfFieldMaterial, blurPass);
filmicDepthOfFieldMaterial.SetVector("_Offsets", m_HexagonalBokehDirection2);
Graphics.Blit(tmp, src, filmicDepthOfFieldMaterial, blurPass);
filmicDepthOfFieldMaterial.SetVector("_Offsets", m_HexagonalBokehDirection3);
filmicDepthOfFieldMaterial.SetTexture("_ThirdTex", src);
Graphics.Blit(tmp, dst, filmicDepthOfFieldMaterial, blurPassMerge);
m_RTU.ReleaseTemporaryRenderTexture(tmp);
SwapRenderTexture(ref src, ref dst);
}
private void DoOctogonalBlur(RenderTexture blurredFgCoc, ref RenderTexture src, ref RenderTexture dst, float maxRadius)
{
ComputeBlurDirections(false);
int blurPass;
int blurPassMerge;
GetDirectionalBlurPassesFromRadius(blurredFgCoc, maxRadius, out blurPass, out blurPassMerge);
filmicDepthOfFieldMaterial.SetTexture("_SecondTex", blurredFgCoc);
RenderTexture tmp = m_RTU.GetTemporaryRenderTexture(src.width, src.height, 0, src.format);
filmicDepthOfFieldMaterial.SetVector("_Offsets", m_OctogonalBokehDirection1);
Graphics.Blit(src, tmp, filmicDepthOfFieldMaterial, blurPass);
filmicDepthOfFieldMaterial.SetVector("_Offsets", m_OctogonalBokehDirection2);
Graphics.Blit(tmp, dst, filmicDepthOfFieldMaterial, blurPass);
filmicDepthOfFieldMaterial.SetVector("_Offsets", m_OctogonalBokehDirection3);
Graphics.Blit(src, tmp, filmicDepthOfFieldMaterial, blurPass);
filmicDepthOfFieldMaterial.SetVector("_Offsets", m_OctogonalBokehDirection4);
filmicDepthOfFieldMaterial.SetTexture("_ThirdTex", dst);
Graphics.Blit(tmp, src, filmicDepthOfFieldMaterial, blurPassMerge);
m_RTU.ReleaseTemporaryRenderTexture(tmp);
}
private void DoCircularBlur(RenderTexture blurredFgCoc, ref RenderTexture src, ref RenderTexture dst, float maxRadius)
{
int bokehPass;
if (blurredFgCoc != null)
{
filmicDepthOfFieldMaterial.SetTexture("_SecondTex", blurredFgCoc);
bokehPass = (maxRadius > 10.0f) ? (int)Passes.CircleBlurWithDilatedFg : (int)Passes.CircleBlowLowQualityWithDilatedFg;
}
else
{
bokehPass = (maxRadius > 10.0f) ? (int)Passes.CircleBlur : (int)Passes.CircleBlurLowQuality;
}
Graphics.Blit(src, dst, filmicDepthOfFieldMaterial, bokehPass);
SwapRenderTexture(ref src, ref dst);
}
//-------------------------------------------------------------------//
// Helpers //
//-------------------------------------------------------------------//
private void ComputeCocParameters(out Vector4 blurParams, out Vector4 blurCoe)
{
Camera sceneCamera = GetComponent<Camera>();
float focusDistance01 = focusTransform ? (sceneCamera.WorldToViewportPoint(focusTransform.position)).z / (sceneCamera.farClipPlane) : (focusPlane * focusPlane * focusPlane * focusPlane);
if (uiMode == UIMode.Basic || uiMode == UIMode.Advanced)
{
float focusRange01 = focusRange * focusRange * focusRange * focusRange;
float focalLength = 4.0f / Mathf.Tan(0.5f * sceneCamera.fieldOfView * Mathf.Deg2Rad);
float aperture = focalLength / fStops;
blurCoe = new Vector4(0.0f, 0.0f, 1.0f, 1.0f);
blurParams = new Vector4(aperture, focalLength, focusDistance01, focusRange01);
}
else
{
float nearDistance01 = nearPlane * nearPlane * nearPlane * nearPlane;
float farDistance01 = farPlane * farPlane * farPlane * farPlane;
float nearFocusRange01 = focusRange * focusRange * focusRange * focusRange;
float farFocusRange01 = nearFocusRange01;
if (focusDistance01 <= nearDistance01)
focusDistance01 = nearDistance01 + 0.0000001f;
if (focusDistance01 >= farDistance01)
focusDistance01 = farDistance01 - 0.0000001f;
if ((focusDistance01 - nearFocusRange01) <= nearDistance01)
nearFocusRange01 = (focusDistance01 - nearDistance01 - 0.0000001f);
if ((focusDistance01 + farFocusRange01) >= farDistance01)
farFocusRange01 = (farDistance01 - focusDistance01 - 0.0000001f);
float a1 = 1.0f / (nearDistance01 - focusDistance01 + nearFocusRange01);
float a2 = 1.0f / (farDistance01 - focusDistance01 - farFocusRange01);
float b1 = (1.0f - a1 * nearDistance01), b2 = (1.0f - a2 * farDistance01);
const float c1 = -1.0f;
const float c2 = 1.0f;
blurParams = new Vector4(c1 * a1, c1 * b1, c2 * a2, c2 * b2);
blurCoe = new Vector4(0.0f, 0.0f, (b2 - b1) / (a1 - a2), 0.0f);
}
}
private void ReleaseComputeResources()
{
if (m_ComputeBufferDrawArgs != null)
m_ComputeBufferDrawArgs.Release();
m_ComputeBufferDrawArgs = null;
if (m_ComputeBufferPoints != null)
m_ComputeBufferPoints.Release();
m_ComputeBufferPoints = null;
}
private void ComputeBlurDirections(bool force)
{
if (!force && Math.Abs(m_LastApertureOrientation - apertureOrientation) < float.Epsilon) return;
m_LastApertureOrientation = apertureOrientation;
float rotationRadian = apertureOrientation * Mathf.Deg2Rad;
float cosinus = Mathf.Cos(rotationRadian);
float sinus = Mathf.Sin(rotationRadian);
m_OctogonalBokehDirection1 = new Vector4(0.5f, 0.0f, 0.0f, 0.0f);
m_OctogonalBokehDirection2 = new Vector4(0.0f, 0.5f, 1.0f, 0.0f);
m_OctogonalBokehDirection3 = new Vector4(-0.353553f, 0.353553f, 1.0f, 0.0f);
m_OctogonalBokehDirection4 = new Vector4(0.353553f, 0.353553f, 1.0f, 0.0f);
m_HexagonalBokehDirection1 = new Vector4(0.5f, 0.0f, 0.0f, 0.0f);
m_HexagonalBokehDirection2 = new Vector4(0.25f, 0.433013f, 1.0f, 0.0f);
m_HexagonalBokehDirection3 = new Vector4(0.25f, -0.433013f, 1.0f, 0.0f);
if (rotationRadian > float.Epsilon)
{
Rotate2D(ref m_OctogonalBokehDirection1, cosinus, sinus);
Rotate2D(ref m_OctogonalBokehDirection2, cosinus, sinus);
Rotate2D(ref m_OctogonalBokehDirection3, cosinus, sinus);
Rotate2D(ref m_OctogonalBokehDirection4, cosinus, sinus);
Rotate2D(ref m_HexagonalBokehDirection1, cosinus, sinus);
Rotate2D(ref m_HexagonalBokehDirection2, cosinus, sinus);
Rotate2D(ref m_HexagonalBokehDirection3, cosinus, sinus);
}
}
private bool shouldPerformBokeh
{
get { return ImageEffectHelper.supportsDX11 && useBokehTexture && textureBokehMaterial; }
}
private static void Rotate2D(ref Vector4 direction, float cosinus, float sinus)
{
Vector4 source = direction;
direction.x = source.x * cosinus - source.y * sinus;
direction.y = source.x * sinus + source.y * cosinus;
}
private static void SwapRenderTexture(ref RenderTexture src, ref RenderTexture dst)
{
RenderTexture tmp = dst;
dst = src;
src = tmp;
}
private static void GetDirectionalBlurPassesFromRadius(RenderTexture blurredFgCoc, float maxRadius, out int blurPass, out int blurAndMergePass)
{
if (blurredFgCoc == null)
{
if (maxRadius > 10.0f)
{
blurPass = (int)Passes.ShapeHighQuality;
blurAndMergePass = (int)Passes.ShapeHighQualityMerge;
}
else if (maxRadius > 5.0f)
{
blurPass = (int)Passes.ShapeMediumQuality;
blurAndMergePass = (int)Passes.ShapeMediumQualityMerge;
}
else
{
blurPass = (int)Passes.ShapeLowQuality;
blurAndMergePass = (int)Passes.ShapeLowQualityMerge;
}
}
else
{
if (maxRadius > 10.0f)
{
blurPass = (int)Passes.ShapeHighQualityDilateFg;
blurAndMergePass = (int)Passes.ShapeHighQualityMergeDilateFg;
}
else if (maxRadius > 5.0f)
{
blurPass = (int)Passes.ShapeMediumQualityDilateFg;
blurAndMergePass = (int)Passes.ShapeMediumQualityMergeDilateFg;
}
else
{
blurPass = (int)Passes.ShapeLowQualityDilateFg;
blurAndMergePass = (int)Passes.ShapeLowQualityMergeDilateFg;
}
}
}
}
}
| |
//
// FeedItem.cs
//
// Authors:
// Mike Urbanski <michael.c.urbanski@gmail.com>
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2007 Michael C. Urbanski
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Hyena;
using Hyena.Data.Sqlite;
namespace Migo.Syndication
{
public class FeedItemProvider : MigoModelProvider<FeedItem>
{
public FeedItemProvider (HyenaSqliteConnection connection) : base (connection, "PodcastItems")
{
}
}
public class FeedItem : MigoItem<FeedItem>
{
private static SqliteModelProvider<FeedItem> provider;
public static SqliteModelProvider<FeedItem> Provider {
get { return provider; }
}
public static bool Exists (long feed_id, string guid)
{
return Provider.Connection.Query<int> (
String.Format ("SELECT count(*) FROM {0} WHERE FeedID = ? AND Guid = ?", Provider.TableName),
feed_id, guid
) != 0;
}
public static void Init () {
provider = new FeedItemProvider (FeedsManager.Instance.Connection);
}
private bool active = true;
private string author;
private string comments;
private string description;
private string stripped_description;
private FeedEnclosure enclosure;
private string guid;
private bool isRead;
private string link;
private long dbid;
private DateTime modified;
private Feed feed;
private DateTime pubDate;
private string title;
#region Database-backed Properties
[DatabaseColumn ("ItemID", Constraints = DatabaseColumnConstraints.PrimaryKey)]
public override long DbId {
get { return dbid; }
protected set { dbid = value; }
}
[DatabaseColumn("FeedID", Index = "PodcastItemsFeedIDIndex")]
protected long feed_id;
public long FeedId {
get { return feed_id; }
}
[DatabaseColumn]
internal bool Active {
get { return active;}
set {
if (value != active) {
active = value;
}
}
}
[DatabaseColumn]
public string Author {
get { return author; }
set { author = value; }
}
[DatabaseColumn]
public string Comments {
get { return comments; }
set { comments = value; }
}
[DatabaseColumn]
public string Description {
get { return description; }
set {
description = value;
}
}
[DatabaseColumn]
public string StrippedDescription {
get { return stripped_description; }
set { stripped_description = value; }
}
[DatabaseColumn("Guid", Index = "PodcastItemsGuidIndex")]
public string Guid {
get {
if (String.IsNullOrEmpty (guid)) {
guid = String.Format ("{0}-{1}", Title,
PubDate.ToUniversalTime ().ToString (System.Globalization.DateTimeFormatInfo.InvariantInfo)
);
}
return guid;
}
set { guid = value; }
}
[DatabaseColumn("IsRead", Index = "PodcastItemIsReadIndex")]
public bool IsRead {
get { return isRead; }
set { isRead = value; }
}
[DatabaseColumn]
public string Link {
get { return link; }
set { link = value; }
}
[DatabaseColumn]
public DateTime Modified {
get { return modified; }
set { modified = value; }
}
[DatabaseColumn]
public DateTime PubDate {
get { return pubDate; }
set { pubDate = value; }
}
[DatabaseColumn]
public string Title {
get { return title; }
set { title = value; }
}
[DatabaseColumn("LicenseUri")]
protected string license_uri;
public string LicenseUri {
get { return license_uri; }
set { license_uri = value; }
}
#endregion
#region Properties
public Feed Feed {
get {
if (feed == null && feed_id > 0) {
feed = Feed.Provider.FetchSingle (feed_id);
}
return feed;
}
internal set { feed = value; feed_id = value.DbId; }
}
public FeedEnclosure Enclosure {
get {
if (enclosure == null) {
LoadEnclosure ();
}
return enclosure;
}
internal set {
enclosure = value;
enclosure_loaded = true;
if (enclosure != null)
enclosure.Item = this;
}
}
#endregion
#region Constructor
public FeedItem ()
{
}
#endregion
private static FeedManager Manager {
get { return FeedsManager.Instance.FeedManager; }
}
#region Public Methods
public void UpdateStrippedDescription ()
{
StrippedDescription = Hyena.StringUtil.RemoveHtml (Description);
if (StrippedDescription != null) {
StrippedDescription = System.Web.HttpUtility.HtmlDecode (StrippedDescription);
}
}
public void Save ()
{
Save (true);
}
internal void Save (bool notify)
{
bool is_new = DbId < 1;
Provider.Save (this);
if (enclosure != null) {
enclosure.Item = this;
enclosure.Save (false);
}
if (is_new)
Manager.OnItemAdded (this);
else
Manager.OnItemChanged (this);
}
public void Delete (bool delete_file)
{
if (enclosure != null) {
enclosure.Delete (delete_file);
}
Provider.Delete (this);
Manager.OnItemRemoved (this);
}
#endregion
private bool enclosure_loaded;
private void LoadEnclosure ()
{
if (!enclosure_loaded && DbId > 0) {
FeedEnclosure enclosure = FeedEnclosure.Provider.FetchFirstMatching (String.Format (
"{0}.ItemID = {1}", FeedEnclosure.Provider.TableName, DbId
));
if (enclosure != null) {
enclosure.Item = this;
this.enclosure = enclosure;
}
enclosure_loaded = true;
}
}
}
}
| |
using System;
using System.Reflection;
using System.Collections.Generic;
namespace Avalonia.Media
{
internal static class KnownColors
{
private static readonly IReadOnlyDictionary<string, KnownColor> _knownColorNames;
private static readonly IReadOnlyDictionary<uint, string> _knownColors;
#if !BUILDTASK
private static readonly Dictionary<KnownColor, ISolidColorBrush> _knownBrushes;
#endif
static KnownColors()
{
var knownColorNames = new Dictionary<string, KnownColor>(StringComparer.OrdinalIgnoreCase);
var knownColors = new Dictionary<uint, string>();
foreach (var field in typeof(KnownColor).GetRuntimeFields())
{
if (field.FieldType != typeof(KnownColor)) continue;
var knownColor = (KnownColor)field.GetValue(null)!;
if (knownColor == KnownColor.None) continue;
knownColorNames.Add(field.Name, knownColor);
// some known colors have the same value, so use the first
if (!knownColors.ContainsKey((uint)knownColor))
{
knownColors.Add((uint)knownColor, field.Name);
}
}
_knownColorNames = knownColorNames;
_knownColors = knownColors;
#if !BUILDTASK
_knownBrushes = new Dictionary<KnownColor, ISolidColorBrush>();
#endif
}
#if !BUILDTASK
public static ISolidColorBrush? GetKnownBrush(string s)
{
var color = GetKnownColor(s);
return color != KnownColor.None ? color.ToBrush() : null;
}
#endif
public static KnownColor GetKnownColor(string s)
{
if (_knownColorNames.TryGetValue(s, out var color))
{
return color;
}
return KnownColor.None;
}
public static string? GetKnownColorName(uint rgb)
{
return _knownColors.TryGetValue(rgb, out var name) ? name : null;
}
public static Color ToColor(this KnownColor color)
{
return Color.FromUInt32((uint)color);
}
#if !BUILDTASK
public static ISolidColorBrush ToBrush(this KnownColor color)
{
lock (_knownBrushes)
{
if (!_knownBrushes.TryGetValue(color, out var brush))
{
brush = new Immutable.ImmutableSolidColorBrush(color.ToColor());
_knownBrushes.Add(color, brush);
}
return brush;
}
}
#endif
}
internal enum KnownColor : uint
{
None,
AliceBlue = 0xfff0f8ff,
AntiqueWhite = 0xfffaebd7,
Aqua = 0xff00ffff,
Aquamarine = 0xff7fffd4,
Azure = 0xfff0ffff,
Beige = 0xfff5f5dc,
Bisque = 0xffffe4c4,
Black = 0xff000000,
BlanchedAlmond = 0xffffebcd,
Blue = 0xff0000ff,
BlueViolet = 0xff8a2be2,
Brown = 0xffa52a2a,
BurlyWood = 0xffdeb887,
CadetBlue = 0xff5f9ea0,
Chartreuse = 0xff7fff00,
Chocolate = 0xffd2691e,
Coral = 0xffff7f50,
CornflowerBlue = 0xff6495ed,
Cornsilk = 0xfffff8dc,
Crimson = 0xffdc143c,
Cyan = 0xff00ffff,
DarkBlue = 0xff00008b,
DarkCyan = 0xff008b8b,
DarkGoldenrod = 0xffb8860b,
DarkGray = 0xffa9a9a9,
DarkGreen = 0xff006400,
DarkKhaki = 0xffbdb76b,
DarkMagenta = 0xff8b008b,
DarkOliveGreen = 0xff556b2f,
DarkOrange = 0xffff8c00,
DarkOrchid = 0xff9932cc,
DarkRed = 0xff8b0000,
DarkSalmon = 0xffe9967a,
DarkSeaGreen = 0xff8fbc8f,
DarkSlateBlue = 0xff483d8b,
DarkSlateGray = 0xff2f4f4f,
DarkTurquoise = 0xff00ced1,
DarkViolet = 0xff9400d3,
DeepPink = 0xffff1493,
DeepSkyBlue = 0xff00bfff,
DimGray = 0xff696969,
DodgerBlue = 0xff1e90ff,
Firebrick = 0xffb22222,
FloralWhite = 0xfffffaf0,
ForestGreen = 0xff228b22,
Fuchsia = 0xffff00ff,
Gainsboro = 0xffdcdcdc,
GhostWhite = 0xfff8f8ff,
Gold = 0xffffd700,
Goldenrod = 0xffdaa520,
Gray = 0xff808080,
Green = 0xff008000,
GreenYellow = 0xffadff2f,
Honeydew = 0xfff0fff0,
HotPink = 0xffff69b4,
IndianRed = 0xffcd5c5c,
Indigo = 0xff4b0082,
Ivory = 0xfffffff0,
Khaki = 0xfff0e68c,
Lavender = 0xffe6e6fa,
LavenderBlush = 0xfffff0f5,
LawnGreen = 0xff7cfc00,
LemonChiffon = 0xfffffacd,
LightBlue = 0xffadd8e6,
LightCoral = 0xfff08080,
LightCyan = 0xffe0ffff,
LightGoldenrodYellow = 0xfffafad2,
LightGreen = 0xff90ee90,
LightGray = 0xffd3d3d3,
LightPink = 0xffffb6c1,
LightSalmon = 0xffffa07a,
LightSeaGreen = 0xff20b2aa,
LightSkyBlue = 0xff87cefa,
LightSlateGray = 0xff778899,
LightSteelBlue = 0xffb0c4de,
LightYellow = 0xffffffe0,
Lime = 0xff00ff00,
LimeGreen = 0xff32cd32,
Linen = 0xfffaf0e6,
Magenta = 0xffff00ff,
Maroon = 0xff800000,
MediumAquamarine = 0xff66cdaa,
MediumBlue = 0xff0000cd,
MediumOrchid = 0xffba55d3,
MediumPurple = 0xff9370db,
MediumSeaGreen = 0xff3cb371,
MediumSlateBlue = 0xff7b68ee,
MediumSpringGreen = 0xff00fa9a,
MediumTurquoise = 0xff48d1cc,
MediumVioletRed = 0xffc71585,
MidnightBlue = 0xff191970,
MintCream = 0xfff5fffa,
MistyRose = 0xffffe4e1,
Moccasin = 0xffffe4b5,
NavajoWhite = 0xffffdead,
Navy = 0xff000080,
OldLace = 0xfffdf5e6,
Olive = 0xff808000,
OliveDrab = 0xff6b8e23,
Orange = 0xffffa500,
OrangeRed = 0xffff4500,
Orchid = 0xffda70d6,
PaleGoldenrod = 0xffeee8aa,
PaleGreen = 0xff98fb98,
PaleTurquoise = 0xffafeeee,
PaleVioletRed = 0xffdb7093,
PapayaWhip = 0xffffefd5,
PeachPuff = 0xffffdab9,
Peru = 0xffcd853f,
Pink = 0xffffc0cb,
Plum = 0xffdda0dd,
PowderBlue = 0xffb0e0e6,
Purple = 0xff800080,
Red = 0xffff0000,
RosyBrown = 0xffbc8f8f,
RoyalBlue = 0xff4169e1,
SaddleBrown = 0xff8b4513,
Salmon = 0xfffa8072,
SandyBrown = 0xfff4a460,
SeaGreen = 0xff2e8b57,
SeaShell = 0xfffff5ee,
Sienna = 0xffa0522d,
Silver = 0xffc0c0c0,
SkyBlue = 0xff87ceeb,
SlateBlue = 0xff6a5acd,
SlateGray = 0xff708090,
Snow = 0xfffffafa,
SpringGreen = 0xff00ff7f,
SteelBlue = 0xff4682b4,
Tan = 0xffd2b48c,
Teal = 0xff008080,
Thistle = 0xffd8bfd8,
Tomato = 0xffff6347,
Transparent = 0x00ffffff,
Turquoise = 0xff40e0d0,
Violet = 0xffee82ee,
Wheat = 0xfff5deb3,
White = 0xffffffff,
WhiteSmoke = 0xfff5f5f5,
Yellow = 0xffffff00,
YellowGreen = 0xff9acd32
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PcapDotNet.Packets;
using PcapDotNet.Packets.Dns;
using PcapDotNet.Packets.Ethernet;
using PcapDotNet.Packets.Gre;
using PcapDotNet.Packets.Http;
using PcapDotNet.Packets.Icmp;
using PcapDotNet.Packets.IpV4;
using PcapDotNet.Packets.TestUtils;
using PcapDotNet.Packets.Transport;
using PcapDotNet.TestUtils;
namespace PcapDotNet.Core.Test
{
/// <summary>
/// Summary description for WiresharkCompareTests
/// </summary>
[TestClass]
public class WiresharkCompareTests
{
private const string WiresharkDiretory = @"C:\Program Files\Wireshark\";
private const string WiresharkTsharkPath = WiresharkDiretory + @"tshark.exe";
private static bool IsRetry
{
get { return RetryNumber != -1; }
}
private const int RetryNumber = -1;
/// <summary>
/// Gets or sets the test context which provides
/// information about and functionality for the current test run.
/// </summary>
public TestContext TestContext { get; set; }
#region Additional test attributes
//
// You can use the following additional attributes as you write your tests:
//
// Use ClassInitialize to run code before running the first test in the class
// [ClassInitialize()]
// public static void MyClassInitialize(TestContext testContext) { }
//
// Use ClassCleanup to run code after all tests in a class have run
// [ClassCleanup()]
// public static void MyClassCleanup() { }
//
// Use TestInitialize to run code before running each test
// [TestInitialize()]
// public void MyTestInitialize() { }
//
// Use TestCleanup to run code after each test has run
// [TestCleanup()]
// public void MyTestCleanup() { }
//
#endregion
[TestMethod]
public void ComparePacketsToWiresharkTest()
{
#pragma warning disable 162 // This code is unreachable on purpose
if (IsRetry)
{
ComparePacketsToWireshark(null);
return;
}
#pragma warning restore 162
Random random = new Random();
for (int i = 0; i != 10; ++i)
{
// Create packets
List<Packet> packets = new List<Packet>(CreateRandomPackets(random, 200));
// Compare packets to wireshark
ComparePacketsToWireshark(packets);
}
}
[TestMethod]
public void CompareTimestampPacketsToWiresharkTest()
{
const long Ticks = 633737178954260865;
DateTime timestamp = new DateTime(Ticks).ToUniversalTime().ToLocalTime();
// Create packet
Packet packet = new Packet(new byte[14], timestamp, DataLinkKind.Ethernet);
// Compare packet to wireshark
ComparePacketsToWireshark(new[] { packet });
// BUG: Limited timestamp due to Windows bug: https://connect.microsoft.com/VisualStudio/feedback/details/559198/net-4-datetime-tolocaltime-is-sometimes-wrong
// Now check different dates.
// packet = new Packet(new byte[14], new DateTime(2004,08,25,10,36,41, DateTimeKind.Utc).ToLocalTime(), DataLinkKind.Ethernet);
// ComparePacketsToWireshark(new[] { packet });
}
[TestMethod]
public void CompareEthernetTrailerToWiresharkTest()
{
const string PacketString = "001120cf0900000c29566988080045000029627b00008006de80c0a8640bc0a81477a42cc03bdd3c481c6cfcd72050104278a5a90000000e01bf0101";
Packet packet = Packet.FromHexadecimalString(PacketString, DateTime.Now, DataLinkKind.Ethernet);
ComparePacketsToWireshark(packet);
}
[TestMethod]
public void CompareVLanTaggedFrameTrailerToWiresharkTest()
{
const string PacketString =
"0004f2402ffca870a5002e02810001f408060001080006040001a870a5002e02ac141401000000000000ac1414670000000000000000000000000000";
Packet packet = Packet.FromHexadecimalString(PacketString, DateTime.Now, DataLinkKind.Ethernet);
ComparePacketsToWireshark(packet);
}
[TestMethod]
public void CompareEthernetFcsToWiresharkTest()
{
Packet packet = PacketBuilder.Build(DateTime.Now,
new EthernetLayer(),
new IpV4Layer
{
Protocol = IpV4Protocol.Udp
});
byte[] buffer = new byte[packet.Length + 100];
new Random().NextBytes(buffer);
packet.CopyTo(buffer, 0);
packet = new Packet(buffer, DateTime.Now, DataLinkKind.Ethernet);
ComparePacketsToWireshark(packet);
}
[TestMethod]
public void CompareHInvalidHttpRequestUriToWiresharkTest()
{
Packet packet = Packet.FromHexadecimalString(
"0013f7a44dc0000c2973b9bb0800450001642736400080060000c0a80126c0002b0a12710050caa94b1f450b454950180100ae2f0000474554202f442543332542437273742" +
"f3fefbca120485454502f312e310d0a4163636570743a20746578742f68746d6c2c206170706c69636174696f6e2f7868746d6c2b786d6c2c202a2f2a0d0a52656665726572" +
"3a20687474703a2f2f6c6f6f6b6f75742e6e65742f746573742f6972692f6d6978656e632e7068700d0a4163636570742d4c616e67756167653a20656e2d55530d0a5573657" +
"22d4167656e743a204d6f7a696c6c612f352e302028636f6d70617469626c653b204d53494520392e303b2057696e646f7773204e5420362e313b20574f5736343b20547269" +
"64656e742f352e30290d0a4163636570742d456e636f64696e673a20677a69702c206465666c6174650d0a486f73743a207777772e6578616d706c652e636f6d0d0a436f6e6" +
"e656374696f6e3a204b6565702d416c6976650d0a0d0a",
DateTime.Now, DataLinkKind.Ethernet);
ComparePacketsToWireshark(packet);
}
[TestMethod]
public void CompareIpV4DataLinkToWiresharkTest()
{
ComparePacketsToWireshark(
// Normal.
Packet.FromHexadecimalString("46000028000000000102c48601487eebe0000016940400002200f9010000000104000000e00000fc", DateTime.Now, DataLinkKind.IpV4),
// dns.response_to.
Packet.FromHexadecimalString(
"45000107400100003a110e4adc9fd4c801487eeb0035c8db00f3ead1fb96818000010001000500050436746f340469707636096d6963726f736f667403636f6d0000010001c00c0001000100000dbb00",
DateTime.Now, DataLinkKind.IpV4),
// TCP Checksum is bad because of too big IP total length.
Packet.FromHexadecimalString(
"450000a8392040003706944a4a7dab3501487eeb0050cb50800f365664e4726250180089df90000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
DateTime.Now, DataLinkKind.IpV4),
// TCP Checksum is zero.
Packet.FromHexadecimalString(
"450005dc54224000370674144a7dab3501487eeb0050cb5080a8136c64e4726250100089000000002db2707095328b271a9acf128e85be789f0e5ea6cb9d6f13f32481f6baf855420b60fe5c4053407e",
DateTime.Now, DataLinkKind.IpV4));
}
[TestMethod]
public void CompareTcpZeroChecksumToWiresharkTest()
{
ComparePacketsToWireshark(
PacketBuilder.Build(DateTime.Now,
new EthernetLayer(),
new IpV4Layer
{
Ttl = 128
},
new TcpLayer
{
Checksum = 0,
Window = 100,
},
new PayloadLayer
{
Data = new Datagram(new byte[10])
}));
}
private static Packet CreateRandomPacket(Random random)
{
Packet packet;
do
{
// TODO. BUG: Limited timestamp due to Windows bug: https://connect.microsoft.com/VisualStudio/feedback/details/559198/net-4-datetime-tolocaltime-is-sometimes-wrong
DateTime packetTimestamp =
random.NextDateTime(new DateTime(2010, 1, 1), new DateTime(2010, 12, 31)).ToUniversalTime().ToLocalTime();
//random.NextDateTime(PacketTimestamp.MinimumPacketTimestamp, PacketTimestamp.MaximumPacketTimestamp).ToUniversalTime().ToLocalTime();
List<ILayer> layers = new List<ILayer>();
EthernetLayer ethernetLayer = random.NextEthernetLayer();
layers.Add(ethernetLayer);
CreateRandomEthernetPayload(random, ethernetLayer, layers);
packet = PacketBuilder.Build(packetTimestamp, layers);
} while (packet.Length > 65536);
return packet;
}
private static void CreateRandomEthernetPayload(Random random, EthernetBaseLayer ethernetBaseLayer, List<ILayer> layers)
{
if (random.NextBool(20))
{
// Finish with payload.
PayloadLayer payloadLayer = random.NextPayloadLayer(random.Next(100));
layers.Add(payloadLayer);
return;
}
ethernetBaseLayer.EtherType = EthernetType.None;
switch (random.NextInt(0, 5))
{
case 0: // VLanTaggedFrame.
case 1:
VLanTaggedFrameLayer vLanTaggedFrameLayer = random.NextVLanTaggedFrameLayer();
layers.Add(vLanTaggedFrameLayer);
CreateRandomEthernetPayload(random, vLanTaggedFrameLayer, layers);
return;
case 2: // ARP.
EthernetLayer ethernetLayer = (ethernetBaseLayer as EthernetLayer);
if (ethernetLayer != null)
ethernetLayer.Destination = MacAddress.Zero;
layers.Add(random.NextArpLayer());
return;
case 3: // IPv4.
case 4:
IpV4Layer ipV4Layer = random.NextIpV4Layer();
layers.Add(ipV4Layer);
CreateRandomIpV4Payload(random, ipV4Layer, layers);
return;
default:
throw new InvalidOperationException("Invalid value.");
}
}
private static void CreateRandomIpV4Payload(Random random, IpV4Layer ipV4Layer, List<ILayer> layers)
{
if (random.NextBool(20))
{
// Finish with payload.
PayloadLayer payloadLayer = random.NextPayloadLayer(random.Next(100));
layers.Add(payloadLayer);
return;
}
ipV4Layer.Protocol = null;
if (random.NextBool())
ipV4Layer.Fragmentation = IpV4Fragmentation.None;
switch (random.Next(0, 9))
{
case 0: // IpV4.
case 1:
IpV4Layer innerIpV4Layer = random.NextIpV4Layer();
layers.Add(innerIpV4Layer);
CreateRandomIpV4Payload(random, innerIpV4Layer, layers);
return;
case 2: // Igmp.
layers.Add(random.NextIgmpLayer());
return;
case 3: // Icmp.
IcmpLayer icmpLayer = random.NextIcmpLayer();
layers.Add(icmpLayer);
layers.AddRange(random.NextIcmpPayloadLayers(icmpLayer));
return;
case 4: // Gre.
GreLayer greLayer = random.NextGreLayer();
layers.Add(greLayer);
CreateRandomEthernetPayload(random, greLayer, layers);
return;
case 5: // Udp.
case 6:
UdpLayer udpLayer = random.NextUdpLayer();
layers.Add(udpLayer);
CreateRandomUdpPayload(random, udpLayer, layers);
return;
case 7: // Tcp.
case 8:
TcpLayer tcpLayer = random.NextTcpLayer();
layers.Add(tcpLayer);
CreateRandomTcpPayload(random, tcpLayer, layers);
return;
default:
throw new InvalidOperationException("Invalid value.");
}
}
private static void CreateRandomUdpPayload(Random random, UdpLayer udpLayer, List<ILayer> layers)
{
if (random.NextBool(20))
{
// Finish with payload.
PayloadLayer payloadLayer = random.NextPayloadLayer(random.Next(100));
layers.Add(payloadLayer);
return;
}
DnsLayer dnsLayer = random.NextDnsLayer();
layers.Add(dnsLayer);
ushort specialPort = (ushort)(random.NextBool() ? 53 : 5355);
if (dnsLayer.IsQuery)
udpLayer.DestinationPort = specialPort;
else
udpLayer.SourcePort = specialPort;
}
private static void CreateRandomTcpPayload(Random random, TcpLayer tcpLayer, List<ILayer> layers)
{
if (random.NextBool(20))
{
// Finish with payload.
PayloadLayer payloadLayer = random.NextPayloadLayer(random.Next(100));
layers.Add(payloadLayer);
return;
}
HttpLayer httpLayer = random.NextHttpLayer();
layers.Add(httpLayer);
if (httpLayer.IsRequest)
tcpLayer.DestinationPort = 80;
else
tcpLayer.SourcePort = 80;
if (random.NextBool())
return;
HttpLayer httpLayer2 = httpLayer.IsRequest ? (HttpLayer)random.NextHttpRequestLayer() : random.NextHttpResponseLayer();
layers.Add(httpLayer2);
}
private static IEnumerable<Packet> CreateRandomPackets(Random random, int numPackets)
{
for (int i = 0; i != numPackets; ++i)
{
Packet packet = CreateRandomPacket(random);
yield return packet;
}
}
private static void ComparePacketsToWireshark(params Packet[] packets)
{
ComparePacketsToWireshark((IEnumerable<Packet>)packets);
}
private static void ComparePacketsToWireshark(IEnumerable<Packet> packets)
{
string pcapFilename = Path.GetTempPath() + "temp." + new Random().NextByte() + ".pcap";
#pragma warning disable 162
// ReSharper disable ConditionIsAlwaysTrueOrFalse
// ReSharper disable HeuristicUnreachableCode
if (!IsRetry)
{
PacketDumpFile.Dump(pcapFilename, new PcapDataLink(packets.First().DataLink.Kind), PacketDevice.DefaultSnapshotLength, packets);
}
else
{
pcapFilename = Path.GetTempPath() + "temp." + RetryNumber + ".pcap";
List<Packet> packetsList = new List<Packet>();
using (PacketCommunicator communicator = new OfflinePacketDevice(pcapFilename).Open())
{
communicator.ReceivePackets(-1, packetsList.Add);
}
packets = packetsList;
}
// ReSharper restore HeuristicUnreachableCode
// ReSharper restore ConditionIsAlwaysTrueOrFalse
#pragma warning restore 162
// Create pdml file
string documentFilename = pcapFilename + ".pdml";
using (Process process = new Process())
{
process.StartInfo = new ProcessStartInfo
{
// Wireshark's preferences file is %APPDATA%\Wireshark\preferences
FileName = WiresharkTsharkPath,
Arguments = "-o udp.check_checksum:TRUE " +
"-o tcp.relative_sequence_numbers:FALSE " +
"-o tcp.analyze_sequence_numbers:FALSE " +
"-o tcp.track_bytes_in_flight:FALSE " +
"-o tcp.desegment_tcp_streams:FALSE " +
"-o tcp.check_checksum:TRUE " +
"-o http.dechunk_body:FALSE " +
"-t r -n -r \"" + pcapFilename + "\" -T pdml",
WorkingDirectory = WiresharkDiretory,
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
};
Console.WriteLine("Starting process " + process.StartInfo.FileName + " " + process.StartInfo.Arguments);
process.Start();
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
File.WriteAllText(documentFilename, output);
}
// Fix pdml file
string fixedDocumentFilename = documentFilename + ".fixed";
File.WriteAllBytes(fixedDocumentFilename, new List<byte>(from b in File.ReadAllBytes(documentFilename)
select b == 0x0A || b == 0x0D
? b
: Math.Max((byte)0x20, Math.Min(b, (byte)0x7F))).ToArray());
try
{
Compare(XDocument.Load(fixedDocumentFilename), packets);
}
catch (AssertFailedException exception)
{
throw new AssertFailedException("Failed comparing packets in file " + pcapFilename + ". Message: " + exception.Message, exception);
}
}
private static void Compare(XDocument document, IEnumerable<Packet> packets)
{
IEnumerator<Packet> packetEnumerator = packets.GetEnumerator();
List<Packet> failedPackets = new List<Packet>();
StringBuilder failureMessage = new StringBuilder();
// Parse XML
int i = 1;
foreach (var documentPacket in document.Element("pdml").Elements("packet"))
{
packetEnumerator.MoveNext();
Packet packet = packetEnumerator.Current;
try
{
ComparePacket(packet, documentPacket);
}
catch (Exception e)
{
failedPackets.Add(packet);
failureMessage.Append(new AssertFailedException("Failed comparing packet " + i + ". " + e.Message, e) + Environment.NewLine);
}
++i;
}
if (failedPackets.Any())
{
PacketDumpFile.Dump(Path.GetTempPath() + "temp." + 1000 + ".pcap", failedPackets.First().DataLink.Kind, 65536, failedPackets);
throw new AssertFailedException("Failed comparing " + failedPackets.Count + " packets:" + Environment.NewLine + failureMessage);
}
}
private static void ComparePacket(Packet packet, XElement documentPacket)
{
object currentDatagram = packet;
CompareProtocols(currentDatagram, documentPacket);
}
internal static void CompareProtocols(object currentDatagram, XElement layersContainer)
{
foreach (var layer in layersContainer.Protocols())
{
switch (layer.Name())
{
case "geninfo":
case "raw":
break;
case "frame":
CompareFrame(layer, (Packet)currentDatagram);
break;
default:
var comparer = WiresharkDatagramComparer.GetComparer(layer.Name());
if (comparer == null)
return;
currentDatagram = comparer.Compare(layer, currentDatagram);
if (currentDatagram == null)
return;
break;
}
}
}
private static void CompareFrame(XElement frame, Packet packet)
{
foreach (var field in frame.Fields())
{
switch (field.Name())
{
// case "frame.time":
// string fieldShow = field.Show();
// if (fieldShow == "Not representable")
// break;
// fieldShow = fieldShow.Substring(0, fieldShow.Length - 2);
// DateTime fieldTimestamp = fieldShow[4] == ' '
// ? DateTime.ParseExact(fieldShow, "MMM d, yyyy HH:mm:ss.fffffff", CultureInfo.InvariantCulture)
// : DateTime.ParseExact(fieldShow, "MMM dd, yyyy HH:mm:ss.fffffff", CultureInfo.InvariantCulture);
// MoreAssert.IsInRange(fieldTimestamp.AddSeconds(-2), fieldTimestamp.AddSeconds(2), packet.Timestamp, "Timestamp");
// break;
case "frame.time_epoch":
double timeEpoch = double.Parse(field.Show());
DateTime fieldTimestamp = new DateTime(1970, 1, 1).AddSeconds(timeEpoch);
MoreAssert.IsInRange(fieldTimestamp.AddMilliseconds(-1), fieldTimestamp.AddMilliseconds(1), packet.Timestamp.ToUniversalTime(), "Timestamp");
break;
case "frame.len":
field.AssertShowDecimal(packet.Length);
break;
}
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/api/auth.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 Google.Api {
/// <summary>Holder for reflection information generated from google/api/auth.proto</summary>
public static partial class AuthReflection {
#region Descriptor
/// <summary>File descriptor for google/api/auth.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static AuthReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChVnb29nbGUvYXBpL2F1dGgucHJvdG8SCmdvb2dsZS5hcGkaHGdvb2dsZS9h",
"cGkvYW5ub3RhdGlvbnMucHJvdG8ibAoOQXV0aGVudGljYXRpb24SLQoFcnVs",
"ZXMYAyADKAsyHi5nb29nbGUuYXBpLkF1dGhlbnRpY2F0aW9uUnVsZRIrCglw",
"cm92aWRlcnMYBCADKAsyGC5nb29nbGUuYXBpLkF1dGhQcm92aWRlciKpAQoS",
"QXV0aGVudGljYXRpb25SdWxlEhAKCHNlbGVjdG9yGAEgASgJEiwKBW9hdXRo",
"GAIgASgLMh0uZ29vZ2xlLmFwaS5PQXV0aFJlcXVpcmVtZW50cxIgChhhbGxv",
"d193aXRob3V0X2NyZWRlbnRpYWwYBSABKAgSMQoMcmVxdWlyZW1lbnRzGAcg",
"AygLMhsuZ29vZ2xlLmFwaS5BdXRoUmVxdWlyZW1lbnQiTwoMQXV0aFByb3Zp",
"ZGVyEgoKAmlkGAEgASgJEg4KBmlzc3VlchgCIAEoCRIQCghqd2tzX3VyaRgD",
"IAEoCRIRCglhdWRpZW5jZXMYBCABKAkiLQoRT0F1dGhSZXF1aXJlbWVudHMS",
"GAoQY2Fub25pY2FsX3Njb3BlcxgBIAEoCSI5Cg9BdXRoUmVxdWlyZW1lbnQS",
"EwoLcHJvdmlkZXJfaWQYASABKAkSEQoJYXVkaWVuY2VzGAIgASgJQmsKDmNv",
"bS5nb29nbGUuYXBpQglBdXRoUHJvdG9QAVpFZ29vZ2xlLmdvbGFuZy5vcmcv",
"Z2VucHJvdG8vZ29vZ2xlYXBpcy9hcGkvc2VydmljZWNvbmZpZztzZXJ2aWNl",
"Y29uZmlnogIER0FQSWIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Authentication), global::Google.Api.Authentication.Parser, new[]{ "Rules", "Providers" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.AuthenticationRule), global::Google.Api.AuthenticationRule.Parser, new[]{ "Selector", "Oauth", "AllowWithoutCredential", "Requirements" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.AuthProvider), global::Google.Api.AuthProvider.Parser, new[]{ "Id", "Issuer", "JwksUri", "Audiences" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.OAuthRequirements), global::Google.Api.OAuthRequirements.Parser, new[]{ "CanonicalScopes" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.AuthRequirement), global::Google.Api.AuthRequirement.Parser, new[]{ "ProviderId", "Audiences" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// `Authentication` defines the authentication configuration for an API.
///
/// Example for an API targeted for external use:
///
/// name: calendar.googleapis.com
/// authentication:
/// providers:
/// - id: google_calendar_auth
/// jwks_uri: https://www.googleapis.com/oauth2/v1/certs
/// issuer: https://securetoken.google.com
/// rules:
/// - selector: "*"
/// requirements:
/// provider_id: google_calendar_auth
/// </summary>
public sealed partial class Authentication : pb::IMessage<Authentication> {
private static readonly pb::MessageParser<Authentication> _parser = new pb::MessageParser<Authentication>(() => new Authentication());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Authentication> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.AuthReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Authentication() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Authentication(Authentication other) : this() {
rules_ = other.rules_.Clone();
providers_ = other.providers_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Authentication Clone() {
return new Authentication(this);
}
/// <summary>Field number for the "rules" field.</summary>
public const int RulesFieldNumber = 3;
private static readonly pb::FieldCodec<global::Google.Api.AuthenticationRule> _repeated_rules_codec
= pb::FieldCodec.ForMessage(26, global::Google.Api.AuthenticationRule.Parser);
private readonly pbc::RepeatedField<global::Google.Api.AuthenticationRule> rules_ = new pbc::RepeatedField<global::Google.Api.AuthenticationRule>();
/// <summary>
/// A list of authentication rules that apply to individual API methods.
///
/// **NOTE:** All service configuration rules follow "last one wins" order.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Api.AuthenticationRule> Rules {
get { return rules_; }
}
/// <summary>Field number for the "providers" field.</summary>
public const int ProvidersFieldNumber = 4;
private static readonly pb::FieldCodec<global::Google.Api.AuthProvider> _repeated_providers_codec
= pb::FieldCodec.ForMessage(34, global::Google.Api.AuthProvider.Parser);
private readonly pbc::RepeatedField<global::Google.Api.AuthProvider> providers_ = new pbc::RepeatedField<global::Google.Api.AuthProvider>();
/// <summary>
/// Defines a set of authentication providers that a service supports.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Api.AuthProvider> Providers {
get { return providers_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Authentication);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Authentication other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!rules_.Equals(other.rules_)) return false;
if(!providers_.Equals(other.providers_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= rules_.GetHashCode();
hash ^= providers_.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) {
rules_.WriteTo(output, _repeated_rules_codec);
providers_.WriteTo(output, _repeated_providers_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += rules_.CalculateSize(_repeated_rules_codec);
size += providers_.CalculateSize(_repeated_providers_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Authentication other) {
if (other == null) {
return;
}
rules_.Add(other.rules_);
providers_.Add(other.providers_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 26: {
rules_.AddEntriesFrom(input, _repeated_rules_codec);
break;
}
case 34: {
providers_.AddEntriesFrom(input, _repeated_providers_codec);
break;
}
}
}
}
}
/// <summary>
/// Authentication rules for the service.
///
/// By default, if a method has any authentication requirements, every request
/// must include a valid credential matching one of the requirements.
/// It's an error to include more than one kind of credential in a single
/// request.
///
/// If a method doesn't have any auth requirements, request credentials will be
/// ignored.
/// </summary>
public sealed partial class AuthenticationRule : pb::IMessage<AuthenticationRule> {
private static readonly pb::MessageParser<AuthenticationRule> _parser = new pb::MessageParser<AuthenticationRule>(() => new AuthenticationRule());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<AuthenticationRule> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.AuthReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AuthenticationRule() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AuthenticationRule(AuthenticationRule other) : this() {
selector_ = other.selector_;
Oauth = other.oauth_ != null ? other.Oauth.Clone() : null;
allowWithoutCredential_ = other.allowWithoutCredential_;
requirements_ = other.requirements_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AuthenticationRule Clone() {
return new AuthenticationRule(this);
}
/// <summary>Field number for the "selector" field.</summary>
public const int SelectorFieldNumber = 1;
private string selector_ = "";
/// <summary>
/// Selects the methods to which this rule applies.
///
/// Refer to [selector][google.api.DocumentationRule.selector] for syntax details.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Selector {
get { return selector_; }
set {
selector_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "oauth" field.</summary>
public const int OauthFieldNumber = 2;
private global::Google.Api.OAuthRequirements oauth_;
/// <summary>
/// The requirements for OAuth credentials.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Api.OAuthRequirements Oauth {
get { return oauth_; }
set {
oauth_ = value;
}
}
/// <summary>Field number for the "allow_without_credential" field.</summary>
public const int AllowWithoutCredentialFieldNumber = 5;
private bool allowWithoutCredential_;
/// <summary>
/// Whether to allow requests without a credential. The credential can be
/// an OAuth token, Google cookies (first-party auth) or EndUserCreds.
///
/// For requests without credentials, if the service control environment is
/// specified, each incoming request **must** be associated with a service
/// consumer. This can be done by passing an API key that belongs to a consumer
/// project.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool AllowWithoutCredential {
get { return allowWithoutCredential_; }
set {
allowWithoutCredential_ = value;
}
}
/// <summary>Field number for the "requirements" field.</summary>
public const int RequirementsFieldNumber = 7;
private static readonly pb::FieldCodec<global::Google.Api.AuthRequirement> _repeated_requirements_codec
= pb::FieldCodec.ForMessage(58, global::Google.Api.AuthRequirement.Parser);
private readonly pbc::RepeatedField<global::Google.Api.AuthRequirement> requirements_ = new pbc::RepeatedField<global::Google.Api.AuthRequirement>();
/// <summary>
/// Requirements for additional authentication providers.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Api.AuthRequirement> Requirements {
get { return requirements_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as AuthenticationRule);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(AuthenticationRule other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Selector != other.Selector) return false;
if (!object.Equals(Oauth, other.Oauth)) return false;
if (AllowWithoutCredential != other.AllowWithoutCredential) return false;
if(!requirements_.Equals(other.requirements_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Selector.Length != 0) hash ^= Selector.GetHashCode();
if (oauth_ != null) hash ^= Oauth.GetHashCode();
if (AllowWithoutCredential != false) hash ^= AllowWithoutCredential.GetHashCode();
hash ^= requirements_.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) {
if (Selector.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Selector);
}
if (oauth_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Oauth);
}
if (AllowWithoutCredential != false) {
output.WriteRawTag(40);
output.WriteBool(AllowWithoutCredential);
}
requirements_.WriteTo(output, _repeated_requirements_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Selector.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Selector);
}
if (oauth_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Oauth);
}
if (AllowWithoutCredential != false) {
size += 1 + 1;
}
size += requirements_.CalculateSize(_repeated_requirements_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(AuthenticationRule other) {
if (other == null) {
return;
}
if (other.Selector.Length != 0) {
Selector = other.Selector;
}
if (other.oauth_ != null) {
if (oauth_ == null) {
oauth_ = new global::Google.Api.OAuthRequirements();
}
Oauth.MergeFrom(other.Oauth);
}
if (other.AllowWithoutCredential != false) {
AllowWithoutCredential = other.AllowWithoutCredential;
}
requirements_.Add(other.requirements_);
}
[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: {
Selector = input.ReadString();
break;
}
case 18: {
if (oauth_ == null) {
oauth_ = new global::Google.Api.OAuthRequirements();
}
input.ReadMessage(oauth_);
break;
}
case 40: {
AllowWithoutCredential = input.ReadBool();
break;
}
case 58: {
requirements_.AddEntriesFrom(input, _repeated_requirements_codec);
break;
}
}
}
}
}
/// <summary>
/// Configuration for an anthentication provider, including support for
/// [JSON Web Token (JWT)](https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32).
/// </summary>
public sealed partial class AuthProvider : pb::IMessage<AuthProvider> {
private static readonly pb::MessageParser<AuthProvider> _parser = new pb::MessageParser<AuthProvider>(() => new AuthProvider());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<AuthProvider> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.AuthReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AuthProvider() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AuthProvider(AuthProvider other) : this() {
id_ = other.id_;
issuer_ = other.issuer_;
jwksUri_ = other.jwksUri_;
audiences_ = other.audiences_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AuthProvider Clone() {
return new AuthProvider(this);
}
/// <summary>Field number for the "id" field.</summary>
public const int IdFieldNumber = 1;
private string id_ = "";
/// <summary>
/// The unique identifier of the auth provider. It will be referred to by
/// `AuthRequirement.provider_id`.
///
/// Example: "bookstore_auth".
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Id {
get { return id_; }
set {
id_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "issuer" field.</summary>
public const int IssuerFieldNumber = 2;
private string issuer_ = "";
/// <summary>
/// Identifies the principal that issued the JWT. See
/// https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.1
/// Usually a URL or an email address.
///
/// Example: https://securetoken.google.com
/// Example: 1234567-compute@developer.gserviceaccount.com
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Issuer {
get { return issuer_; }
set {
issuer_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "jwks_uri" field.</summary>
public const int JwksUriFieldNumber = 3;
private string jwksUri_ = "";
/// <summary>
/// URL of the provider's public key set to validate signature of the JWT. See
/// [OpenID Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata).
/// Optional if the key set document:
/// - can be retrieved from
/// [OpenID Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html
/// of the issuer.
/// - can be inferred from the email domain of the issuer (e.g. a Google service account).
///
/// Example: https://www.googleapis.com/oauth2/v1/certs
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string JwksUri {
get { return jwksUri_; }
set {
jwksUri_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "audiences" field.</summary>
public const int AudiencesFieldNumber = 4;
private string audiences_ = "";
/// <summary>
/// The list of JWT
/// [audiences](https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.3).
/// that are allowed to access. A JWT containing any of these audiences will
/// be accepted. When this setting is absent, only JWTs with audience
/// "https://[Service_name][google.api.Service.name]/[API_name][google.protobuf.Api.name]"
/// will be accepted. For example, if no audiences are in the setting,
/// LibraryService API will only accept JWTs with the following audience
/// "https://library-example.googleapis.com/google.example.library.v1.LibraryService".
///
/// Example:
///
/// audiences: bookstore_android.apps.googleusercontent.com,
/// bookstore_web.apps.googleusercontent.com
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Audiences {
get { return audiences_; }
set {
audiences_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as AuthProvider);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(AuthProvider other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Id != other.Id) return false;
if (Issuer != other.Issuer) return false;
if (JwksUri != other.JwksUri) return false;
if (Audiences != other.Audiences) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Id.Length != 0) hash ^= Id.GetHashCode();
if (Issuer.Length != 0) hash ^= Issuer.GetHashCode();
if (JwksUri.Length != 0) hash ^= JwksUri.GetHashCode();
if (Audiences.Length != 0) hash ^= Audiences.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) {
if (Id.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Id);
}
if (Issuer.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Issuer);
}
if (JwksUri.Length != 0) {
output.WriteRawTag(26);
output.WriteString(JwksUri);
}
if (Audiences.Length != 0) {
output.WriteRawTag(34);
output.WriteString(Audiences);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Id.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Id);
}
if (Issuer.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Issuer);
}
if (JwksUri.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(JwksUri);
}
if (Audiences.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Audiences);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(AuthProvider other) {
if (other == null) {
return;
}
if (other.Id.Length != 0) {
Id = other.Id;
}
if (other.Issuer.Length != 0) {
Issuer = other.Issuer;
}
if (other.JwksUri.Length != 0) {
JwksUri = other.JwksUri;
}
if (other.Audiences.Length != 0) {
Audiences = other.Audiences;
}
}
[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: {
Id = input.ReadString();
break;
}
case 18: {
Issuer = input.ReadString();
break;
}
case 26: {
JwksUri = input.ReadString();
break;
}
case 34: {
Audiences = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// OAuth scopes are a way to define data and permissions on data. For example,
/// there are scopes defined for "Read-only access to Google Calendar" and
/// "Access to Cloud Platform". Users can consent to a scope for an application,
/// giving it permission to access that data on their behalf.
///
/// OAuth scope specifications should be fairly coarse grained; a user will need
/// to see and understand the text description of what your scope means.
///
/// In most cases: use one or at most two OAuth scopes for an entire family of
/// products. If your product has multiple APIs, you should probably be sharing
/// the OAuth scope across all of those APIs.
///
/// When you need finer grained OAuth consent screens: talk with your product
/// management about how developers will use them in practice.
///
/// Please note that even though each of the canonical scopes is enough for a
/// request to be accepted and passed to the backend, a request can still fail
/// due to the backend requiring additional scopes or permissions.
/// </summary>
public sealed partial class OAuthRequirements : pb::IMessage<OAuthRequirements> {
private static readonly pb::MessageParser<OAuthRequirements> _parser = new pb::MessageParser<OAuthRequirements>(() => new OAuthRequirements());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<OAuthRequirements> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.AuthReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public OAuthRequirements() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public OAuthRequirements(OAuthRequirements other) : this() {
canonicalScopes_ = other.canonicalScopes_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public OAuthRequirements Clone() {
return new OAuthRequirements(this);
}
/// <summary>Field number for the "canonical_scopes" field.</summary>
public const int CanonicalScopesFieldNumber = 1;
private string canonicalScopes_ = "";
/// <summary>
/// The list of publicly documented OAuth scopes that are allowed access. An
/// OAuth token containing any of these scopes will be accepted.
///
/// Example:
///
/// canonical_scopes: https://www.googleapis.com/auth/calendar,
/// https://www.googleapis.com/auth/calendar.read
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string CanonicalScopes {
get { return canonicalScopes_; }
set {
canonicalScopes_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as OAuthRequirements);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(OAuthRequirements other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (CanonicalScopes != other.CanonicalScopes) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (CanonicalScopes.Length != 0) hash ^= CanonicalScopes.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) {
if (CanonicalScopes.Length != 0) {
output.WriteRawTag(10);
output.WriteString(CanonicalScopes);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (CanonicalScopes.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(CanonicalScopes);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(OAuthRequirements other) {
if (other == null) {
return;
}
if (other.CanonicalScopes.Length != 0) {
CanonicalScopes = other.CanonicalScopes;
}
}
[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: {
CanonicalScopes = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// User-defined authentication requirements, including support for
/// [JSON Web Token (JWT)](https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32).
/// </summary>
public sealed partial class AuthRequirement : pb::IMessage<AuthRequirement> {
private static readonly pb::MessageParser<AuthRequirement> _parser = new pb::MessageParser<AuthRequirement>(() => new AuthRequirement());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<AuthRequirement> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.AuthReflection.Descriptor.MessageTypes[4]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AuthRequirement() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AuthRequirement(AuthRequirement other) : this() {
providerId_ = other.providerId_;
audiences_ = other.audiences_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AuthRequirement Clone() {
return new AuthRequirement(this);
}
/// <summary>Field number for the "provider_id" field.</summary>
public const int ProviderIdFieldNumber = 1;
private string providerId_ = "";
/// <summary>
/// [id][google.api.AuthProvider.id] from authentication provider.
///
/// Example:
///
/// provider_id: bookstore_auth
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ProviderId {
get { return providerId_; }
set {
providerId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "audiences" field.</summary>
public const int AudiencesFieldNumber = 2;
private string audiences_ = "";
/// <summary>
/// NOTE: This will be deprecated soon, once AuthProvider.audiences is
/// implemented and accepted in all the runtime components.
///
/// The list of JWT
/// [audiences](https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.3).
/// that are allowed to access. A JWT containing any of these audiences will
/// be accepted. When this setting is absent, only JWTs with audience
/// "https://[Service_name][google.api.Service.name]/[API_name][google.protobuf.Api.name]"
/// will be accepted. For example, if no audiences are in the setting,
/// LibraryService API will only accept JWTs with the following audience
/// "https://library-example.googleapis.com/google.example.library.v1.LibraryService".
///
/// Example:
///
/// audiences: bookstore_android.apps.googleusercontent.com,
/// bookstore_web.apps.googleusercontent.com
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Audiences {
get { return audiences_; }
set {
audiences_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as AuthRequirement);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(AuthRequirement other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ProviderId != other.ProviderId) return false;
if (Audiences != other.Audiences) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ProviderId.Length != 0) hash ^= ProviderId.GetHashCode();
if (Audiences.Length != 0) hash ^= Audiences.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) {
if (ProviderId.Length != 0) {
output.WriteRawTag(10);
output.WriteString(ProviderId);
}
if (Audiences.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Audiences);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ProviderId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ProviderId);
}
if (Audiences.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Audiences);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(AuthRequirement other) {
if (other == null) {
return;
}
if (other.ProviderId.Length != 0) {
ProviderId = other.ProviderId;
}
if (other.Audiences.Length != 0) {
Audiences = other.Audiences;
}
}
[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: {
ProviderId = input.ReadString();
break;
}
case 18: {
Audiences = input.ReadString();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections.Generic;
using System.Text;
using EmergeTk.Model;
namespace EmergeTk.Widgets.Html
{
/// <summary>
/// ListBuilder presents two side by side SelectLists with Add/Remove buttons to move items between lists
/// </summary>
public class ListBuilder<T> : Generic, IDataBindable, IDataSourced where T : AbstractRecord, new()
{
#pragma warning disable 67
//TODO: what is intended here?
public event EventHandler OnSelectedOptionsChanged;
#pragma warning restore 67
private bool isDataBound = false;
private IRecordList<T> availableOptions = null;
private IRecordList<T> selectedOptions = null;
private SelectList<T> availableOptionsSelectList;
private SelectList<T> selectedOptionsSelectList;
private Button addAll;
private Button addSelected;
private Button removeSelected;
private Button removeAll;
public IRecordList<T> AvailableOptions
{
get { return availableOptions; }
set
{
availableOptions = value;
if (availableOptionsSelectList != null)
{
availableOptionsSelectList.DataSource = value;
availableOptionsSelectList.DataBind();
ClearSelected();
RaisePropertyChangedNotification("AvailableOptions");
}
}
}
public IRecordList<T> SelectedOptions
{
get { return selectedOptions; }
set
{
selectedOptions = value;
if (selectedOptionsSelectList != null)
{
selectedOptionsSelectList.DataSource = value;
selectedOptionsSelectList.DataBind();
RaisePropertyChangedNotification("SelectedOptions");
if (OnSelectedOptionsChanged != null)
OnSelectedOptionsChanged(this, null);
}
}
}
private string viewTemplate;
public string ViewTemplate
{
get
{
return viewTemplate;
}
set
{
viewTemplate = value;
if (availableOptionsSelectList != null)
availableOptionsSelectList.ViewTemplate = value;
if (selectedOptionsSelectList != null)
selectedOptionsSelectList.ViewTemplate = value;
}
}
public override void Initialize()
{
addAll = Find<Button>("buttonAddAll");
addSelected = Find<Button>("buttonAddSelected");
removeSelected = Find<Button>("buttonRemoveSelected");
removeAll = Find<Button>("buttonRemoveAll");
availableOptionsSelectList = Find<SelectList<T>>("availableOptions");
if (availableOptionsSelectList != null)
{
availableOptionsSelectList.ViewTemplate = ViewTemplate;
availableOptionsSelectList.SelectedItems = new RecordList<T>();
availableOptionsSelectList.DataSource = AvailableOptions ?? availableOptionsSelectList.SelectedItems;
availableOptionsSelectList.DataBind();
availableOptionsSelectList.OnChanged += AvailableOptions_OnChanged;
availableOptionsSelectList.SelectNone();
}
selectedOptionsSelectList = Find<SelectList<T>>("selectedOptions");
if (selectedOptionsSelectList != null)
{
selectedOptionsSelectList.ViewTemplate = ViewTemplate;
selectedOptionsSelectList.SelectedItems = new RecordList<T>();
selectedOptionsSelectList.DataSource = SelectedOptions ?? selectedOptionsSelectList.SelectedItems;
selectedOptionsSelectList.DataBind();
selectedOptionsSelectList.OnChanged += SelectedOptions_OnChanged;
selectedOptionsSelectList.SelectNone();
}
base.Initialize();
}
private void ClearSelected()
{
availableOptionsSelectList.SelectedItems = new RecordList<T>();
availableOptionsSelectList.SelectNone();
selectedOptionsSelectList.SelectedItems = new RecordList<T>();
selectedOptionsSelectList.SelectNone();
}
void AvailableOptions_OnChanged(object sender, ChangedEventArgs e)
{
addSelected.Enabled = availableOptionsSelectList.SelectedItems.Count != 0;
addAll.Enabled = (this.AvailableOptions ?? new RecordList<T>()).Count != 0;
}
void SelectedOptions_OnChanged(object sender, ChangedEventArgs e)
{
removeSelected.Enabled = selectedOptionsSelectList.SelectedItems.Count != 0;
removeAll.Enabled = (this.SelectedOptions ?? new RecordList<T>()).Count != 0;
}
public void AddAll_OnClick(object sender, ClickEventArgs ea)
{
if (availableOptionsSelectList != null && availableOptions != null)
{
IRecordList<T> selected = SelectedOptions ?? new RecordList<T>();
foreach (T t in AvailableOptions)
{
if( ! selected.Contains( t ) )
selected.Add(t);
}
selected.Sort(new SortInfo("Name"));
SelectedOptions = selected;
AvailableOptions = new RecordList<T>();
ClearSelected();
if (null != addAll)
addAll.Enabled = false;
if (null != addSelected)
addSelected.Enabled = false;
}
}
public void AddSelected_OnClick(object sender, ClickEventArgs ea)
{
if (availableOptionsSelectList != null)
{
IRecordList<T> availableSelected = availableOptionsSelectList.SelectedItems;
if (availableSelected.Count > 0)
{
IRecordList<T> available = AvailableOptions;
IRecordList<T> selected = SelectedOptions ?? new RecordList<T>();
foreach (T t in availableSelected)
{
if( ! selected.Contains( t ) )
selected.Add(t);
available.Remove(t);
}
selected.Sort(new SortInfo("Name"));
AvailableOptions = available;
SelectedOptions = selected;
ClearSelected();
}
}
}
public void RemoveSelected_OnClick(object sender, ClickEventArgs ea)
{
if (selectedOptionsSelectList != null)
{
IRecordList<T> selectedSelected = selectedOptionsSelectList.SelectedItems;
if (selectedSelected.Count > 0)
{
IRecordList<T> available = AvailableOptions ?? new RecordList<T>();
IRecordList<T> selected = SelectedOptions;
foreach (T t in selectedSelected)
{
if( ! available.Contains( t ) )
available.Add(t);
selected.Remove(t);
}
available.Sort(new SortInfo("Name"));
AvailableOptions = available;
SelectedOptions = selected;
ClearSelected();
}
}
}
public void RemoveAll_OnClick(object sender, ClickEventArgs ea)
{
if (selectedOptionsSelectList != null && selectedOptions != null)
{
IRecordList<T> available = AvailableOptions ?? new RecordList<T>();
foreach (T t in SelectedOptions)
{
if( ! available.Contains( t ) )
available.Add(t);
}
available.Sort(new SortInfo("Name"));
AvailableOptions = available;
SelectedOptions = new RecordList<T>();
ClearSelected();
if (null != removeAll)
removeAll.Enabled = false;
if (null != removeSelected)
removeSelected.Enabled = false;
}
}
#region IDataSourced Members
public IRecordList DataSource
{
get
{
return AvailableOptions;
}
set
{
AvailableOptions = (IRecordList<T>)value;
}
}
public bool IsDataBound
{
get
{
return isDataBound;
}
}
public void DataBind()
{
// do nothing because AvailableOptions property does this
}
public string PropertySource
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public AbstractRecord Selected
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
#endregion
}
}
| |
//-----------------------------------------------------------------------------
// 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.
//-----------------------------------------------------------------------------
//
// This will change to something more abstract in the near future, or will be moved into
// the level editor if there is no concise way to abstract it.
//
// This function will build out an empty frame and add it to its given parent. The newly
// built frame control is returned
function GuiFormClass::BuildEmptyFrame(%pos, %ext, %columns, %rows, %parentID)
{
%frame = new GuiFrameSetCtrl()
{
profile = "ToolsGuiFrameSetProfile";
horizSizing = "width";
vertSizing = "height";
position = %pos;
extent = %ext;
columns = %columns;
rows = %rows;
borderWidth = "5"; //"4";
//borderColor = "192 192 192";
absoluteFrames = "1";
relativeResizing = "1";
specialHighlighting = "1";
};
%parentID.add(%frame);
return %frame;
}
//
// This will change to something more abstract in the near future, or will be moved into
// the level editor if there is no concise way to abstract it.
//
// This function will build out a form control and add it to its parent. The newly built
// form control is returned.
function GuiFormClass::BuildFormControl( %parentID, %ContentLibrary )
{
// Find Default 'None' Content.
%contentNoneObj = GuiFormManager::FindFormContent( %ContentLibrary, "Scene View" );
if( %contentNoneObj == 0 )
{
error("GuiFormClass::BuildFormControl - Cannot find 'Scene View' Content Object!" );
return false;
}
%newFormObj = new GuiFormCtrl()
{
class = "FormControlClass";
profile = "ToolsGuiFormProfile";
canSaveDynamicFields = 1;
horizSizing = "width";
vertSizing = "height";
position = "0 0";
extent = "640 455";
minExtent = "20 20";
visible = "1";
caption = $FormClassNoContentCaption;
collapsable = "1";
barBehindText = "1";
hasMenu = true;
ContentLibrary = %ContentLibrary;
ContentID = %contentNoneObj;
Content = "Scene View";
};
%parentID.add( %newFormObj );
return %newFormObj;
}
//
// This will change to something more abstract in the near future, or will be moved into
// the level editor if there is no concise way to abstract it.
//
function FormControlClass::onWake( %this )
{
if( %this.ContentLibrary !$= "" && %this.Content !$= "" )
{
%contentObj = GuiFormManager::FindFormContent( %this.ContentLibrary, %this.Content );
if( %contentObj == 0 )
{
error("GuiFormClass::onWake - Content Library Specified But Content Not Found!" );
return;
}
// Set Form Content
//if( %this.ContentID != %contentObj || !isObject( %this.ContentID ) )
GuiFormClass::SetFormContent( %this, %contentObj );
}
%parentId = %this.getParent();
%extent = %parentID.getExtent();
%this.setExtent( GetWord(%extent, 0), GetWord(%extent, 1) );
GuiFormClass::BuildFormMenu( %this );
}
//
// This will change to something more abstract in the near future, or will be moved into
// the level editor if there is no concise way to abstract it.
//
function GuiFormClass::BuildFormMenu( %formObj )
{
if( !%formObj.hasMenu )
return;
// Menu Name.
%menuName = "FormMainMenu";
// Retrieve Menu ID.
%formMenu = %formObj.getMenuID();
%formMenu.clearMenuItems( %menuName );
//*** Setup the check mark bitmap index to start at the third bitmap
%formMenu.setCheckmarkBitmapIndex(1);
//*** Add a menu to the menubar
%formMenu.addMenu( %menuName, %formObj);
%formMenu.setMenuBitmapIndex( %menuName, 0, true, false);
%formMenu.setMenuMargins(0, 0, 0);
// Build Division Control Menu Items.
%formMenu.addMenuItem( %menuName, "Split This View Horizontally", 1);
%formMenu.addMenuItem( %menuName, "Split This View Vertically", 2);
%formMenu.addMenuItem( %menuName, "-", 0);
%formMenu.addMenuItem( %menuName, "Remove This View", 3);
}
//
// This will change to something more abstract in the near future, or will be moved into
// the level editor if there is no concise way to abstract it.
//
function GuiFormClass::SetFormContent( %formObj, %contentObj )
{
// Menu Name.
%menuName = "FormMainMenu";
// Validate New Content.
if( !isObject( %contentObj ) )
{
// Failure
error("GuiFormClass::SetFormContent- No Valid Content Object!" );
return 0;
}
// Remove any other content from the Form
%count = %formObj.getCount();
if(%count > 1)
{
// Notify Script of Content Changing.
if( %formObj.isMethod("onContentChanging") )
%formObj.onContentChanging( %contentObj );
// Object 0 is Always The Menu.
%currentContent = %formObj.getObject( 1 );
if( isObject( %currentContent ) )
{
// Remove from Reference List.
if( %formObj.contentID !$= "" )
GuiFormManager::RemoveContentReference( %formObj.ContentLibrary, %formObj.contentID.Name, %currentContent );
// Delete the content.
%currentContent.delete();
// Update form Caption
%formObj.setCaption( $FormClassNoContentCaption );
}
}
// Handle the Form content choices by obtaining the script build command
if( %contentObj.CreateFunction !$= "" )
{
//*** Set the name first
%name = %contentObj.Name;
%formObj.setCaption(%name);
// We set the content ID prior to calling the create function so
// that it may reference it's content to retrieve information about it.
%oldContentId = %formObj.contentID;
%formObj.contentID = %contentObj;
%result = eval( %contentObj.CreateFunction @ "(" @ %formObj @ ");" );
if(!%result)
{
//*** Couldn't set up the form's contents so set the name back. We need to
//*** do it like this to allow the form's contents to change the form caption
//*** if the above command worked.
%formObj.setCaption($FormClassNoContentCaption);
// Restore Content ID.
%formObj.contentID = %oldContentID;
// Notify Script of Failure.
if( %formObj.isMethod("onContentChangeFailure") )
%formObj.onContentChangeFailure();
}
else
{
// Add to Reference List.
%currentContent = %formObj.getObject( 1 );
if( isObject( %currentContent ) )
GuiFormManager::AddContentReference( %formObj.ContentLibrary, %contentObj.Name, %currentContent );
%formObj.Content = %formObj.contentId.name;
// Notify Script of Content Change
if( %formObj.isMethod("onContentChanged") )
%formObj.onContentChanged( %contentObj );
return %result;
}
}
return 0;
}
//
// Create a given content library content instance on a given parent control and
// reference count it in the ref manager.
//
function GuiFormClass::SetControlContent( %controlObj, %contentLibrary, %contentObj )
{
// Validate New Content.
if( !isObject( %contentObj ) )
{
// Failure
error("GuiFormClass::SetControlContent- No Valid Content Object!" );
return 0;
}
// Remove any other content from the Form
if( isObject( %controlObj.ContentID ) )
{
// Find Control of current content internal name on the control.
%currentContent = %controlObj.findObjectByInternalName( %controlObj.ContentID.Name );
if( isObject( %currentContent ) )
{
// Notify Script of Content Changing.
if( %controlObj.isMethod("onContentChanging") )
%controlObj.onContentChanging( %contentObj );
// Remove from Reference List.
GuiFormManager::RemoveContentReference( %contentLibrary, %controlObj.contentID.Name, %currentContent );
// Delete the content.
%currentContent.delete();
}
}
// Handle the Form content choices by obtaining the script build command
if( %contentObj.CreateFunction !$= "" )
{
%name = %contentObj.Name;
// We set the content ID prior to calling the create function so
// that it may reference it's content to retrieve information about it.
%oldContentId = %controlObj.contentID;
%controlObj.contentID = %contentObj;
%currentContent = eval( %contentObj.CreateFunction @ "(" @ %controlObj @ ");" );
if( !isObject( %currentContent ) )
{
// Restore Content ID.
%controlObj.contentID = %oldContentID;
// Notify Script of Failure.
if( %controlObj.isMethod("onContentChangeFailure") )
%controlObj.onContentChangeFailure();
}
else
{
// Add to Reference List.
GuiFormManager::AddContentReference( %contentLibrary, %contentObj.Name, %currentContent );
// Store Internal Name
%currentContent.setInternalName( %contentObj.Name );
// Store Content
%controlObj.Content = %controlObj.contentId.name;
// Notify Script of Content Change
if( %controlObj.isMethod("onContentChanged") )
%controlObj.onContentChanged( %contentObj );
return %currentContent;
}
}
return 0;
}
//
// Remove a given library content instance from a control that is housing it.
//
function GuiFormClass::ClearControlContent( %controlObj, %contentLibrary )
{
// Remove any other content from the Form
if( isObject( %controlObj.ContentID ) )
{
// Find Control of current content internal name on the control.
%currentContent = %controlObj.findObjectByInternalName( %controlObj.ContentID.Name );
if( isObject( %currentContent ) )
{
// Notify Script of Content Changing.
if( %controlObj.isMethod("onContentClearing") )
%controlObj.onContentClearing( %controlObj.ContentID );
// Remove from Reference List.
GuiFormManager::RemoveContentReference( %contentLibrary, %controlObj.contentID.Name, %currentContent );
// Delete the content.
%currentContent.delete();
}
}
}
//
// This will change to something more abstract in the near future, or will be moved into
// the level editor if there is no concise way to abstract it.
//
// Turn a form into a split frame and add the form back and build a new blank
// form in the empty slot. %horizontal==ture then make a horizontal split, otherwise
// make a vertical one.
function GuiFormClass::AddFrameSplitToForm(%formid, %horizontal)
{
%formparent = %formid.getGroup();
// Get form position and size
%pos = %formid.position;
%ext = %formid.extent;
%rows = "0";
%columns = "0";
if(%horizontal)
{
%framesplit = getWord(%ext,1) / 2;
%rows = "0 " @ %framesplit;
}
else
{
%framesplit = getWord(%ext,0) / 2;
%columns = "0 " @ %framesplit;
}
// If the form's parent is a frame control and this form is the first control then
// we will need to move it to the front of the other children later on. Otherwise
// we'll be added to the bottom of the stack and the order will get messed up.
// This all assumes that a frame control only has two children.
%secondctrl = -1;
if(%formparent.getClassName() $= "GuiFrameSetCtrl")
{
//error("Form parent is GuiFrameSetCtrl");
if(%formparent.getObject(0) == %formid)
{
// This form is the first child.
//error("Form is at the top");
%secondctrl = %formparent.getObject(1);
}
}
// If we're adding a frameset around the layout base, propogate the
// layoutRef and layoutObj's to the new parent.
if( %formID.LayoutRef !$= "" )
%LayoutRef = %formID.LayoutRef;
else
%LayoutRef = 0;
// Remove form from parent, put a frame control in its place, and then add this form back to the frame
%formparent.remove(%formid);
%frame = GuiFormClass::BuildEmptyFrame(%pos, %ext, %columns, %rows, %formparent);
if( %layoutRef != 0 )
{
%frame.LayoutRef = %LayoutRef;
%frame.LayoutRef.layoutObj = %frame;
%frame.setCanSave( true );
}
if(%secondctrl != -1)
{
// Move this frame to the top of its parent's children stack by removing the
// other child and adding it back again. This will force this second child to
// the bottom and our new frame back to the first child (the same location the
// original form was). Whew! Maybe the frame control needs to be modified to
// handle this.
//error("Moving to the top");
%formparent.remove(%secondctrl);
%formparent.add(%secondctrl);
}
%frame.add(%formid);
// Add a blank form to the bottom frame
GuiFormClass::BuildFormControl(%frame, %formid.ContentLibrary );
//error("New parent: " @ %frame SPC "(" @ %frame.getClassName() @ ")");
}
//
// This will change to something more abstract in the near future, or will be moved into
// the level editor if there is no concise way to abstract it.
//
//*** Remove a form's frame and any other of the frame's children and put the given
//*** form in its place, effectively removing the split. %keepform==true then remove
//*** all children of a parent Frame Set and keep the given Form. Otherwise, remove
//*** the given Form and keep the other child.
function GuiFormClass::RemoveFrameSplit(%formid, %keepform)
{
//*** Get the form's parent and make sure it is a frame GUI. Other wise do nothing.
%frameID = %formid.getGroup();
if(%frameID.getClassName() !$= "GuiFrameSetCtrl")
return;
//*** Get frame's position and size
%pos = %frameID.position;
%ext = %frameID.extent;
if(%keepform)
{
%form = %frameID.getObject(0);
// Remove from Reference List.
if(%form.getClassName() $= "GuiFormCtrl")
GuiFormManager::RemoveContentReference( %form.ContentLibrary, %form.contentID.Name, %form.getObject(1) );
//*** Go through the frame's children and remove them (which includes our form)
%frameID.clear();
}
else
{
// Remove from Reference List.
if( %formId.getClassName() $= "GuiFormCtrl" )
GuiFormManager::RemoveContentReference( %formId.ContentLibrary, %formId.contentID.Name, %formId.getObject(1) );
//*** Store the first child that is not the given Form
%count = %frameID.getCount();
for(%i=0; %i < %count; %i++)
{
%child = %frameID.getObject(%i);
if(%child != %formid)
{
//*** This is the first child that isn't the given Form, so
//*** swap the given %formid with this new child so we keep it
%formid = %child;
break;
}
}
//*** Now remove all children from the frame.
%frameID.clear();
}
//*** Obtain the frame's parent
%frameparentID = %frameID.getGroup();
//*** If the frame's parent is itself a frame, then track all of its children and add
//*** our form into the correct location, and remove our frame in the process. Otherwise
//*** just delete our frame and add our form to the parent.
if(%frameparentID.getClassName() $= "GuiFrameSetCtrl")
{
//*** Store the children
%count = %frameparentID.getCount();
%check = -1;
for(%i=0; %i<%count; %i++)
{
%obj[%i] = %frameparentID.getObject(%i);
if(%obj[%i] == %frameID)
%check = %i;
}
//*** Clear the existing children
%frameparentID.clear();
//*** Now add them back, including our form
for(%i=0; %i<%count; %i++)
{
if(%i == %check)
{
//*** Add our form
%frameparentID.add(%formid);
}
else
{
//*** Add the old child back
%frameparentID.add(%obj[%i]);
}
}
} else
{
// If we're about to remove a frame that has a layout ref move it to the new object (%formID)
if( %frameID.LayoutRef !$= "" )
{
%formID.LayoutRef = %frameID.LayoutRef;
// By default if a control has been added to a form it will tag itself as cannot save.
// just to be safe, we mark it as we can since it's clearly now becoming the root of a layout.
%formID.LayoutRef.layoutObj = %formID;
%formID.setCanSave( true );
}
//*** Remove old child and add our form to the parent
%frameparentID.remove(%frameID);
%frameparentID.add(%formid);
}
//*** Finally resize the form to fit
%formid.resize(getWord(%pos,0),getWord(%pos,1),getWord(%ext,0),getWord(%ext,1));
}
//
// This will change to something more abstract in the near future, or will be moved into
// the level editor if there is no concise way to abstract it.
//
//*** Will resize the Form's content to fit. This is usually done at the beginning when
//*** the content is first added to the form.
function FormControlClass::sizeContentsToFit(%this, %content, %margin)
{
%formext = %this.getExtent();
%menupos = %this.getObject(0).getPosition();
%menuext = %this.getObject(0).getExtent();
%ctrlposx = getWord(%menupos,0) + %this.contentID.Margin;
%ctrlposy = getWord(%menupos,1) + getWord(%menuext,1) + %this.contentID.Margin;
%ctrlextx = getWord(%formext,0) - %ctrlposx - %this.contentID.Margin;
%ctrlexty = getWord(%formext,1) - %ctrlposy - %this.contentID.Margin;
%content.resize(%ctrlposx,%ctrlposy,%ctrlextx,%ctrlexty);
}
//
// This will change to something more abstract in the near future, or will be moved into
// the level editor if there is no concise way to abstract it.
//
function FormControlClass::onResize(%this)
{
//*** If this form has a content child, then pass along this resize notice
//*** to allow it to do something.
if(%this.getCount() > 1)
{
%child = %this.getObject(1);
if( isObject( %child ) )
%this.sizeContentsToFit( %child );
if( %child.isMethod("onResize") )
%child.onResize(%this);
}
}
//
// This will change to something more abstract in the near future, or will be moved into
// the level editor if there is no concise way to abstract it.
//
function FormMenuBarClass::onMenuItemSelect(%this, %menuid, %menutext, %itemid, %itemtext)
{
%formId = %menuid; // %menuid should contain the form's ID
//error("FormMenuBarClass::onMenuSelect(): " @ %menuid SPC %menutext SPC %itemid SPC %itemtext SPC "parent: " @ %formparent);
// If the ID is less than 1000, we know it's a layout menu item
if( %itemid < 1000 )
{
// Handle the standard menu choices
switch(%itemid)
{
case "1": // Add horizontal split
GuiFormClass::AddFrameSplitToForm(%formid, true);
case "2": // Add vertical split
GuiFormClass::AddFrameSplitToForm(%formid, false);
case "3": // Remove split and keep other child
GuiFormClass::RemoveFrameSplit(%formid, false);
}
// We're Done Here.
return;
}
else
GuiFormClass::SetFormContent( %formId, %itemId );
}
| |
using Template10.Mvvm;
using System.Collections.Generic;
using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Template10.Services.NavigationService;
using Windows.UI.Xaml.Navigation;
using Refit;
using Template10.Common;
using Template10.Controls;
using TimePunchUWP.Api.HttpHandlers;
using TimePunchUWP.Api.Services;
using TimePunchUWP.Models;
using TimePunchUWP.Services;
using TimePunchUWP.Views;
using TimePunchUWP.Api;
using TimeSpan = System.TimeSpan;
namespace TimePunchUWP.ViewModels
{
public class MainPageViewModel : ViewModelBase
{
private readonly AuthService _authService;
private readonly TimeSpanService _timeSpanService;
private Models.LastTimeSpan _lastTimeSpan;
private bool _hasTimeSpan;
private bool _isTimerRunning;
private TimeSpan _timeSpan;
private DispatcherTimer timer;
public bool HasTimeSpan
{
get { return _hasTimeSpan; }
set { Set(ref _hasTimeSpan, value); }
}
public bool IsTimerRunning
{
get { return _isTimerRunning; }
set
{
Set(ref _isTimerRunning, value);
StartTimerCommand.RaiseCanExecuteChanged();
StopTimerCommand.RaiseCanExecuteChanged();
ContinueTimerCommand.RaiseCanExecuteChanged();
}
}
public MainPageViewModel()
{
IsTimerRunning = false;
_authService = AuthService.Instance;
_timeSpanService = new TimeSpanService(RestService.For<TimeSpanApiService>(new HttpClient(new AuthenticatedHttpClientHandler(GetToken)) { BaseAddress = new Uri(Constants.BASE_URL) }));
timer = new DispatcherTimer {Interval = TimeSpan.FromSeconds(1)};
timer.Tick += Timer_Tick;
RefreshCommand.Execute();
}
public TimeSpan TimeSpan
{
get { return _timeSpan; }
set { Set(ref _timeSpan, value); }
}
private void Timer_Tick(object sender, object e)
{
TimeSpan = TimeSpan.Add(TimeSpan.FromSeconds(1));
}
public Models.LastTimeSpan LastTimeSpan
{
get { return _lastTimeSpan; }
set { Set(ref _lastTimeSpan, value); }
}
private Task<string> GetToken()
{
var token = _authService.GetToken();
return Task.FromResult(token);
}
public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode,
IDictionary<string, object> suspensionState)
{
// if (suspensionState.Any())
// {
// Value = suspensionState[nameof(Value)]?.ToString();
// }
await Task.CompletedTask;
}
public override async Task OnNavigatedFromAsync(IDictionary<string, object> suspensionState, bool suspending)
{
// if (suspending)
// {
// suspensionState[nameof(Value)] = Value;
// }
await Task.CompletedTask;
}
public override async Task OnNavigatingFromAsync(NavigatingEventArgs args)
{
args.Cancel = false;
await Task.CompletedTask;
}
public void GotoSettings() =>
NavigationService.Navigate(typeof(Views.SettingsPage), 0);
public void GotoPrivacy() =>
NavigationService.Navigate(typeof(Views.SettingsPage), 1);
public void GotoAbout() =>
NavigationService.Navigate(typeof(Views.SettingsPage), 2);
public void Logout()
{
Shell.Logout();
}
public DelegateCommand RefreshCommand => new DelegateCommand(async () =>
{
LastTimeSpan = await _timeSpanService.GetLastTimeSpan();
if (LastTimeSpan == null)
{
HasTimeSpan = false;
return;
}
if (LastTimeSpan.TimeSpan.StopTime == null)
{
HasTimeSpan = true;
TimeSpan = DateTime.Now - LastTimeSpan.TimeSpan.StartTime;
ContinueTimerCommand.Execute();
IsTimerRunning = true;
}
});
private DelegateCommand _startTimerCommand;
public DelegateCommand StartTimerCommand
{
get
{
return _startTimerCommand ??
(_startTimerCommand = new DelegateCommand(ExecuteStartTimerCommand, CanExecuteStartTimerCommand));
}
set { Set(ref _startTimerCommand, value); }
}
private bool CanExecuteStartTimerCommand()
{
return !IsTimerRunning;
}
private async void ExecuteStartTimerCommand()
{
timer.Start();
TimeSpan = TimeSpan.Zero;
IsTimerRunning = true;
DateTime startDateTime = DateTime.Now;
LastTimeSpan.TimeSpan = await _timeSpanService.CreateTimeSpan(LastTimeSpan.Project.Id, LastTimeSpan.Issue.Id, new Models.TimeSpan { StartTime = startDateTime });
LastTimeSpan.TimeSpan.StartTime = startDateTime;
}
private DelegateCommand _continueTimerCommand;
public DelegateCommand ContinueTimerCommand
{
get
{
return _continueTimerCommand ??
(_continueTimerCommand = new DelegateCommand(ExecuteContinueTimerCommand, CanExecuteContinueTimerCommand));
}
set { Set(ref _continueTimerCommand, value); }
}
private bool CanExecuteContinueTimerCommand()
{
return !IsTimerRunning;
}
private void ExecuteContinueTimerCommand()
{
timer.Start();
IsTimerRunning = true;
}
private DelegateCommand _stopTimerCommand;
public DelegateCommand StopTimerCommand
{
get
{
return _stopTimerCommand ??
(_stopTimerCommand = new DelegateCommand(ExecuteStopTimerCommand, CanExecuteStopTimerCommand));
}
set { Set(ref _stopTimerCommand, value); }
}
private bool CanExecuteStopTimerCommand()
{
return IsTimerRunning;
}
private async void ExecuteStopTimerCommand()
{
timer.Stop();
IsTimerRunning = false;
LastTimeSpan.TimeSpan.StopTime = DateTime.Now;
await _timeSpanService.StopTimeSpan(LastTimeSpan.Project.Id, LastTimeSpan.Issue.Id, LastTimeSpan.TimeSpan);
}
}
}
| |
/*
* 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.
*/
// ReSharper disable UnassignedField.Global
// ReSharper disable CollectionNeverUpdated.Global
// ReSharper disable UnusedAutoPropertyAccessor.Global
namespace Apache.Ignite.Core.Tests.Binary
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Impl.Binary;
using NUnit.Framework;
/// <summary>
/// Binary builder self test.
/// </summary>
public class BinaryBuilderSelfTest
{
/** Undefined type: Empty. */
private const string TypeEmpty = "EmptyUndefined";
/** Grid. */
private Ignite _grid;
/** Marshaller. */
private Marshaller _marsh;
/// <summary>
/// Set up routine.
/// </summary>
[TestFixtureSetUp]
public void SetUp()
{
TestUtils.KillProcesses();
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
BinaryConfiguration = new BinaryConfiguration
{
TypeConfigurations = GetTypeConfigurations(),
IdMapper = new IdMapper(),
NameMapper = new NameMapper(GetNameMapper()),
CompactFooter = GetCompactFooter(),
}
};
_grid = (Ignite) Ignition.Start(cfg);
_marsh = _grid.Marshaller;
}
/// <summary>
/// Gets the type configurations.
/// </summary>
protected virtual ICollection<BinaryTypeConfiguration> GetTypeConfigurations()
{
return new[]
{
new BinaryTypeConfiguration(typeof(Empty)),
new BinaryTypeConfiguration(typeof(Primitives)),
new BinaryTypeConfiguration(typeof(PrimitiveArrays)),
new BinaryTypeConfiguration(typeof(StringDateGuidEnum)),
new BinaryTypeConfiguration(typeof(WithRaw)),
new BinaryTypeConfiguration(typeof(MetaOverwrite)),
new BinaryTypeConfiguration(typeof(NestedOuter)),
new BinaryTypeConfiguration(typeof(NestedInner)),
new BinaryTypeConfiguration(typeof(MigrationOuter)),
new BinaryTypeConfiguration(typeof(MigrationInner)),
new BinaryTypeConfiguration(typeof(InversionOuter)),
new BinaryTypeConfiguration(typeof(InversionInner)),
new BinaryTypeConfiguration(typeof(CompositeOuter)),
new BinaryTypeConfiguration(typeof(CompositeInner)),
new BinaryTypeConfiguration(typeof(CompositeArray)),
new BinaryTypeConfiguration(typeof(CompositeContainer)),
new BinaryTypeConfiguration(typeof(ToBinary)),
new BinaryTypeConfiguration(typeof(Remove)),
new BinaryTypeConfiguration(typeof(RemoveInner)),
new BinaryTypeConfiguration(typeof(BuilderInBuilderOuter)),
new BinaryTypeConfiguration(typeof(BuilderInBuilderInner)),
new BinaryTypeConfiguration(typeof(BuilderCollection)),
new BinaryTypeConfiguration(typeof(BuilderCollectionItem)),
new BinaryTypeConfiguration(typeof(DecimalHolder)),
new BinaryTypeConfiguration(TypeEmpty),
new BinaryTypeConfiguration(typeof(TestEnumRegistered)),
new BinaryTypeConfiguration(typeof(NameMapperTestType))
};
}
/// <summary>
/// Gets the compact footer setting.
/// </summary>
protected virtual bool GetCompactFooter()
{
return true;
}
/// <summary>
/// Gets the name mapper.
/// </summary>
protected virtual IBinaryNameMapper GetNameMapper()
{
return BinaryBasicNameMapper.FullNameInstance;
}
/// <summary>
/// Gets the name of the type.
/// </summary>
private string GetTypeName(Type type)
{
return GetNameMapper().GetTypeName(type.AssemblyQualifiedName);
}
/// <summary>
/// Tear down routine.
/// </summary>
[TestFixtureTearDown]
public void TearDown()
{
if (_grid != null)
Ignition.Stop(_grid.Name, true);
_grid = null;
}
/// <summary>
/// Ensure that binary engine is able to work with type names, which are not configured.
/// </summary>
[Test]
public void TestNonConfigured()
{
string typeName1 = "Type1";
string typeName2 = "Type2";
string field1 = "field1";
string field2 = "field2";
// 1. Ensure that builder works fine.
IBinaryObject binObj1 = _grid.GetBinary().GetBuilder(typeName1).SetField(field1, 1).Build();
Assert.AreEqual(typeName1, binObj1.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj1.GetBinaryType().Fields.Count);
Assert.AreEqual(field1, binObj1.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj1.GetBinaryType().GetFieldTypeName(field1));
Assert.AreEqual(1, binObj1.GetField<int>(field1));
// 2. Ensure that object can be unmarshalled without deserialization.
byte[] data = ((BinaryObject) binObj1).Data;
binObj1 = _grid.Marshaller.Unmarshal<IBinaryObject>(data, BinaryMode.ForceBinary);
Assert.AreEqual(typeName1, binObj1.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj1.GetBinaryType().Fields.Count);
Assert.AreEqual(field1, binObj1.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj1.GetBinaryType().GetFieldTypeName(field1));
Assert.AreEqual(1, binObj1.GetField<int>(field1));
// 3. Ensure that we can nest one anonymous object inside another
IBinaryObject binObj2 =
_grid.GetBinary().GetBuilder(typeName2).SetField(field2, binObj1).Build();
Assert.AreEqual(typeName2, binObj2.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj2.GetBinaryType().Fields.Count);
Assert.AreEqual(field2, binObj2.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, binObj2.GetBinaryType().GetFieldTypeName(field2));
binObj1 = binObj2.GetField<IBinaryObject>(field2);
Assert.AreEqual(typeName1, binObj1.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj1.GetBinaryType().Fields.Count);
Assert.AreEqual(field1, binObj1.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj1.GetBinaryType().GetFieldTypeName(field1));
Assert.AreEqual(1, binObj1.GetField<int>(field1));
// 4. Ensure that we can unmarshal object with other nested object.
data = ((BinaryObject) binObj2).Data;
binObj2 = _grid.Marshaller.Unmarshal<IBinaryObject>(data, BinaryMode.ForceBinary);
Assert.AreEqual(typeName2, binObj2.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj2.GetBinaryType().Fields.Count);
Assert.AreEqual(field2, binObj2.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, binObj2.GetBinaryType().GetFieldTypeName(field2));
binObj1 = binObj2.GetField<IBinaryObject>(field2);
Assert.AreEqual(typeName1, binObj1.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj1.GetBinaryType().Fields.Count);
Assert.AreEqual(field1, binObj1.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj1.GetBinaryType().GetFieldTypeName(field1));
Assert.AreEqual(1, binObj1.GetField<int>(field1));
}
/// <summary>
/// Test "ToBinary()" method.
/// </summary>
[Test]
public void TestToBinary()
{
DateTime date = DateTime.Now.ToUniversalTime();
Guid guid = Guid.NewGuid();
IBinary api = _grid.GetBinary();
// 1. Primitives.
Assert.AreEqual(1, api.ToBinary<byte>((byte)1));
Assert.AreEqual(1, api.ToBinary<short>((short)1));
Assert.AreEqual(1, api.ToBinary<int>(1));
Assert.AreEqual(1, api.ToBinary<long>((long)1));
Assert.AreEqual((float)1, api.ToBinary<float>((float)1));
Assert.AreEqual((double)1, api.ToBinary<double>((double)1));
Assert.AreEqual(true, api.ToBinary<bool>(true));
Assert.AreEqual('a', api.ToBinary<char>('a'));
// 2. Special types.
Assert.AreEqual("a", api.ToBinary<string>("a"));
Assert.AreEqual(date, api.ToBinary<IBinaryObject>(date).Deserialize<DateTime>());
Assert.AreEqual(guid, api.ToBinary<Guid>(guid));
Assert.AreEqual(TestEnumRegistered.One, api.ToBinary<IBinaryObject>(TestEnumRegistered.One)
.Deserialize<TestEnumRegistered>());
// 3. Arrays.
Assert.AreEqual(new byte[] { 1 }, api.ToBinary<byte[]>(new byte[] { 1 }));
Assert.AreEqual(new short[] { 1 }, api.ToBinary<short[]>(new short[] { 1 }));
Assert.AreEqual(new[] { 1 }, api.ToBinary<int[]>(new[] { 1 }));
Assert.AreEqual(new long[] { 1 }, api.ToBinary<long[]>(new long[] { 1 }));
Assert.AreEqual(new float[] { 1 }, api.ToBinary<float[]>(new float[] { 1 }));
Assert.AreEqual(new double[] { 1 }, api.ToBinary<double[]>(new double[] { 1 }));
Assert.AreEqual(new[] { true }, api.ToBinary<bool[]>(new[] { true }));
Assert.AreEqual(new[] { 'a' }, api.ToBinary<char[]>(new[] { 'a' }));
Assert.AreEqual(new[] { "a" }, api.ToBinary<string[]>(new[] { "a" }));
Assert.AreEqual(new[] {date}, api.ToBinary<IBinaryObject[]>(new[] {date})
.Select(x => x.Deserialize<DateTime>()));
Assert.AreEqual(new[] { guid }, api.ToBinary<Guid[]>(new[] { guid }));
Assert.AreEqual(new[] { TestEnumRegistered.One},
api.ToBinary<IBinaryObject[]>(new[] { TestEnumRegistered.One})
.Select(x => x.Deserialize<TestEnumRegistered>()).ToArray());
// 4. Objects.
IBinaryObject binObj = api.ToBinary<IBinaryObject>(new ToBinary(1));
Assert.AreEqual(GetTypeName(typeof(ToBinary)), binObj.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj.GetBinaryType().Fields.Count);
Assert.AreEqual("Val", binObj.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj.GetBinaryType().GetFieldTypeName("Val"));
Assert.AreEqual(1, binObj.GetField<int>("val"));
Assert.AreEqual(1, binObj.Deserialize<ToBinary>().Val);
// 5. Object array.
var binObjArr = api.ToBinary<object[]>(new object[] {new ToBinary(1)})
.OfType<IBinaryObject>().ToArray();
Assert.AreEqual(1, binObjArr.Length);
Assert.AreEqual(1, binObjArr[0].GetField<int>("Val"));
Assert.AreEqual(1, binObjArr[0].Deserialize<ToBinary>().Val);
}
/// <summary>
/// Test builder field remove logic.
/// </summary>
[Test]
public void TestRemove()
{
// Create empty object.
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(Remove)).Build();
Assert.IsNull(binObj.GetField<object>("val"));
Assert.IsNull(binObj.Deserialize<Remove>().Val);
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(Remove)), meta.TypeName);
Assert.AreEqual(0, meta.Fields.Count);
// Populate it with field.
IBinaryObjectBuilder builder = binObj.ToBuilder();
Assert.IsNull(builder.GetField<object>("val"));
object val = 1;
builder.SetField("val", val);
Assert.AreEqual(val, builder.GetField<object>("val"));
binObj = builder.Build();
Assert.AreEqual(val, binObj.GetField<object>("val"));
Assert.AreEqual(val, binObj.Deserialize<Remove>().Val);
meta = binObj.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(Remove)), meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("val", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("val"));
// Perform field remove.
builder = binObj.ToBuilder();
Assert.AreEqual(val, builder.GetField<object>("val"));
builder.RemoveField("val");
Assert.IsNull(builder.GetField<object>("val"));
builder.SetField("val", val);
Assert.AreEqual(val, builder.GetField<object>("val"));
builder.RemoveField("val");
Assert.IsNull(builder.GetField<object>("val"));
binObj = builder.Build();
Assert.IsNull(binObj.GetField<object>("val"));
Assert.IsNull(binObj.Deserialize<Remove>().Val);
// Test correct removal of field being referenced by handle somewhere else.
RemoveInner inner = new RemoveInner(2);
binObj = _grid.GetBinary().GetBuilder(typeof(Remove))
.SetField("val", inner)
.SetField("val2", inner)
.Build();
binObj = binObj.ToBuilder().RemoveField("val").Build();
Remove obj = binObj.Deserialize<Remove>();
Assert.IsNull(obj.Val);
Assert.AreEqual(2, obj.Val2.Val);
}
/// <summary>
/// Test builder-in-builder scenario.
/// </summary>
[Test]
public void TestBuilderInBuilder()
{
// Test different builders assembly.
IBinaryObjectBuilder builderOuter = _grid.GetBinary().GetBuilder(typeof(BuilderInBuilderOuter));
IBinaryObjectBuilder builderInner = _grid.GetBinary().GetBuilder(typeof(BuilderInBuilderInner));
builderOuter.SetField<object>("inner", builderInner);
builderInner.SetField<object>("outer", builderOuter);
IBinaryObject outerbinObj = builderOuter.Build();
IBinaryType meta = outerbinObj.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(BuilderInBuilderOuter)), meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("inner", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("inner"));
IBinaryObject innerbinObj = outerbinObj.GetField<IBinaryObject>("inner");
meta = innerbinObj.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(BuilderInBuilderInner)), meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("outer", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("outer"));
BuilderInBuilderOuter outer = outerbinObj.Deserialize<BuilderInBuilderOuter>();
Assert.AreSame(outer, outer.Inner.Outer);
// Test same builders assembly.
innerbinObj = _grid.GetBinary().GetBuilder(typeof(BuilderInBuilderInner)).Build();
outerbinObj = _grid.GetBinary().GetBuilder(typeof(BuilderInBuilderOuter))
.SetField("inner", innerbinObj)
.SetField("inner2", innerbinObj)
.Build();
meta = outerbinObj.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(BuilderInBuilderOuter)), meta.TypeName);
Assert.AreEqual(2, meta.Fields.Count);
Assert.IsTrue(meta.Fields.Contains("inner"));
Assert.IsTrue(meta.Fields.Contains("inner2"));
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("inner"));
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("inner2"));
outer = outerbinObj.Deserialize<BuilderInBuilderOuter>();
Assert.AreSame(outer.Inner, outer.Inner2);
builderOuter = _grid.GetBinary().GetBuilder(outerbinObj);
IBinaryObjectBuilder builderInner2 = builderOuter.GetField<IBinaryObjectBuilder>("inner2");
builderInner2.SetField("outer", builderOuter);
outerbinObj = builderOuter.Build();
outer = outerbinObj.Deserialize<BuilderInBuilderOuter>();
Assert.AreSame(outer, outer.Inner.Outer);
Assert.AreSame(outer.Inner, outer.Inner2);
}
/// <summary>
/// Test for decimals building.
/// </summary>
[Test]
public void TestDecimals()
{
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(DecimalHolder))
.SetField("val", decimal.One)
.SetField("valArr", new decimal?[] { decimal.MinusOne })
.Build();
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(DecimalHolder)), meta.TypeName);
Assert.AreEqual(2, meta.Fields.Count);
Assert.IsTrue(meta.Fields.Contains("val"));
Assert.IsTrue(meta.Fields.Contains("valArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameDecimal, meta.GetFieldTypeName("val"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayDecimal, meta.GetFieldTypeName("valArr"));
Assert.AreEqual(decimal.One, binObj.GetField<decimal>("val"));
Assert.AreEqual(new decimal?[] { decimal.MinusOne }, binObj.GetField<decimal?[]>("valArr"));
DecimalHolder obj = binObj.Deserialize<DecimalHolder>();
Assert.AreEqual(decimal.One, obj.Val);
Assert.AreEqual(new decimal?[] { decimal.MinusOne }, obj.ValArr);
}
/// <summary>
/// Test for an object returning collection of builders.
/// </summary>
[Test]
public void TestBuilderCollection()
{
// Test collection with single element.
IBinaryObjectBuilder builderCol = _grid.GetBinary().GetBuilder(typeof(BuilderCollection));
IBinaryObjectBuilder builderItem =
_grid.GetBinary().GetBuilder(typeof(BuilderCollectionItem)).SetField("val", 1);
builderCol.SetCollectionField("col", new ArrayList { builderItem });
IBinaryObject binCol = builderCol.Build();
IBinaryType meta = binCol.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(BuilderCollection)), meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("col", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameCollection, meta.GetFieldTypeName("col"));
var binColItems = binCol.GetField<ArrayList>("col");
Assert.AreEqual(1, binColItems.Count);
var binItem = (IBinaryObject) binColItems[0];
meta = binItem.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(BuilderCollectionItem)), meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("val", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, meta.GetFieldTypeName("val"));
BuilderCollection col = binCol.Deserialize<BuilderCollection>();
Assert.IsNotNull(col.Col);
Assert.AreEqual(1, col.Col.Count);
Assert.AreEqual(1, ((BuilderCollectionItem) col.Col[0]).Val);
// Add more binary objects to collection.
builderCol = _grid.GetBinary().GetBuilder(binCol);
IList builderColItems = builderCol.GetField<IList>("col");
Assert.AreEqual(1, builderColItems.Count);
BinaryObjectBuilder builderColItem = (BinaryObjectBuilder) builderColItems[0];
builderColItem.SetField("val", 2); // Change nested value.
builderColItems.Add(builderColItem); // Add the same object to check handles.
builderColItems.Add(builderItem); // Add item from another builder.
builderColItems.Add(binItem); // Add item in binary form.
binCol = builderCol.Build();
col = binCol.Deserialize<BuilderCollection>();
Assert.AreEqual(4, col.Col.Count);
var item0 = (BuilderCollectionItem) col.Col[0];
var item1 = (BuilderCollectionItem) col.Col[1];
var item2 = (BuilderCollectionItem) col.Col[2];
var item3 = (BuilderCollectionItem) col.Col[3];
Assert.AreEqual(2, item0.Val);
Assert.AreSame(item0, item1);
Assert.AreNotSame(item0, item2);
Assert.AreNotSame(item0, item3);
Assert.AreEqual(1, item2.Val);
Assert.AreEqual(1, item3.Val);
Assert.AreNotSame(item2, item3);
// Test handle update inside collection.
builderCol = _grid.GetBinary().GetBuilder(binCol);
builderColItems = builderCol.GetField<IList>("col");
((BinaryObjectBuilder) builderColItems[1]).SetField("val", 3);
binCol = builderCol.Build();
col = binCol.Deserialize<BuilderCollection>();
item0 = (BuilderCollectionItem) col.Col[0];
item1 = (BuilderCollectionItem) col.Col[1];
Assert.AreEqual(3, item0.Val);
Assert.AreSame(item0, item1);
}
/// <summary>
/// Test build of an empty object.
/// </summary>
[Test]
public void TestEmptyDefined()
{
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(Empty)).Build();
Assert.IsNotNull(binObj);
Assert.AreEqual(1, binObj.GetHashCode());
IBinaryType meta = binObj.GetBinaryType();
Assert.IsNotNull(meta);
Assert.AreEqual(GetTypeName(typeof(Empty)), meta.TypeName);
Assert.AreEqual(0, meta.Fields.Count);
Empty obj = binObj.Deserialize<Empty>();
Assert.IsNotNull(obj);
}
/// <summary>
/// Test build of an empty undefined object.
/// </summary>
[Test]
public void TestEmptyUndefined()
{
IBinaryObject binObj = _grid.GetBinary().GetBuilder(TypeEmpty).Build();
Assert.IsNotNull(binObj);
Assert.AreEqual(1, binObj.GetHashCode());
IBinaryType meta = binObj.GetBinaryType();
Assert.IsNotNull(meta);
Assert.AreEqual(TypeEmpty, meta.TypeName);
Assert.AreEqual(0, meta.Fields.Count);
}
/// <summary>
/// Test object rebuild with no changes.
/// </summary>
[Test]
public void TestEmptyRebuild()
{
var binObj = (BinaryObject) _grid.GetBinary().GetBuilder(typeof(Empty)).Build();
BinaryObject newbinObj = (BinaryObject) _grid.GetBinary().GetBuilder(binObj).Build();
Assert.AreEqual(binObj.Data, newbinObj.Data);
}
/// <summary>
/// Tests equality and formatting members.
/// </summary>
[Test]
public void TestEquality()
{
var bin = _grid.GetBinary();
var obj1 = bin.GetBuilder("myType").SetStringField("str", "foo").SetIntField("int", 1).Build();
var obj2 = bin.GetBuilder("myType").SetStringField("str", "foo").SetIntField("int", 1).Build();
Assert.AreEqual(obj1, obj2);
Assert.AreEqual(-88648479, obj1.GetHashCode());
Assert.AreEqual(obj1.GetHashCode(), obj2.GetHashCode());
Assert.AreEqual("myType [, int=1, str=foo]", Regex.Replace(obj1.ToString(), "idHash=\\d+", ""));
}
/// <summary>
/// Test primitive fields setting.
/// </summary>
[Test]
public void TestPrimitiveFields()
{
// Generic SetField method.
var binObj = _grid.GetBinary().GetBuilder(typeof(Primitives))
.SetField<byte>("fByte", 1)
.SetField("fBool", true)
.SetField<short>("fShort", 2)
.SetField("fChar", 'a')
.SetField("fInt", 3)
.SetField<long>("fLong", 4)
.SetField<float>("fFloat", 5)
.SetField<double>("fDouble", 6)
.SetField("fDecimal", 7.7m)
.Build();
CheckPrimitiveFields1(binObj);
// Rebuild unchanged.
binObj = binObj.ToBuilder().Build();
CheckPrimitiveFields1(binObj);
// Specific setter methods.
var binObj2 = _grid.GetBinary().GetBuilder(typeof(Primitives))
.SetByteField("fByte", 1)
.SetBooleanField("fBool", true)
.SetShortField("fShort", 2)
.SetCharField("fChar", 'a')
.SetIntField("fInt", 3)
.SetLongField("fLong", 4)
.SetFloatField("fFloat", 5)
.SetDoubleField("fDouble", 6)
.SetDecimalField("fDecimal", 7.7m)
.Build();
CheckPrimitiveFields1(binObj2);
// Check equality.
Assert.AreEqual(binObj, binObj2);
Assert.AreEqual(binObj.GetHashCode(), binObj2.GetHashCode());
// Overwrite with generic methods.
binObj = binObj.ToBuilder()
.SetField<byte>("fByte", 7)
.SetField("fBool", false)
.SetField<short>("fShort", 8)
.SetField("fChar", 'b')
.SetField("fInt", 9)
.SetField<long>("fLong", 10)
.SetField<float>("fFloat", 11)
.SetField<double>("fDouble", 12)
.SetField("fDecimal", 13.13m)
.Build();
CheckPrimitiveFields2(binObj);
// Overwrite with specific methods.
binObj2 = binObj.ToBuilder()
.SetByteField("fByte", 7)
.SetBooleanField("fBool", false)
.SetShortField("fShort", 8)
.SetCharField("fChar", 'b')
.SetIntField("fInt", 9)
.SetLongField("fLong", 10)
.SetFloatField("fFloat", 11)
.SetDoubleField("fDouble", 12)
.SetDecimalField("fDecimal", 13.13m)
.Build();
CheckPrimitiveFields2(binObj);
// Check equality.
Assert.AreEqual(binObj, binObj2);
Assert.AreEqual(binObj.GetHashCode(), binObj2.GetHashCode());
}
/// <summary>
/// Checks the primitive fields values.
/// </summary>
private void CheckPrimitiveFields1(IBinaryObject binObj)
{
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(Primitives)), meta.TypeName);
Assert.AreEqual(9, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameByte, meta.GetFieldTypeName("fByte"));
Assert.AreEqual(BinaryTypeNames.TypeNameBool, meta.GetFieldTypeName("fBool"));
Assert.AreEqual(BinaryTypeNames.TypeNameShort, meta.GetFieldTypeName("fShort"));
Assert.AreEqual(BinaryTypeNames.TypeNameChar, meta.GetFieldTypeName("fChar"));
Assert.AreEqual(BinaryTypeNames.TypeNameInt, meta.GetFieldTypeName("fInt"));
Assert.AreEqual(BinaryTypeNames.TypeNameLong, meta.GetFieldTypeName("fLong"));
Assert.AreEqual(BinaryTypeNames.TypeNameFloat, meta.GetFieldTypeName("fFloat"));
Assert.AreEqual(BinaryTypeNames.TypeNameDouble, meta.GetFieldTypeName("fDouble"));
Assert.AreEqual(BinaryTypeNames.TypeNameDecimal, meta.GetFieldTypeName("fDecimal"));
Assert.AreEqual(1, binObj.GetField<byte>("fByte"));
Assert.AreEqual(true, binObj.GetField<bool>("fBool"));
Assert.AreEqual(2, binObj.GetField<short>("fShort"));
Assert.AreEqual('a', binObj.GetField<char>("fChar"));
Assert.AreEqual(3, binObj.GetField<int>("fInt"));
Assert.AreEqual(4, binObj.GetField<long>("fLong"));
Assert.AreEqual(5, binObj.GetField<float>("fFloat"));
Assert.AreEqual(6, binObj.GetField<double>("fDouble"));
Assert.AreEqual(7.7m, binObj.GetField<decimal>("fDecimal"));
Primitives obj = binObj.Deserialize<Primitives>();
Assert.AreEqual(1, obj.FByte);
Assert.AreEqual(true, obj.FBool);
Assert.AreEqual(2, obj.FShort);
Assert.AreEqual('a', obj.FChar);
Assert.AreEqual(3, obj.FInt);
Assert.AreEqual(4, obj.FLong);
Assert.AreEqual(5, obj.FFloat);
Assert.AreEqual(6, obj.FDouble);
Assert.AreEqual(7.7m, obj.FDecimal);
}
/// <summary>
/// Checks the primitive fields values.
/// </summary>
private static void CheckPrimitiveFields2(IBinaryObject binObj)
{
Assert.AreEqual(7, binObj.GetField<byte>("fByte"));
Assert.AreEqual(false, binObj.GetField<bool>("fBool"));
Assert.AreEqual(8, binObj.GetField<short>("fShort"));
Assert.AreEqual('b', binObj.GetField<char>("fChar"));
Assert.AreEqual(9, binObj.GetField<int>("fInt"));
Assert.AreEqual(10, binObj.GetField<long>("fLong"));
Assert.AreEqual(11, binObj.GetField<float>("fFloat"));
Assert.AreEqual(12, binObj.GetField<double>("fDouble"));
Assert.AreEqual(13.13m, binObj.GetField<decimal>("fDecimal"));
var obj = binObj.Deserialize<Primitives>();
Assert.AreEqual(7, obj.FByte);
Assert.AreEqual(false, obj.FBool);
Assert.AreEqual(8, obj.FShort);
Assert.AreEqual('b', obj.FChar);
Assert.AreEqual(9, obj.FInt);
Assert.AreEqual(10, obj.FLong);
Assert.AreEqual(11, obj.FFloat);
Assert.AreEqual(12, obj.FDouble);
Assert.AreEqual(13.13m, obj.FDecimal);
}
/// <summary>
/// Test primitive array fields setting.
/// </summary>
[Test]
public void TestPrimitiveArrayFields()
{
// Generic SetField method.
var binObj = _grid.GetBinary().GetBuilder(typeof(PrimitiveArrays))
.SetField("fByte", new byte[] { 1 })
.SetField("fBool", new[] { true })
.SetField("fShort", new short[] { 2 })
.SetField("fChar", new[] { 'a' })
.SetField("fInt", new[] { 3 })
.SetField("fLong", new long[] { 4 })
.SetField("fFloat", new float[] { 5 })
.SetField("fDouble", new double[] { 6 })
.SetField("fDecimal", new decimal?[] { 7.7m })
.Build();
CheckPrimitiveArrayFields1(binObj);
// Rebuild unchanged.
binObj = binObj.ToBuilder().Build();
CheckPrimitiveArrayFields1(binObj);
// Specific setters.
var binObj2 = _grid.GetBinary().GetBuilder(typeof(PrimitiveArrays))
.SetByteArrayField("fByte", new byte[] {1})
.SetBooleanArrayField("fBool", new[] {true})
.SetShortArrayField("fShort", new short[] {2})
.SetCharArrayField("fChar", new[] {'a'})
.SetIntArrayField("fInt", new[] {3})
.SetLongArrayField("fLong", new long[] {4})
.SetFloatArrayField("fFloat", new float[] {5})
.SetDoubleArrayField("fDouble", new double[] {6})
.SetDecimalArrayField("fDecimal", new decimal?[] {7.7m})
.Build();
CheckPrimitiveArrayFields1(binObj2);
// Check equality.
Assert.AreEqual(binObj, binObj2);
Assert.AreEqual(binObj.GetHashCode(), binObj2.GetHashCode());
// Overwrite with generic setter.
binObj = _grid.GetBinary().GetBuilder(binObj)
.SetField("fByte", new byte[] { 7 })
.SetField("fBool", new[] { false })
.SetField("fShort", new short[] { 8 })
.SetField("fChar", new[] { 'b' })
.SetField("fInt", new[] { 9 })
.SetField("fLong", new long[] { 10 })
.SetField("fFloat", new float[] { 11 })
.SetField("fDouble", new double[] { 12 })
.SetField("fDecimal", new decimal?[] { 13.13m })
.Build();
CheckPrimitiveArrayFields2(binObj);
// Overwrite with specific setters.
binObj2 = _grid.GetBinary().GetBuilder(binObj)
.SetByteArrayField("fByte", new byte[] { 7 })
.SetBooleanArrayField("fBool", new[] { false })
.SetShortArrayField("fShort", new short[] { 8 })
.SetCharArrayField("fChar", new[] { 'b' })
.SetIntArrayField("fInt", new[] { 9 })
.SetLongArrayField("fLong", new long[] { 10 })
.SetFloatArrayField("fFloat", new float[] { 11 })
.SetDoubleArrayField("fDouble", new double[] { 12 })
.SetDecimalArrayField("fDecimal", new decimal?[] { 13.13m })
.Build();
CheckPrimitiveArrayFields2(binObj);
// Check equality.
Assert.AreEqual(binObj, binObj2);
Assert.AreEqual(binObj.GetHashCode(), binObj2.GetHashCode());
}
/// <summary>
/// Checks the primitive array fields.
/// </summary>
private void CheckPrimitiveArrayFields1(IBinaryObject binObj)
{
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(PrimitiveArrays)), meta.TypeName);
Assert.AreEqual(9, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameArrayByte, meta.GetFieldTypeName("fByte"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayBool, meta.GetFieldTypeName("fBool"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayShort, meta.GetFieldTypeName("fShort"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayChar, meta.GetFieldTypeName("fChar"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayInt, meta.GetFieldTypeName("fInt"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayLong, meta.GetFieldTypeName("fLong"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayFloat, meta.GetFieldTypeName("fFloat"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayDouble, meta.GetFieldTypeName("fDouble"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayDecimal, meta.GetFieldTypeName("fDecimal"));
Assert.AreEqual(new byte[] { 1 }, binObj.GetField<byte[]>("fByte"));
Assert.AreEqual(new[] { true }, binObj.GetField<bool[]>("fBool"));
Assert.AreEqual(new short[] { 2 }, binObj.GetField<short[]>("fShort"));
Assert.AreEqual(new[] { 'a' }, binObj.GetField<char[]>("fChar"));
Assert.AreEqual(new[] { 3 }, binObj.GetField<int[]>("fInt"));
Assert.AreEqual(new long[] { 4 }, binObj.GetField<long[]>("fLong"));
Assert.AreEqual(new float[] { 5 }, binObj.GetField<float[]>("fFloat"));
Assert.AreEqual(new double[] { 6 }, binObj.GetField<double[]>("fDouble"));
Assert.AreEqual(new decimal?[] { 7.7m }, binObj.GetField<decimal?[]>("fDecimal"));
PrimitiveArrays obj = binObj.Deserialize<PrimitiveArrays>();
Assert.AreEqual(new byte[] { 1 }, obj.FByte);
Assert.AreEqual(new[] { true }, obj.FBool);
Assert.AreEqual(new short[] { 2 }, obj.FShort);
Assert.AreEqual(new[] { 'a' }, obj.FChar);
Assert.AreEqual(new[] { 3 }, obj.FInt);
Assert.AreEqual(new long[] { 4 }, obj.FLong);
Assert.AreEqual(new float[] { 5 }, obj.FFloat);
Assert.AreEqual(new double[] { 6 }, obj.FDouble);
Assert.AreEqual(new decimal?[] { 7.7m }, obj.FDecimal);
}
/// <summary>
/// Checks the primitive array fields.
/// </summary>
private static void CheckPrimitiveArrayFields2(IBinaryObject binObj)
{
Assert.AreEqual(new byte[] { 7 }, binObj.GetField<byte[]>("fByte"));
Assert.AreEqual(new[] { false }, binObj.GetField<bool[]>("fBool"));
Assert.AreEqual(new short[] { 8 }, binObj.GetField<short[]>("fShort"));
Assert.AreEqual(new[] { 'b' }, binObj.GetField<char[]>("fChar"));
Assert.AreEqual(new[] { 9 }, binObj.GetField<int[]>("fInt"));
Assert.AreEqual(new long[] { 10 }, binObj.GetField<long[]>("fLong"));
Assert.AreEqual(new float[] { 11 }, binObj.GetField<float[]>("fFloat"));
Assert.AreEqual(new double[] { 12 }, binObj.GetField<double[]>("fDouble"));
Assert.AreEqual(new decimal?[] { 13.13m }, binObj.GetField<decimal?[]>("fDecimal"));
var obj = binObj.Deserialize<PrimitiveArrays>();
Assert.AreEqual(new byte[] { 7 }, obj.FByte);
Assert.AreEqual(new[] { false }, obj.FBool);
Assert.AreEqual(new short[] { 8 }, obj.FShort);
Assert.AreEqual(new[] { 'b' }, obj.FChar);
Assert.AreEqual(new[] { 9 }, obj.FInt);
Assert.AreEqual(new long[] { 10 }, obj.FLong);
Assert.AreEqual(new float[] { 11 }, obj.FFloat);
Assert.AreEqual(new double[] { 12 }, obj.FDouble);
Assert.AreEqual(new decimal?[] { 13.13m }, obj.FDecimal);
}
/// <summary>
/// Test non-primitive fields and their array counterparts.
/// </summary>
[Test]
public void TestStringDateGuidEnum()
{
DateTime? nDate = DateTime.Now.ToUniversalTime();
Guid? nGuid = Guid.NewGuid();
// Generic setters.
var binObj = _grid.GetBinary().GetBuilder(typeof(StringDateGuidEnum))
.SetField("fStr", "str")
.SetField("fNDate", nDate)
.SetTimestampField("fNTimestamp", nDate)
.SetField("fNGuid", nGuid)
.SetField("fEnum", TestEnum.One)
.SetStringArrayField("fStrArr", new[] { "str" })
.SetArrayField("fDateArr", new[] { nDate })
.SetTimestampArrayField("fTimestampArr", new[] { nDate })
.SetGuidArrayField("fGuidArr", new[] { nGuid })
.SetEnumArrayField("fEnumArr", new[] { TestEnum.One })
.Build();
CheckStringDateGuidEnum1(binObj, nDate, nGuid);
// Rebuild with no changes.
binObj = binObj.ToBuilder().Build();
CheckStringDateGuidEnum1(binObj, nDate, nGuid);
// Specific setters.
var binObj2 = _grid.GetBinary().GetBuilder(typeof(StringDateGuidEnum))
.SetStringField("fStr", "str")
.SetField("fNDate", nDate)
.SetTimestampField("fNTimestamp", nDate)
.SetGuidField("fNGuid", nGuid)
.SetEnumField("fEnum", TestEnum.One)
.SetStringArrayField("fStrArr", new[] { "str" })
.SetArrayField("fDateArr", new[] { nDate })
.SetTimestampArrayField("fTimestampArr", new[] { nDate })
.SetGuidArrayField("fGuidArr", new[] { nGuid })
.SetEnumArrayField("fEnumArr", new[] { TestEnum.One })
.Build();
CheckStringDateGuidEnum1(binObj2, nDate, nGuid);
// Check equality.
Assert.AreEqual(binObj, binObj2);
Assert.AreEqual(binObj.GetHashCode(), binObj2.GetHashCode());
// Overwrite.
nDate = DateTime.Now.ToUniversalTime();
nGuid = Guid.NewGuid();
binObj = _grid.GetBinary().GetBuilder(typeof(StringDateGuidEnum))
.SetField("fStr", "str2")
.SetField("fNDate", nDate)
.SetTimestampField("fNTimestamp", nDate)
.SetField("fNGuid", nGuid)
.SetField("fEnum", TestEnum.Two)
.SetField("fStrArr", new[] { "str2" })
.SetArrayField("fDateArr", new[] { nDate })
.SetTimestampArrayField("fTimestampArr", new[] { nDate })
.SetField("fGuidArr", new[] { nGuid })
.SetField("fEnumArr", new[] { TestEnum.Two })
.Build();
CheckStringDateGuidEnum2(binObj, nDate, nGuid);
// Overwrite with specific setters
binObj2 = _grid.GetBinary().GetBuilder(typeof(StringDateGuidEnum))
.SetStringField("fStr", "str2")
.SetField("fNDate", nDate)
.SetTimestampField("fNTimestamp", nDate)
.SetGuidField("fNGuid", nGuid)
.SetEnumField("fEnum", TestEnum.Two)
.SetStringArrayField("fStrArr", new[] { "str2" })
.SetArrayField("fDateArr", new[] { nDate })
.SetTimestampArrayField("fTimestampArr", new[] { nDate })
.SetGuidArrayField("fGuidArr", new[] { nGuid })
.SetEnumArrayField("fEnumArr", new[] { TestEnum.Two })
.Build();
CheckStringDateGuidEnum2(binObj2, nDate, nGuid);
// Check equality.
Assert.AreEqual(binObj, binObj2);
Assert.AreEqual(binObj.GetHashCode(), binObj2.GetHashCode());
}
/// <summary>
/// Checks the string date guid enum values.
/// </summary>
private void CheckStringDateGuidEnum1(IBinaryObject binObj, DateTime? nDate, Guid? nGuid)
{
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(StringDateGuidEnum)), meta.TypeName);
Assert.AreEqual(10, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameString, meta.GetFieldTypeName("fStr"));
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("fNDate"));
Assert.AreEqual(BinaryTypeNames.TypeNameTimestamp, meta.GetFieldTypeName("fNTimestamp"));
Assert.AreEqual(BinaryTypeNames.TypeNameGuid, meta.GetFieldTypeName("fNGuid"));
Assert.AreEqual(BinaryTypeNames.TypeNameEnum, meta.GetFieldTypeName("fEnum"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayString, meta.GetFieldTypeName("fStrArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayObject, meta.GetFieldTypeName("fDateArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayTimestamp, meta.GetFieldTypeName("fTimestampArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayGuid, meta.GetFieldTypeName("fGuidArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayEnum, meta.GetFieldTypeName("fEnumArr"));
Assert.AreEqual("str", binObj.GetField<string>("fStr"));
Assert.AreEqual(nDate, binObj.GetField<IBinaryObject>("fNDate").Deserialize<DateTime?>());
Assert.AreEqual(nDate, binObj.GetField<DateTime?>("fNTimestamp"));
Assert.AreEqual(nGuid, binObj.GetField<Guid?>("fNGuid"));
Assert.AreEqual(TestEnum.One, binObj.GetField<IBinaryObject>("fEnum").Deserialize<TestEnum>());
Assert.AreEqual(new[] {"str"}, binObj.GetField<string[]>("fStrArr"));
Assert.AreEqual(new[] {nDate}, binObj.GetField<IBinaryObject[]>("fDateArr")
.Select(x => x.Deserialize<DateTime?>()));
Assert.AreEqual(new[] {nDate}, binObj.GetField<DateTime?[]>("fTimestampArr"));
Assert.AreEqual(new[] {nGuid}, binObj.GetField<Guid?[]>("fGuidArr"));
Assert.AreEqual(new[] {TestEnum.One},
binObj.GetField<IBinaryObject[]>("fEnumArr").Select(x => x.Deserialize<TestEnum>()));
StringDateGuidEnum obj = binObj.Deserialize<StringDateGuidEnum>();
Assert.AreEqual("str", obj.FStr);
Assert.AreEqual(nDate, obj.FnDate);
Assert.AreEqual(nDate, obj.FnTimestamp);
Assert.AreEqual(nGuid, obj.FnGuid);
Assert.AreEqual(TestEnum.One, obj.FEnum);
Assert.AreEqual(new[] {"str"}, obj.FStrArr);
Assert.AreEqual(new[] {nDate}, obj.FDateArr);
Assert.AreEqual(new[] {nGuid}, obj.FGuidArr);
Assert.AreEqual(new[] {TestEnum.One}, obj.FEnumArr);
// Check builder field caching.
var builder = _grid.GetBinary().GetBuilder(binObj);
Assert.AreEqual("str", builder.GetField<string>("fStr"));
Assert.AreEqual(nDate, builder.GetField<IBinaryObjectBuilder>("fNDate").Build().Deserialize<DateTime?>());
Assert.AreEqual(nDate, builder.GetField<DateTime?>("fNTimestamp"));
Assert.AreEqual(nGuid, builder.GetField<Guid?>("fNGuid"));
Assert.AreEqual(TestEnum.One, builder.GetField<IBinaryObject>("fEnum").Deserialize<TestEnum>());
Assert.AreEqual(new[] {"str"}, builder.GetField<string[]>("fStrArr"));
Assert.AreEqual(new[] {nDate}, builder.GetField<IBinaryObjectBuilder[]>("fDateArr")
.Select(x => x.Build().Deserialize<DateTime?>()));
Assert.AreEqual(new[] {nDate}, builder.GetField<DateTime?[]>("fTimestampArr"));
Assert.AreEqual(new[] {nGuid}, builder.GetField<Guid?[]>("fGuidArr"));
Assert.AreEqual(new[] {TestEnum.One},
builder.GetField<IBinaryObject[]>("fEnumArr").Select(x => x.Deserialize<TestEnum>()));
// Check reassemble.
binObj = builder.Build();
Assert.AreEqual("str", binObj.GetField<string>("fStr"));
Assert.AreEqual(nDate, binObj.GetField<IBinaryObject>("fNDate").Deserialize<DateTime?>());
Assert.AreEqual(nDate, binObj.GetField<DateTime?>("fNTimestamp"));
Assert.AreEqual(nGuid, binObj.GetField<Guid?>("fNGuid"));
Assert.AreEqual(TestEnum.One, binObj.GetField<IBinaryObject>("fEnum").Deserialize<TestEnum>());
Assert.AreEqual(new[] {"str"}, binObj.GetField<string[]>("fStrArr"));
Assert.AreEqual(new[] {nDate}, binObj.GetField<IBinaryObject[]>("fDateArr")
.Select(x => x.Deserialize<DateTime?>()));
Assert.AreEqual(new[] {nDate}, binObj.GetField<DateTime?[]>("fTimestampArr"));
Assert.AreEqual(new[] {nGuid}, binObj.GetField<Guid?[]>("fGuidArr"));
Assert.AreEqual(new[] { TestEnum.One },
binObj.GetField<IBinaryObject[]>("fEnumArr").Select(x => x.Deserialize<TestEnum>()));
obj = binObj.Deserialize<StringDateGuidEnum>();
Assert.AreEqual("str", obj.FStr);
Assert.AreEqual(nDate, obj.FnDate);
Assert.AreEqual(nDate, obj.FnTimestamp);
Assert.AreEqual(nGuid, obj.FnGuid);
Assert.AreEqual(TestEnum.One, obj.FEnum);
Assert.AreEqual(new[] {"str"}, obj.FStrArr);
Assert.AreEqual(new[] {nDate}, obj.FDateArr);
Assert.AreEqual(new[] {nGuid}, obj.FGuidArr);
Assert.AreEqual(new[] {TestEnum.One}, obj.FEnumArr);
}
/// <summary>
/// Checks the string date guid enum values.
/// </summary>
private static void CheckStringDateGuidEnum2(IBinaryObject binObj, DateTime? nDate, Guid? nGuid)
{
Assert.AreEqual("str2", binObj.GetField<string>("fStr"));
Assert.AreEqual(nDate, binObj.GetField<IBinaryObject>("fNDate").Deserialize<DateTime?>());
Assert.AreEqual(nDate, binObj.GetField<DateTime?>("fNTimestamp"));
Assert.AreEqual(nGuid, binObj.GetField<Guid?>("fNGuid"));
Assert.AreEqual(TestEnum.Two, binObj.GetField<IBinaryObject>("fEnum").Deserialize<TestEnum>());
Assert.AreEqual(new[] { "str2" }, binObj.GetField<string[]>("fStrArr"));
Assert.AreEqual(new[] {nDate}, binObj.GetField<IBinaryObject[]>("fDateArr")
.Select(x => x.Deserialize<DateTime?>()));
Assert.AreEqual(new[] { nDate }, binObj.GetField<DateTime?[]>("fTimestampArr"));
Assert.AreEqual(new[] { nGuid }, binObj.GetField<Guid?[]>("fGuidArr"));
Assert.AreEqual(new[] {TestEnum.Two},
binObj.GetField<IBinaryObject[]>("fEnumArr").Select(x => x.Deserialize<TestEnum>()));
var obj = binObj.Deserialize<StringDateGuidEnum>();
Assert.AreEqual("str2", obj.FStr);
Assert.AreEqual(nDate, obj.FnDate);
Assert.AreEqual(nDate, obj.FnTimestamp);
Assert.AreEqual(nGuid, obj.FnGuid);
Assert.AreEqual(TestEnum.Two, obj.FEnum);
Assert.AreEqual(new[] { "str2" }, obj.FStrArr);
Assert.AreEqual(new[] { nDate }, obj.FDateArr);
Assert.AreEqual(new[] { nGuid }, obj.FGuidArr);
Assert.AreEqual(new[] { TestEnum.Two }, obj.FEnumArr);
}
[Test]
public void TestEnumMeta()
{
var bin = _grid.GetBinary();
// Put to cache to populate metas
var binEnum = bin.ToBinary<IBinaryObject>(TestEnumRegistered.One);
Assert.AreEqual(_marsh.GetDescriptor(typeof (TestEnumRegistered)).TypeId, binEnum.GetBinaryType().TypeId);
Assert.AreEqual(0, binEnum.EnumValue);
var meta = binEnum.GetBinaryType();
Assert.IsTrue(meta.IsEnum);
Assert.AreEqual(GetTypeName(typeof (TestEnumRegistered)), meta.TypeName);
Assert.AreEqual(0, meta.Fields.Count);
}
/// <summary>
/// Test arrays.
/// </summary>
[Test]
public void TestCompositeArray()
{
// 1. Test simple array.
object[] inArr = { new CompositeInner(1) };
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(CompositeArray))
.SetField("inArr", inArr).Build();
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(CompositeArray)), meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameArrayObject, meta.GetFieldTypeName("inArr"));
var binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(1, binInArr.Length);
Assert.AreEqual(1, binInArr[0].GetField<int>("val"));
CompositeArray arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(1, arr.InArr.Length);
Assert.AreEqual(1, ((CompositeInner) arr.InArr[0]).Val);
// 2. Test addition to array.
binObj = _grid.GetBinary().GetBuilder(binObj)
.SetField("inArr", new[] { binInArr[0], null }).Build();
binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(1, binInArr[0].GetField<int>("val"));
Assert.IsNull(binInArr[1]);
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(2, arr.InArr.Length);
Assert.AreEqual(1, ((CompositeInner) arr.InArr[0]).Val);
Assert.IsNull(arr.InArr[1]);
binInArr[1] = _grid.GetBinary().GetBuilder(typeof(CompositeInner)).SetField("val", 2).Build();
binObj = _grid.GetBinary().GetBuilder(binObj)
.SetField("inArr", binInArr.OfType<object>().ToArray()).Build();
binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(1, binInArr[0].GetField<int>("val"));
Assert.AreEqual(2, binInArr[1].GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(2, arr.InArr.Length);
Assert.AreEqual(1, ((CompositeInner)arr.InArr[0]).Val);
Assert.AreEqual(2, ((CompositeInner)arr.InArr[1]).Val);
// 3. Test top-level handle inversion.
CompositeInner inner = new CompositeInner(1);
inArr = new object[] { inner, inner };
binObj = _grid.GetBinary().GetBuilder(typeof(CompositeArray))
.SetField("inArr", inArr).Build();
binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(1, binInArr[0].GetField<int>("val"));
Assert.AreEqual(1, binInArr[1].GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(2, arr.InArr.Length);
Assert.AreEqual(1, ((CompositeInner)arr.InArr[0]).Val);
Assert.AreEqual(1, ((CompositeInner)arr.InArr[1]).Val);
binInArr[0] = _grid.GetBinary().GetBuilder(typeof(CompositeInner)).SetField("val", 2).Build();
binObj = _grid.GetBinary().GetBuilder(binObj)
.SetField("inArr", binInArr.ToArray<object>()).Build();
binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(2, binInArr[0].GetField<int>("val"));
Assert.AreEqual(1, binInArr[1].GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(2, arr.InArr.Length);
Assert.AreEqual(2, ((CompositeInner)arr.InArr[0]).Val);
Assert.AreEqual(1, ((CompositeInner)arr.InArr[1]).Val);
// 4. Test nested object handle inversion.
CompositeOuter[] outArr = { new CompositeOuter(inner), new CompositeOuter(inner) };
binObj = _grid.GetBinary().GetBuilder(typeof(CompositeArray))
.SetField("outArr", outArr.ToArray<object>()).Build();
meta = binObj.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(CompositeArray)), meta.TypeName);
Assert.AreEqual(2, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameArrayObject, meta.GetFieldTypeName("inArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayObject, meta.GetFieldTypeName("outArr"));
var binOutArr = binObj.GetField<IBinaryObject[]>("outArr").ToArray();
Assert.AreEqual(2, binOutArr.Length);
Assert.AreEqual(1, binOutArr[0].GetField<IBinaryObject>("inner").GetField<int>("val"));
Assert.AreEqual(1, binOutArr[1].GetField<IBinaryObject>("inner").GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.InArr);
Assert.AreEqual(2, arr.OutArr.Length);
Assert.AreEqual(1, ((CompositeOuter) arr.OutArr[0]).Inner.Val);
Assert.AreEqual(1, ((CompositeOuter) arr.OutArr[0]).Inner.Val);
binOutArr[0] = _grid.GetBinary().GetBuilder(typeof(CompositeOuter))
.SetField("inner", new CompositeInner(2)).Build();
binObj = _grid.GetBinary().GetBuilder(binObj)
.SetField("outArr", binOutArr.ToArray<object>()).Build();
binInArr = binObj.GetField<IBinaryObject[]>("outArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(2, binOutArr[0].GetField<IBinaryObject>("inner").GetField<int>("val"));
Assert.AreEqual(1, binOutArr[1].GetField<IBinaryObject>("inner").GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.InArr);
Assert.AreEqual(2, arr.OutArr.Length);
Assert.AreEqual(2, ((CompositeOuter)arr.OutArr[0]).Inner.Val);
Assert.AreEqual(1, ((CompositeOuter)arr.OutArr[1]).Inner.Val);
}
/// <summary>
/// Test container types other than array.
/// </summary>
[Test]
public void TestCompositeContainer()
{
ArrayList col = new ArrayList();
IDictionary dict = new Hashtable();
col.Add(new CompositeInner(1));
dict[3] = new CompositeInner(3);
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(CompositeContainer))
.SetCollectionField("col", col)
.SetDictionaryField("dict", dict).Build();
// 1. Check meta.
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(CompositeContainer)), meta.TypeName);
Assert.AreEqual(2, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameCollection, meta.GetFieldTypeName("col"));
Assert.AreEqual(BinaryTypeNames.TypeNameMap, meta.GetFieldTypeName("dict"));
// 2. Check in binary form.
Assert.AreEqual(1, binObj.GetField<ICollection>("col").Count);
Assert.AreEqual(1, binObj.GetField<ICollection>("col").OfType<IBinaryObject>().First()
.GetField<int>("val"));
Assert.AreEqual(1, binObj.GetField<IDictionary>("dict").Count);
Assert.AreEqual(3, ((IBinaryObject) binObj.GetField<IDictionary>("dict")[3]).GetField<int>("val"));
// 3. Check in deserialized form.
CompositeContainer obj = binObj.Deserialize<CompositeContainer>();
Assert.AreEqual(1, obj.Col.Count);
Assert.AreEqual(1, obj.Col.OfType<CompositeInner>().First().Val);
Assert.AreEqual(1, obj.Dict.Count);
Assert.AreEqual(3, ((CompositeInner) obj.Dict[3]).Val);
}
/// <summary>
/// Ensure that raw data is not lost during build.
/// </summary>
[Test]
public void TestRawData()
{
var raw = new WithRaw
{
A = 1,
B = 2
};
var binObj = _marsh.Unmarshal<IBinaryObject>(_marsh.Marshal(raw), BinaryMode.ForceBinary);
raw = binObj.Deserialize<WithRaw>();
Assert.AreEqual(1, raw.A);
Assert.AreEqual(2, raw.B);
IBinaryObject newbinObj = _grid.GetBinary().GetBuilder(binObj).SetField("a", 3).Build();
raw = newbinObj.Deserialize<WithRaw>();
Assert.AreEqual(3, raw.A);
Assert.AreEqual(2, raw.B);
}
/// <summary>
/// Test nested objects.
/// </summary>
[Test]
public void TestNested()
{
// 1. Create from scratch.
IBinaryObjectBuilder builder = _grid.GetBinary().GetBuilder(typeof(NestedOuter));
NestedInner inner1 = new NestedInner {Val = 1};
builder.SetField("inner1", inner1);
IBinaryObject outerbinObj = builder.Build();
IBinaryType meta = outerbinObj.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(NestedOuter)), meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("inner1"));
IBinaryObject innerbinObj1 = outerbinObj.GetField<IBinaryObject>("inner1");
IBinaryType innerMeta = innerbinObj1.GetBinaryType();
Assert.AreEqual(GetTypeName(typeof(NestedInner)), innerMeta.TypeName);
Assert.AreEqual(1, innerMeta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameInt, innerMeta.GetFieldTypeName("Val"));
inner1 = innerbinObj1.Deserialize<NestedInner>();
Assert.AreEqual(1, inner1.Val);
NestedOuter outer = outerbinObj.Deserialize<NestedOuter>();
Assert.AreEqual(outer.Inner1.Val, 1);
Assert.IsNull(outer.Inner2);
// 2. Add another field over existing binary object.
builder = _grid.GetBinary().GetBuilder(outerbinObj);
NestedInner inner2 = new NestedInner {Val = 2};
builder.SetField("inner2", inner2);
outerbinObj = builder.Build();
outer = outerbinObj.Deserialize<NestedOuter>();
Assert.AreEqual(1, outer.Inner1.Val);
Assert.AreEqual(2, outer.Inner2.Val);
// 3. Try setting inner object in binary form.
innerbinObj1 = _grid.GetBinary().GetBuilder(innerbinObj1).SetField("val", 3).Build();
inner1 = innerbinObj1.Deserialize<NestedInner>();
Assert.AreEqual(3, inner1.Val);
outerbinObj = _grid.GetBinary().GetBuilder(outerbinObj).SetField<object>("inner1", innerbinObj1).Build();
outer = outerbinObj.Deserialize<NestedOuter>();
Assert.AreEqual(3, outer.Inner1.Val);
Assert.AreEqual(2, outer.Inner2.Val);
}
/// <summary>
/// Test handle migration.
/// </summary>
[Test]
public void TestHandleMigration()
{
// 1. Simple comparison of results.
MigrationInner inner = new MigrationInner {Val = 1};
MigrationOuter outer = new MigrationOuter
{
Inner1 = inner,
Inner2 = inner
};
byte[] outerBytes = _marsh.Marshal(outer);
IBinaryObjectBuilder builder = _grid.GetBinary().GetBuilder(typeof(MigrationOuter));
builder.SetField<object>("inner1", inner);
builder.SetField<object>("inner2", inner);
BinaryObject portOuter = (BinaryObject) builder.Build();
byte[] portOuterBytes = new byte[outerBytes.Length];
Buffer.BlockCopy(portOuter.Data, 0, portOuterBytes, 0, portOuterBytes.Length);
Assert.AreEqual(outerBytes, portOuterBytes);
// 2. Change the first inner object so that the handle must migrate.
MigrationInner inner1 = new MigrationInner {Val = 2};
IBinaryObject portOuterMigrated =
_grid.GetBinary().GetBuilder(portOuter).SetField<object>("inner1", inner1).Build();
MigrationOuter outerMigrated = portOuterMigrated.Deserialize<MigrationOuter>();
Assert.AreEqual(2, outerMigrated.Inner1.Val);
Assert.AreEqual(1, outerMigrated.Inner2.Val);
// 3. Change the first value using serialized form.
IBinaryObject inner1Port =
_grid.GetBinary().GetBuilder(typeof(MigrationInner)).SetField("val", 2).Build();
portOuterMigrated =
_grid.GetBinary().GetBuilder(portOuter).SetField<object>("inner1", inner1Port).Build();
outerMigrated = portOuterMigrated.Deserialize<MigrationOuter>();
Assert.AreEqual(2, outerMigrated.Inner1.Val);
Assert.AreEqual(1, outerMigrated.Inner2.Val);
}
/// <summary>
/// Test handle inversion.
/// </summary>
[Test]
public void TestHandleInversion()
{
InversionInner inner = new InversionInner();
InversionOuter outer = new InversionOuter();
inner.Outer = outer;
outer.Inner = inner;
byte[] rawOuter = _marsh.Marshal(outer);
IBinaryObject portOuter = _marsh.Unmarshal<IBinaryObject>(rawOuter, BinaryMode.ForceBinary);
IBinaryObject portInner = portOuter.GetField<IBinaryObject>("inner");
// 1. Ensure that inner object can be deserialized after build.
IBinaryObject portInnerNew = _grid.GetBinary().GetBuilder(portInner).Build();
InversionInner innerNew = portInnerNew.Deserialize<InversionInner>();
Assert.AreSame(innerNew, innerNew.Outer.Inner);
// 2. Ensure that binary object with external dependencies could be added to builder.
IBinaryObject portOuterNew =
_grid.GetBinary().GetBuilder(typeof(InversionOuter)).SetField<object>("inner", portInner).Build();
InversionOuter outerNew = portOuterNew.Deserialize<InversionOuter>();
Assert.AreNotSame(outerNew, outerNew.Inner.Outer);
Assert.AreSame(outerNew.Inner, outerNew.Inner.Outer.Inner);
}
/// <summary>
/// Test build multiple objects.
/// </summary>
[Test]
public void TestBuildMultiple()
{
IBinaryObjectBuilder builder = _grid.GetBinary().GetBuilder(typeof(Primitives));
builder.SetField<byte>("fByte", 1).SetField("fBool", true);
IBinaryObject po1 = builder.Build();
IBinaryObject po2 = builder.Build();
Assert.AreEqual(1, po1.GetField<byte>("fByte"));
Assert.AreEqual(true, po1.GetField<bool>("fBool"));
Assert.AreEqual(1, po2.GetField<byte>("fByte"));
Assert.AreEqual(true, po2.GetField<bool>("fBool"));
builder.SetField<byte>("fByte", 2);
IBinaryObject po3 = builder.Build();
Assert.AreEqual(1, po1.GetField<byte>("fByte"));
Assert.AreEqual(true, po1.GetField<bool>("fBool"));
Assert.AreEqual(1, po2.GetField<byte>("fByte"));
Assert.AreEqual(true, po2.GetField<bool>("fBool"));
Assert.AreEqual(2, po3.GetField<byte>("fByte"));
Assert.AreEqual(true, po2.GetField<bool>("fBool"));
builder = _grid.GetBinary().GetBuilder(po1);
builder.SetField<byte>("fByte", 10);
po1 = builder.Build();
po2 = builder.Build();
builder.SetField<byte>("fByte", 20);
po3 = builder.Build();
Assert.AreEqual(10, po1.GetField<byte>("fByte"));
Assert.AreEqual(true, po1.GetField<bool>("fBool"));
Assert.AreEqual(10, po2.GetField<byte>("fByte"));
Assert.AreEqual(true, po2.GetField<bool>("fBool"));
Assert.AreEqual(20, po3.GetField<byte>("fByte"));
Assert.AreEqual(true, po3.GetField<bool>("fBool"));
}
/// <summary>
/// Tests type id method.
/// </summary>
[Test]
public void TestTypeId()
{
Assert.Throws<ArgumentException>(() => _grid.GetBinary().GetTypeId(null));
Assert.AreEqual(IdMapper.TestTypeId, _grid.GetBinary().GetTypeId(IdMapper.TestTypeName));
Assert.AreEqual(BinaryUtils.GetStringHashCode("someTypeName"), _grid.GetBinary().GetTypeId("someTypeName"));
}
/// <summary>
/// Tests type name mapper.
/// </summary>
[Test]
public void TestTypeName()
{
var bytes = _marsh.Marshal(new NameMapperTestType {NameMapperTestField = 17});
var bin = _marsh.Unmarshal<IBinaryObject>(bytes, BinaryMode.ForceBinary);
var binType = bin.GetBinaryType();
Assert.AreEqual(BinaryUtils.GetStringHashCode(NameMapper.TestTypeName + "_"), binType.TypeId);
Assert.AreEqual(17, bin.GetField<int>(NameMapper.TestFieldName));
}
/// <summary>
/// Tests metadata methods.
/// </summary>
[Test]
public void TestMetadata()
{
// Populate metadata
var binary = _grid.GetBinary();
binary.ToBinary<IBinaryObject>(new DecimalHolder());
var typeName = GetTypeName(typeof(DecimalHolder));
// All meta
var allMetas = binary.GetBinaryTypes();
var decimalMeta = allMetas.Single(x => x.TypeName == typeName);
Assert.AreEqual(new[] {"val", "valArr"}, decimalMeta.Fields);
// By type
decimalMeta = binary.GetBinaryType(typeof (DecimalHolder));
Assert.AreEqual(new[] {"val", "valArr"}, decimalMeta.Fields);
// By type id
decimalMeta = binary.GetBinaryType(binary.GetTypeId(typeName));
Assert.AreEqual(new[] {"val", "valArr"}, decimalMeta.Fields);
// By type name
decimalMeta = binary.GetBinaryType(typeName);
Assert.AreEqual(new[] {"val", "valArr"}, decimalMeta.Fields);
}
[Test]
public void TestBuildEnum()
{
var binary = _grid.GetBinary();
int val = (int) TestEnumRegistered.Two;
var binEnums = new[]
{
binary.BuildEnum(typeof (TestEnumRegistered), val),
binary.BuildEnum(GetTypeName(typeof (TestEnumRegistered)), val)
};
foreach (var binEnum in binEnums)
{
Assert.IsTrue(binEnum.GetBinaryType().IsEnum);
Assert.AreEqual(val, binEnum.EnumValue);
Assert.AreEqual((TestEnumRegistered) val, binEnum.Deserialize<TestEnumRegistered>());
}
Assert.AreEqual(binEnums[0], binEnums[1]);
Assert.AreEqual(binEnums[0].GetHashCode(), binEnums[1].GetHashCode());
}
/// <summary>
/// Tests the compact footer setting.
/// </summary>
[Test]
public void TestCompactFooterSetting()
{
Assert.AreEqual(GetCompactFooter(), _marsh.CompactFooter);
}
/// <summary>
/// Tests the binary mode on remote node.
/// </summary>
[Test]
public void TestRemoteBinaryMode()
{
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
IgniteInstanceName = "grid2",
BinaryConfiguration = new BinaryConfiguration
{
CompactFooter = GetCompactFooter()
}
};
using (var grid2 = Ignition.Start(cfg))
{
var cache1 = _grid.GetOrCreateCache<int, Primitives>("cache");
var cache2 = grid2.GetCache<int, object>("cache").WithKeepBinary<int, IBinaryObject>();
// Exchange data
cache1[1] = new Primitives {FByte = 3};
var obj = cache2[1];
// Rebuild with no changes.
cache2[2] = obj.ToBuilder().Build();
Assert.AreEqual(3, cache1[2].FByte);
// Rebuild with read
Assert.AreEqual(3, obj.GetField<byte>("FByte"));
cache2[3] = obj.ToBuilder().Build();
Assert.AreEqual(3, cache1[3].FByte);
// Modify and rebuild
cache2[4] = obj.ToBuilder().SetField("FShort", (short) 15).Build();
Assert.AreEqual(15, cache1[4].FShort);
// New binary type without a class
cache2[5] = grid2.GetBinary().GetBuilder("myNewType").SetField("foo", "bar").Build();
var cache1Bin = cache1.WithKeepBinary<int, IBinaryObject>();
var newObj = cache1Bin[5];
Assert.AreEqual("bar", newObj.GetField<string>("foo"));
cache1Bin[6] = newObj.ToBuilder().SetField("foo2", 3).Build();
Assert.AreEqual(3, cache2[6].GetField<int>("foo2"));
}
}
/// <summary>
/// Tests that fields are sorted by name in serialized form.
/// </summary>
[Test]
public void TestFieldSorting()
{
var obj1 = (BinaryObject)_grid.GetBinary().GetBuilder("sortTest")
.SetByteField("c", 3).SetByteField("b", 1).SetByteField("a", 2).Build();
var obj2 = (BinaryObject)_grid.GetBinary().GetBuilder("sortTest")
.SetByteField("b", 1).SetByteField("a", 2).SetByteField("c", 3).Build();
Assert.AreEqual(obj1, obj2);
Assert.AreEqual(obj1.GetHashCode(), obj2.GetHashCode());
Assert.AreEqual("sortTest [, a=2, b=1, c=3]", Regex.Replace(obj1.ToString(), "idHash=\\d+", ""));
// Skip header, take 3 fields (type code + value).
var bytes1 = obj1.Data.Skip(24).Take(6).ToArray();
var bytes2 = obj2.Data.Skip(24).Take(6).ToArray();
Assert.AreEqual(bytes1, bytes2);
Assert.AreEqual(new[] {1, 2, 1, 1, 1, 3}, bytes1);
}
}
/// <summary>
/// Empty binary class.
/// </summary>
public class Empty
{
// No-op.
}
/// <summary>
/// binary with primitive fields.
/// </summary>
public class Primitives
{
public byte FByte;
public bool FBool;
public short FShort;
public char FChar;
public int FInt;
public long FLong;
public float FFloat;
public double FDouble;
public decimal FDecimal;
}
/// <summary>
/// binary with primitive array fields.
/// </summary>
public class PrimitiveArrays
{
public byte[] FByte;
public bool[] FBool;
public short[] FShort;
public char[] FChar;
public int[] FInt;
public long[] FLong;
public float[] FFloat;
public double[] FDouble;
public decimal?[] FDecimal;
}
/// <summary>
/// binary having strings, dates, Guids and enums.
/// </summary>
public class StringDateGuidEnum
{
public string FStr;
public DateTime? FnDate;
public DateTime? FnTimestamp;
public Guid? FnGuid;
public TestEnum FEnum;
public string[] FStrArr;
public DateTime?[] FDateArr;
public Guid?[] FGuidArr;
public TestEnum[] FEnumArr;
}
/// <summary>
/// Enumeration.
/// </summary>
public enum TestEnum
{
One, Two
}
/// <summary>
/// Registered enumeration.
/// </summary>
public enum TestEnumRegistered
{
One, Two
}
/// <summary>
/// binary with raw data.
/// </summary>
public class WithRaw : IBinarizable
{
public int A;
public int B;
/** <inheritDoc /> */
public void WriteBinary(IBinaryWriter writer)
{
writer.WriteInt("a", A);
writer.GetRawWriter().WriteInt(B);
}
/** <inheritDoc /> */
public void ReadBinary(IBinaryReader reader)
{
A = reader.ReadInt("a");
B = reader.GetRawReader().ReadInt();
}
}
/// <summary>
/// Empty class for metadata overwrite test.
/// </summary>
public class MetaOverwrite
{
// No-op.
}
/// <summary>
/// Nested outer object.
/// </summary>
public class NestedOuter
{
public NestedInner Inner1;
public NestedInner Inner2;
}
/// <summary>
/// Nested inner object.
/// </summary>
public class NestedInner
{
public int Val;
}
/// <summary>
/// Outer object for handle migration test.
/// </summary>
public class MigrationOuter
{
public MigrationInner Inner1;
public MigrationInner Inner2;
}
/// <summary>
/// Inner object for handle migration test.
/// </summary>
public class MigrationInner
{
public int Val;
}
/// <summary>
/// Outer object for handle inversion test.
/// </summary>
public class InversionOuter
{
public InversionInner Inner;
}
/// <summary>
/// Inner object for handle inversion test.
/// </summary>
public class InversionInner
{
public InversionOuter Outer;
}
/// <summary>
/// Object for composite array tests.
/// </summary>
public class CompositeArray
{
public object[] InArr;
public object[] OutArr;
}
/// <summary>
/// Object for composite collection/dictionary tests.
/// </summary>
public class CompositeContainer
{
public ICollection Col;
public IDictionary Dict;
}
/// <summary>
/// OUter object for composite structures test.
/// </summary>
public class CompositeOuter
{
public CompositeInner Inner;
public CompositeOuter()
{
// No-op.
}
public CompositeOuter(CompositeInner inner)
{
Inner = inner;
}
}
/// <summary>
/// Inner object for composite structures test.
/// </summary>
public class CompositeInner
{
public int Val;
public CompositeInner()
{
// No-op.
}
public CompositeInner(int val)
{
Val = val;
}
}
/// <summary>
/// Type to test "ToBinary()" logic.
/// </summary>
public class ToBinary
{
public int Val;
public ToBinary(int val)
{
Val = val;
}
}
/// <summary>
/// Type to test removal.
/// </summary>
public class Remove
{
public object Val;
public RemoveInner Val2;
}
/// <summary>
/// Inner type to test removal.
/// </summary>
public class RemoveInner
{
/** */
public int Val;
/// <summary>
///
/// </summary>
/// <param name="val"></param>
public RemoveInner(int val)
{
Val = val;
}
}
/// <summary>
///
/// </summary>
public class BuilderInBuilderOuter
{
/** */
public BuilderInBuilderInner Inner;
/** */
public BuilderInBuilderInner Inner2;
}
/// <summary>
///
/// </summary>
public class BuilderInBuilderInner
{
/** */
public BuilderInBuilderOuter Outer;
}
/// <summary>
///
/// </summary>
public class BuilderCollection
{
/** */
public readonly ArrayList Col;
/// <summary>
///
/// </summary>
/// <param name="col"></param>
public BuilderCollection(ArrayList col)
{
Col = col;
}
}
/// <summary>
///
/// </summary>
public class BuilderCollectionItem
{
/** */
public int Val;
/// <summary>
///
/// </summary>
/// <param name="val"></param>
public BuilderCollectionItem(int val)
{
Val = val;
}
}
/// <summary>
///
/// </summary>
public class DecimalHolder
{
/** */
public decimal Val;
/** */
public decimal?[] ValArr;
}
/// <summary>
/// Test id mapper.
/// </summary>
public class IdMapper : IBinaryIdMapper
{
/** */
public const string TestTypeName = "IdMapperTestType";
/** */
public const int TestTypeId = -65537;
/** <inheritdoc /> */
public int GetTypeId(string typeName)
{
return typeName == TestTypeName ? TestTypeId : 0;
}
/** <inheritdoc /> */
public int GetFieldId(int typeId, string fieldName)
{
return 0;
}
}
/// <summary>
/// Test name mapper.
/// </summary>
public class NameMapper : IBinaryNameMapper
{
/** */
private readonly IBinaryNameMapper _baseMapper;
/** */
public const string TestTypeName = "NameMapperTestType";
/** */
public const string TestFieldName = "NameMapperTestField";
/// <summary>
/// Initializes a new instance of the <see cref="NameMapper" /> class.
/// </summary>
/// <param name="baseMapper">The base mapper.</param>
public NameMapper(IBinaryNameMapper baseMapper)
{
_baseMapper = baseMapper;
}
/** <inheritdoc /> */
public string GetTypeName(string name)
{
if (name == typeof(NameMapperTestType).AssemblyQualifiedName)
return TestTypeName + "_";
return _baseMapper.GetTypeName(name);
}
/** <inheritdoc /> */
public string GetFieldName(string name)
{
if (name == TestFieldName)
return name + "_";
return name;
}
}
/// <summary>
/// Name mapper test type.
/// </summary>
public class NameMapperTestType
{
/** */
public int NameMapperTestField { get; set; }
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Internal;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Reflection.Metadata
{
/// <summary>
/// Reads metadata as defined byte the ECMA 335 CLI specification.
/// </summary>
public sealed partial class MetadataReader
{
private readonly MetadataReaderOptions options;
internal readonly MetadataStringDecoder utf8Decoder;
internal readonly NamespaceCache namespaceCache;
private Dictionary<TypeDefinitionHandle, ImmutableArray<TypeDefinitionHandle>> lazyNestedTypesMap;
internal readonly MemoryBlock Block;
// A row id of "mscorlib" AssemblyRef in a WinMD file (each WinMD file must have such a reference).
internal readonly uint WinMDMscorlibRef;
#region Constructors
/// <summary>
/// Creates a metadata reader from the metadata stored at the given memory location.
/// </summary>
/// <remarks>
/// The memory is owned by the caller and it must be kept memory alive and unmodified throughout the lifetime of the <see cref="MetadataReader"/>.
/// </remarks>
public unsafe MetadataReader(byte* metadata, int length)
: this(metadata, length, MetadataReaderOptions.Default, null)
{
}
/// <summary>
/// Creates a metadata reader from the metadata stored at the given memory location.
/// </summary>
/// <remarks>
/// The memory is owned by the caller and it must be kept memory alive and unmodified throughout the lifetime of the <see cref="MetadataReader"/>.
/// Use <see cref="PEReaderExtensions.GetMetadataReader(PortableExecutable.PEReader, MetadataReaderOptions)"/> to obtain
/// metadata from a PE image.
/// </remarks>
public unsafe MetadataReader(byte* metadata, int length, MetadataReaderOptions options)
: this(metadata, length, options, null)
{
}
/// <summary>
/// Creates a metadata reader from the metadata stored at the given memory location.
/// </summary>
/// <remarks>
/// The memory is owned by the caller and it must be kept memory alive and unmodified throughout the lifetime of the <see cref="MetadataReader"/>.
/// Use <see cref="PEReaderExtensions.GetMetadataReader(PortableExecutable.PEReader, MetadataReaderOptions, MetadataStringDecoder)"/> to obtain
/// metadata from a PE image.
/// </remarks>
public unsafe MetadataReader(byte* metadata, int length, MetadataReaderOptions options, MetadataStringDecoder utf8Decoder)
{
if (length <= 0)
{
throw new ArgumentOutOfRangeException("length");
}
if (metadata == null)
{
throw new ArgumentNullException("metadata");
}
if (utf8Decoder == null)
{
utf8Decoder = MetadataStringDecoder.DefaultUTF8;
}
if (!(utf8Decoder.Encoding is UTF8Encoding))
{
throw new ArgumentException(MetadataResources.MetadataStringDecoderEncodingMustBeUtf8, "utf8Decoder");
}
if (!BitConverter.IsLittleEndian)
{
throw new PlatformNotSupportedException(MetadataResources.LitteEndianArchitectureRequired);
}
this.Block = new MemoryBlock(metadata, length);
this.options = options;
this.utf8Decoder = utf8Decoder;
BlobReader memReader = new BlobReader(this.Block);
this.ReadMetadataHeader(ref memReader);
// storage header and stream headers:
MemoryBlock metadataTableStream;
var streamHeaders = this.ReadStreamHeaders(ref memReader);
this.InitializeStreamReaders(ref this.Block, streamHeaders, out metadataTableStream);
memReader = new BlobReader(metadataTableStream);
uint[] metadataTableRowCounts;
this.ReadMetadataTableHeader(ref memReader, out metadataTableRowCounts);
this.InitializeTableReaders(memReader.GetMemoryBlockAt(0, memReader.RemainingBytes), metadataTableRowCounts);
// This previously could occur in obfuscated assemblies but a check was added to prevent
// it getting to this point
Debug.Assert(this.AssemblyTable.NumberOfRows <= 1);
// Although the specification states that the module table will have exactly one row,
// the native metadata reader would successfully read files containing more than one row.
// Such files exist in the wild and may be produced by obfuscators.
if (this.ModuleTable.NumberOfRows < 1)
{
throw new BadImageFormatException(string.Format(MetadataResources.ModuleTableInvalidNumberOfRows, this.ModuleTable.NumberOfRows));
}
// read
this.namespaceCache = new NamespaceCache(this);
if (this.metadataKind != MetadataKind.Ecma335)
{
this.WinMDMscorlibRef = FindMscorlibAssemblyRefNoProjection();
}
}
#endregion
#region Metadata Headers
private MetadataHeader metadataHeader;
private MetadataKind metadataKind;
private MetadataStreamKind metadataStreamKind;
internal StringStreamReader StringStream;
internal BlobStreamReader BlobStream;
internal GuidStreamReader GuidStream;
internal UserStringStreamReader UserStringStream;
/// <summary>
/// True if the metadata stream has minimal delta format. Used for EnC.
/// </summary>
/// <remarks>
/// The metadata stream has minimal delta format if "#JTD" stream is present.
/// Minimal delta format uses large size (4B) when encoding table/heap references.
/// The heaps in minimal delta only contain data of the delta,
/// there is no padding at the beginning of the heaps that would align them
/// with the original full metadata heaps.
/// </remarks>
internal bool IsMinimalDelta;
/// <summary>
/// Looks like this function reads beginning of the header described in
/// Ecma-335 24.2.1 Metadata root
/// </summary>
private void ReadMetadataHeader(ref BlobReader memReader)
{
if (memReader.RemainingBytes < COR20Constants.MinimumSizeofMetadataHeader)
{
throw new BadImageFormatException(MetadataResources.MetadataHeaderTooSmall);
}
this.metadataHeader.Signature = memReader.ReadUInt32();
if (this.metadataHeader.Signature != COR20Constants.COR20MetadataSignature)
{
throw new BadImageFormatException(MetadataResources.MetadataSignature);
}
this.metadataHeader.MajorVersion = memReader.ReadUInt16();
this.metadataHeader.MinorVersion = memReader.ReadUInt16();
this.metadataHeader.ExtraData = memReader.ReadUInt32();
this.metadataHeader.VersionStringSize = memReader.ReadInt32();
if (memReader.RemainingBytes < this.metadataHeader.VersionStringSize)
{
throw new BadImageFormatException(MetadataResources.NotEnoughSpaceForVersionString);
}
int numberOfBytesRead;
this.metadataHeader.VersionString = memReader.GetMemoryBlockAt(0, this.metadataHeader.VersionStringSize).PeekUtf8NullTerminated(0, null, utf8Decoder, out numberOfBytesRead, '\0');
memReader.SkipBytes(this.metadataHeader.VersionStringSize);
this.metadataKind = GetMetadataKind(metadataHeader.VersionString);
}
private MetadataKind GetMetadataKind(string versionString)
{
// Treat metadata as CLI raw metadata if the client doesn't want to see projections.
if ((options & MetadataReaderOptions.ApplyWindowsRuntimeProjections) == 0)
{
return MetadataKind.Ecma335;
}
if (!versionString.Contains("WindowsRuntime"))
{
return MetadataKind.Ecma335;
}
else if (versionString.Contains("CLR"))
{
return MetadataKind.ManagedWindowsMetadata;
}
else
{
return MetadataKind.WindowsMetadata;
}
}
/// <summary>
/// Reads stream headers described in Ecma-335 24.2.2 Stream header
/// </summary>
private StreamHeader[] ReadStreamHeaders(ref BlobReader memReader)
{
// storage header:
memReader.ReadUInt16();
int streamCount = memReader.ReadInt16();
var streamHeaders = new StreamHeader[streamCount];
for (int i = 0; i < streamHeaders.Length; i++)
{
if (memReader.RemainingBytes < COR20Constants.MinimumSizeofStreamHeader)
{
throw new BadImageFormatException(MetadataResources.StreamHeaderTooSmall);
}
streamHeaders[i].Offset = memReader.ReadUInt32();
streamHeaders[i].Size = memReader.ReadInt32();
streamHeaders[i].Name = memReader.ReadUtf8NullTerminated();
bool aligned = memReader.TryAlign(4);
if (!aligned || memReader.RemainingBytes == 0)
{
throw new BadImageFormatException(MetadataResources.NotEnoughSpaceForStreamHeaderName);
}
}
return streamHeaders;
}
private void InitializeStreamReaders(ref MemoryBlock metadataRoot, StreamHeader[] streamHeaders, out MemoryBlock metadataTableStream)
{
metadataTableStream = default(MemoryBlock);
foreach (StreamHeader streamHeader in streamHeaders)
{
switch (streamHeader.Name)
{
case COR20Constants.StringStreamName:
if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size)
{
throw new BadImageFormatException(MetadataResources.NotEnoughSpaceForStringStream);
}
this.StringStream = new StringStreamReader(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size), this.metadataKind);
break;
case COR20Constants.BlobStreamName:
if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size)
{
throw new BadImageFormatException(MetadataResources.NotEnoughSpaceForBlobStream);
}
this.BlobStream = new BlobStreamReader(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size), this.metadataKind);
break;
case COR20Constants.GUIDStreamName:
if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size)
{
throw new BadImageFormatException(MetadataResources.NotEnoughSpaceForGUIDStream);
}
this.GuidStream = new GuidStreamReader(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size));
break;
case COR20Constants.UserStringStreamName:
if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size)
{
throw new BadImageFormatException(MetadataResources.NotEnoughSpaceForBlobStream);
}
this.UserStringStream = new UserStringStreamReader(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size));
break;
case COR20Constants.CompressedMetadataTableStreamName:
if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size)
{
throw new BadImageFormatException(MetadataResources.NotEnoughSpaceForMetadataStream);
}
this.metadataStreamKind = MetadataStreamKind.Compressed;
metadataTableStream = metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size);
break;
case COR20Constants.UncompressedMetadataTableStreamName:
if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size)
{
throw new BadImageFormatException(MetadataResources.NotEnoughSpaceForMetadataStream);
}
this.metadataStreamKind = MetadataStreamKind.Uncompressed;
metadataTableStream = metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size);
break;
case COR20Constants.MinimalDeltaMetadataTableStreamName:
if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size)
{
throw new BadImageFormatException(MetadataResources.NotEnoughSpaceForMetadataStream);
}
// the content of the stream is ignored
this.IsMinimalDelta = true;
break;
default:
// Skip unknown streams. Some obfuscators insert invalid streams.
continue;
}
}
if (IsMinimalDelta && metadataStreamKind != MetadataStreamKind.Uncompressed)
{
throw new BadImageFormatException(MetadataResources.InvalidMetadataStreamFormat);
}
}
#endregion
#region Tables and Heaps
private MetadataTableHeader MetadataTableHeader;
/// <summary>
/// A row count for each possible table. May be indexed by <see cref="TableIndex"/>.
/// </summary>
internal uint[] TableRowCounts;
internal ModuleTableReader ModuleTable;
internal TypeRefTableReader TypeRefTable;
internal TypeDefTableReader TypeDefTable;
internal FieldPtrTableReader FieldPtrTable;
internal FieldTableReader FieldTable;
internal MethodPtrTableReader MethodPtrTable;
internal MethodTableReader MethodDefTable;
internal ParamPtrTableReader ParamPtrTable;
internal ParamTableReader ParamTable;
internal InterfaceImplTableReader InterfaceImplTable;
internal MemberRefTableReader MemberRefTable;
internal ConstantTableReader ConstantTable;
internal CustomAttributeTableReader CustomAttributeTable;
internal FieldMarshalTableReader FieldMarshalTable;
internal DeclSecurityTableReader DeclSecurityTable;
internal ClassLayoutTableReader ClassLayoutTable;
internal FieldLayoutTableReader FieldLayoutTable;
internal StandAloneSigTableReader StandAloneSigTable;
internal EventMapTableReader EventMapTable;
internal EventPtrTableReader EventPtrTable;
internal EventTableReader EventTable;
internal PropertyMapTableReader PropertyMapTable;
internal PropertyPtrTableReader PropertyPtrTable;
internal PropertyTableReader PropertyTable;
internal MethodSemanticsTableReader MethodSemanticsTable;
internal MethodImplTableReader MethodImplTable;
internal ModuleRefTableReader ModuleRefTable;
internal TypeSpecTableReader TypeSpecTable;
internal ImplMapTableReader ImplMapTable;
internal FieldRVATableReader FieldRvaTable;
internal EnCLogTableReader EncLogTable;
internal EnCMapTableReader EncMapTable;
internal AssemblyTableReader AssemblyTable;
internal AssemblyProcessorTableReader AssemblyProcessorTable; // unused
internal AssemblyOSTableReader AssemblyOSTable; // unused
internal AssemblyRefTableReader AssemblyRefTable;
internal AssemblyRefProcessorTableReader AssemblyRefProcessorTable; // unused
internal AssemblyRefOSTableReader AssemblyRefOSTable; // unused
internal FileTableReader FileTable;
internal ExportedTypeTableReader ExportedTypeTable;
internal ManifestResourceTableReader ManifestResourceTable;
internal NestedClassTableReader NestedClassTable;
internal GenericParamTableReader GenericParamTable;
internal MethodSpecTableReader MethodSpecTable;
internal GenericParamConstraintTableReader GenericParamConstraintTable;
private void ReadMetadataTableHeader(ref BlobReader memReader, out uint[] metadataTableRowCounts)
{
if (memReader.RemainingBytes < MetadataStreamConstants.SizeOfMetadataTableHeader)
{
throw new BadImageFormatException(MetadataResources.MetadataTableHeaderTooSmall);
}
this.MetadataTableHeader.Reserved = memReader.ReadUInt32();
this.MetadataTableHeader.MajorVersion = memReader.ReadByte();
this.MetadataTableHeader.MinorVersion = memReader.ReadByte();
this.MetadataTableHeader.HeapSizeFlags = (HeapSizeFlag)memReader.ReadByte();
this.MetadataTableHeader.RowId = memReader.ReadByte();
this.MetadataTableHeader.ValidTables = (TableMask)memReader.ReadUInt64();
this.MetadataTableHeader.SortedTables = (TableMask)memReader.ReadUInt64();
ulong presentTables = (ulong)this.MetadataTableHeader.ValidTables;
// According to ECMA-335, MajorVersion and MinorVersion have fixed values and,
// based on recommendation in 24.1 Fixed fields: When writing these fields it
// is best that they be set to the value indicated, on reading they should be ignored.?
// we will not be checking version values. We will continue checking that the set of
// present tables is within the set we understand.
ulong validTables = (ulong)TableMask.V2_0_TablesMask;
if ((presentTables & ~validTables) != 0)
{
throw new BadImageFormatException(string.Format(MetadataResources.UnknownTables, presentTables));
}
if (this.metadataStreamKind == MetadataStreamKind.Compressed)
{
// In general Ptr tables and EnC tables are not allowed in a compressed stream.
// However when asked for a snapshot of the current metadata after an EnC change has been applied
// the CLR includes the EnCLog table into the snapshot. We need to be able to read the image,
// so we'll allow the table here but pretend it's empty later.
if ((presentTables & (ulong)(TableMask.PtrTables | TableMask.EnCMap)) != 0)
{
throw new BadImageFormatException(MetadataResources.IllegalTablesInCompressedMetadataStream);
}
}
int numberOfTables = this.MetadataTableHeader.GetNumberOfTablesPresent();
if (memReader.RemainingBytes < numberOfTables * sizeof(int))
{
throw new BadImageFormatException(MetadataResources.TableRowCountSpaceTooSmall);
}
var rowCounts = new uint[numberOfTables];
for (int i = 0; i < rowCounts.Length; i++)
{
rowCounts[i] = memReader.ReadUInt32();
}
metadataTableRowCounts = rowCounts;
}
private const int SmallIndexSize = 2;
private const int LargeIndexSize = 4;
private void InitializeTableReaders(MemoryBlock metadataTablesMemoryBlock, uint[] compressedRowCounts)
{
// Only sizes of tables present in metadata are recorded in rowCountCompressedArray.
// This array contains a slot for each possible table, not just those that are present in the metadata.
uint[] rowCounts = new uint[TableIndexExtensions.Count];
// Size of reference tags in each table.
int[] referenceSizes = new int[TableIndexExtensions.Count];
ulong validTables = (ulong)this.MetadataTableHeader.ValidTables;
int compressedRowCountIndex = 0;
for (int i = 0; i < TableIndexExtensions.Count; i++)
{
bool fitsSmall;
if ((validTables & 1UL) != 0)
{
uint rowCount = compressedRowCounts[compressedRowCountIndex++];
rowCounts[i] = rowCount;
fitsSmall = rowCount < MetadataStreamConstants.LargeTableRowCount;
}
else
{
fitsSmall = true;
}
referenceSizes[i] = (fitsSmall && !IsMinimalDelta) ? SmallIndexSize : LargeIndexSize;
validTables >>= 1;
}
this.TableRowCounts = rowCounts;
// Compute ref sizes for tables that can have pointer tables for it
int fieldRefSize = referenceSizes[(int)TableIndex.FieldPtr] > SmallIndexSize ? LargeIndexSize : referenceSizes[(int)TableIndex.Field];
int methodRefSize = referenceSizes[(int)TableIndex.MethodPtr] > SmallIndexSize ? LargeIndexSize : referenceSizes[(int)TableIndex.MethodDef];
int paramRefSize = referenceSizes[(int)TableIndex.ParamPtr] > SmallIndexSize ? LargeIndexSize : referenceSizes[(int)TableIndex.Param];
int eventRefSize = referenceSizes[(int)TableIndex.EventPtr] > SmallIndexSize ? LargeIndexSize : referenceSizes[(int)TableIndex.Event];
int propertyRefSize = referenceSizes[(int)TableIndex.PropertyPtr] > SmallIndexSize ? LargeIndexSize : referenceSizes[(int)TableIndex.Property];
// Compute the coded token ref sizes
int typeDefOrRefRefSize = ComputeCodedTokenSize(TypeDefOrRefTag.LargeRowSize, rowCounts, TypeDefOrRefTag.TablesReferenced);
int hasConstantRefSize = ComputeCodedTokenSize(HasConstantTag.LargeRowSize, rowCounts, HasConstantTag.TablesReferenced);
int hasCustomAttributeRefSize = ComputeCodedTokenSize(HasCustomAttributeTag.LargeRowSize, rowCounts, HasCustomAttributeTag.TablesReferenced);
int hasFieldMarshalRefSize = ComputeCodedTokenSize(HasFieldMarshalTag.LargeRowSize, rowCounts, HasFieldMarshalTag.TablesReferenced);
int hasDeclSecurityRefSize = ComputeCodedTokenSize(HasDeclSecurityTag.LargeRowSize, rowCounts, HasDeclSecurityTag.TablesReferenced);
int memberRefParentRefSize = ComputeCodedTokenSize(MemberRefParentTag.LargeRowSize, rowCounts, MemberRefParentTag.TablesReferenced);
int hasSemanticsRefSize = ComputeCodedTokenSize(HasSemanticsTag.LargeRowSize, rowCounts, HasSemanticsTag.TablesReferenced);
int methodDefOrRefRefSize = ComputeCodedTokenSize(MethodDefOrRefTag.LargeRowSize, rowCounts, MethodDefOrRefTag.TablesReferenced);
int memberForwardedRefSize = ComputeCodedTokenSize(MemberForwardedTag.LargeRowSize, rowCounts, MemberForwardedTag.TablesReferenced);
int implementationRefSize = ComputeCodedTokenSize(ImplementationTag.LargeRowSize, rowCounts, ImplementationTag.TablesReferenced);
int customAttributeTypeRefSize = ComputeCodedTokenSize(CustomAttributeTypeTag.LargeRowSize, rowCounts, CustomAttributeTypeTag.TablesReferenced);
int resolutionScopeRefSize = ComputeCodedTokenSize(ResolutionScopeTag.LargeRowSize, rowCounts, ResolutionScopeTag.TablesReferenced);
int typeOrMethodDefRefSize = ComputeCodedTokenSize(TypeOrMethodDefTag.LargeRowSize, rowCounts, TypeOrMethodDefTag.TablesReferenced);
// Compute HeapRef Sizes
int stringHeapRefSize = (this.MetadataTableHeader.HeapSizeFlags & HeapSizeFlag.StringHeapLarge) == HeapSizeFlag.StringHeapLarge ? LargeIndexSize : SmallIndexSize;
int guidHeapRefSize = (this.MetadataTableHeader.HeapSizeFlags & HeapSizeFlag.GuidHeapLarge) == HeapSizeFlag.GuidHeapLarge ? LargeIndexSize : SmallIndexSize;
int blobHeapRefSize = (this.MetadataTableHeader.HeapSizeFlags & HeapSizeFlag.BlobHeapLarge) == HeapSizeFlag.BlobHeapLarge ? LargeIndexSize : SmallIndexSize;
// Populate the Table blocks
int totalRequiredSize = 0;
this.ModuleTable = new ModuleTableReader(rowCounts[(int)TableIndex.Module], stringHeapRefSize, guidHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ModuleTable.Block.Length;
this.TypeRefTable = new TypeRefTableReader(rowCounts[(int)TableIndex.TypeRef], resolutionScopeRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.TypeRefTable.Block.Length;
this.TypeDefTable = new TypeDefTableReader(rowCounts[(int)TableIndex.TypeDef], fieldRefSize, methodRefSize, typeDefOrRefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.TypeDefTable.Block.Length;
this.FieldPtrTable = new FieldPtrTableReader(rowCounts[(int)TableIndex.FieldPtr], referenceSizes[(int)TableIndex.Field], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.FieldPtrTable.Block.Length;
this.FieldTable = new FieldTableReader(rowCounts[(int)TableIndex.Field], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.FieldTable.Block.Length;
this.MethodPtrTable = new MethodPtrTableReader(rowCounts[(int)TableIndex.MethodPtr], referenceSizes[(int)TableIndex.MethodDef], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.MethodPtrTable.Block.Length;
this.MethodDefTable = new MethodTableReader(rowCounts[(int)TableIndex.MethodDef], paramRefSize, stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.MethodDefTable.Block.Length;
this.ParamPtrTable = new ParamPtrTableReader(rowCounts[(int)TableIndex.ParamPtr], referenceSizes[(int)TableIndex.Param], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ParamPtrTable.Block.Length;
this.ParamTable = new ParamTableReader(rowCounts[(int)TableIndex.Param], stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ParamTable.Block.Length;
this.InterfaceImplTable = new InterfaceImplTableReader(rowCounts[(int)TableIndex.InterfaceImpl], IsDeclaredSorted(TableMask.InterfaceImpl), referenceSizes[(int)TableIndex.TypeDef], typeDefOrRefRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.InterfaceImplTable.Block.Length;
this.MemberRefTable = new MemberRefTableReader(rowCounts[(int)TableIndex.MemberRef], memberRefParentRefSize, stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.MemberRefTable.Block.Length;
this.ConstantTable = new ConstantTableReader(rowCounts[(int)TableIndex.Constant], IsDeclaredSorted(TableMask.Constant), hasConstantRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ConstantTable.Block.Length;
this.CustomAttributeTable = new CustomAttributeTableReader(rowCounts[(int)TableIndex.CustomAttribute],
IsDeclaredSorted(TableMask.CustomAttribute),
hasCustomAttributeRefSize,
customAttributeTypeRefSize,
blobHeapRefSize,
metadataTablesMemoryBlock,
totalRequiredSize);
totalRequiredSize += this.CustomAttributeTable.Block.Length;
this.FieldMarshalTable = new FieldMarshalTableReader(rowCounts[(int)TableIndex.FieldMarshal], IsDeclaredSorted(TableMask.FieldMarshal), hasFieldMarshalRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.FieldMarshalTable.Block.Length;
this.DeclSecurityTable = new DeclSecurityTableReader(rowCounts[(int)TableIndex.DeclSecurity], IsDeclaredSorted(TableMask.DeclSecurity), hasDeclSecurityRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.DeclSecurityTable.Block.Length;
this.ClassLayoutTable = new ClassLayoutTableReader(rowCounts[(int)TableIndex.ClassLayout], IsDeclaredSorted(TableMask.ClassLayout), referenceSizes[(int)TableIndex.TypeDef], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ClassLayoutTable.Block.Length;
this.FieldLayoutTable = new FieldLayoutTableReader(rowCounts[(int)TableIndex.FieldLayout], IsDeclaredSorted(TableMask.FieldLayout), referenceSizes[(int)TableIndex.Field], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.FieldLayoutTable.Block.Length;
this.StandAloneSigTable = new StandAloneSigTableReader(rowCounts[(int)TableIndex.StandAloneSig], blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.StandAloneSigTable.Block.Length;
this.EventMapTable = new EventMapTableReader(rowCounts[(int)TableIndex.EventMap], referenceSizes[(int)TableIndex.TypeDef], eventRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.EventMapTable.Block.Length;
this.EventPtrTable = new EventPtrTableReader(rowCounts[(int)TableIndex.EventPtr], referenceSizes[(int)TableIndex.Event], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.EventPtrTable.Block.Length;
this.EventTable = new EventTableReader(rowCounts[(int)TableIndex.Event], typeDefOrRefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.EventTable.Block.Length;
this.PropertyMapTable = new PropertyMapTableReader(rowCounts[(int)TableIndex.PropertyMap], referenceSizes[(int)TableIndex.TypeDef], propertyRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.PropertyMapTable.Block.Length;
this.PropertyPtrTable = new PropertyPtrTableReader(rowCounts[(int)TableIndex.PropertyPtr], referenceSizes[(int)TableIndex.Property], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.PropertyPtrTable.Block.Length;
this.PropertyTable = new PropertyTableReader(rowCounts[(int)TableIndex.Property], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.PropertyTable.Block.Length;
this.MethodSemanticsTable = new MethodSemanticsTableReader(rowCounts[(int)TableIndex.MethodSemantics], IsDeclaredSorted(TableMask.MethodSemantics), referenceSizes[(int)TableIndex.MethodDef], hasSemanticsRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.MethodSemanticsTable.Block.Length;
this.MethodImplTable = new MethodImplTableReader(rowCounts[(int)TableIndex.MethodImpl], IsDeclaredSorted(TableMask.MethodImpl), referenceSizes[(int)TableIndex.TypeDef], methodDefOrRefRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.MethodImplTable.Block.Length;
this.ModuleRefTable = new ModuleRefTableReader(rowCounts[(int)TableIndex.ModuleRef], stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ModuleRefTable.Block.Length;
this.TypeSpecTable = new TypeSpecTableReader(rowCounts[(int)TableIndex.TypeSpec], blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.TypeSpecTable.Block.Length;
this.ImplMapTable = new ImplMapTableReader(rowCounts[(int)TableIndex.ImplMap], IsDeclaredSorted(TableMask.ImplMap), referenceSizes[(int)TableIndex.ModuleRef], memberForwardedRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ImplMapTable.Block.Length;
this.FieldRvaTable = new FieldRVATableReader(rowCounts[(int)TableIndex.FieldRva], IsDeclaredSorted(TableMask.FieldRva), referenceSizes[(int)TableIndex.Field], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.FieldRvaTable.Block.Length;
this.EncLogTable = new EnCLogTableReader(rowCounts[(int)TableIndex.EncLog], metadataTablesMemoryBlock, totalRequiredSize, this.metadataStreamKind);
totalRequiredSize += this.EncLogTable.Block.Length;
this.EncMapTable = new EnCMapTableReader(rowCounts[(int)TableIndex.EncMap], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.EncMapTable.Block.Length;
this.AssemblyTable = new AssemblyTableReader(rowCounts[(int)TableIndex.Assembly], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.AssemblyTable.Block.Length;
this.AssemblyProcessorTable = new AssemblyProcessorTableReader(rowCounts[(int)TableIndex.AssemblyProcessor], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.AssemblyProcessorTable.Block.Length;
this.AssemblyOSTable = new AssemblyOSTableReader(rowCounts[(int)TableIndex.AssemblyOS], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.AssemblyOSTable.Block.Length;
this.AssemblyRefTable = new AssemblyRefTableReader((int)rowCounts[(int)TableIndex.AssemblyRef], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize, this.metadataKind);
totalRequiredSize += this.AssemblyRefTable.Block.Length;
this.AssemblyRefProcessorTable = new AssemblyRefProcessorTableReader(rowCounts[(int)TableIndex.AssemblyRefProcessor], referenceSizes[(int)TableIndex.AssemblyRef], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.AssemblyRefProcessorTable.Block.Length;
this.AssemblyRefOSTable = new AssemblyRefOSTableReader(rowCounts[(int)TableIndex.AssemblyRefOS], referenceSizes[(int)TableIndex.AssemblyRef], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.AssemblyRefOSTable.Block.Length;
this.FileTable = new FileTableReader(rowCounts[(int)TableIndex.File], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.FileTable.Block.Length;
this.ExportedTypeTable = new ExportedTypeTableReader(rowCounts[(int)TableIndex.ExportedType], implementationRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ExportedTypeTable.Block.Length;
this.ManifestResourceTable = new ManifestResourceTableReader(rowCounts[(int)TableIndex.ManifestResource], implementationRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ManifestResourceTable.Block.Length;
this.NestedClassTable = new NestedClassTableReader(rowCounts[(int)TableIndex.NestedClass], IsDeclaredSorted(TableMask.NestedClass), referenceSizes[(int)TableIndex.TypeDef], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.NestedClassTable.Block.Length;
this.GenericParamTable = new GenericParamTableReader(rowCounts[(int)TableIndex.GenericParam], IsDeclaredSorted(TableMask.GenericParam), typeOrMethodDefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.GenericParamTable.Block.Length;
this.MethodSpecTable = new MethodSpecTableReader(rowCounts[(int)TableIndex.MethodSpec], methodDefOrRefRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.MethodSpecTable.Block.Length;
this.GenericParamConstraintTable = new GenericParamConstraintTableReader(rowCounts[(int)TableIndex.GenericParamConstraint], IsDeclaredSorted(TableMask.GenericParamConstraint), referenceSizes[(int)TableIndex.GenericParam], typeDefOrRefRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.GenericParamConstraintTable.Block.Length;
if (totalRequiredSize > metadataTablesMemoryBlock.Length)
{
throw new BadImageFormatException(MetadataResources.MetadataTablesTooSmall);
}
}
private int ComputeCodedTokenSize(uint largeRowSize, uint[] rowCountArray, TableMask tablesReferenced)
{
if (IsMinimalDelta)
{
return LargeIndexSize;
}
bool isAllReferencedTablesSmall = true;
ulong tablesReferencedMask = (ulong)tablesReferenced;
for (int tableIndex = 0; tableIndex < TableIndexExtensions.Count; tableIndex++)
{
if ((tablesReferencedMask & 1UL) != 0)
{
isAllReferencedTablesSmall = isAllReferencedTablesSmall && (rowCountArray[tableIndex] < largeRowSize);
}
tablesReferencedMask >>= 1;
}
return isAllReferencedTablesSmall ? SmallIndexSize : LargeIndexSize;
}
private bool IsDeclaredSorted(TableMask index)
{
return (this.MetadataTableHeader.SortedTables & index) != 0;
}
#endregion
#region Helpers
// internal for testing
internal NamespaceCache NamespaceCache
{
get { return namespaceCache; }
}
internal bool UseFieldPtrTable
{
get { return this.FieldPtrTable.NumberOfRows > 0; }
}
internal bool UseMethodPtrTable
{
get { return this.MethodPtrTable.NumberOfRows > 0; }
}
internal bool UseParamPtrTable
{
get { return this.ParamPtrTable.NumberOfRows > 0; }
}
internal bool UseEventPtrTable
{
get { return this.EventPtrTable.NumberOfRows > 0; }
}
internal bool UsePropertyPtrTable
{
get { return this.PropertyPtrTable.NumberOfRows > 0; }
}
internal void GetFieldRange(TypeDefinitionHandle typeDef, out int firstFieldRowId, out int lastFieldRowId)
{
uint typeDefRowId = typeDef.RowId;
firstFieldRowId = (int)this.TypeDefTable.GetFieldStart(typeDefRowId);
if (firstFieldRowId == 0)
{
firstFieldRowId = 1;
lastFieldRowId = 0;
}
else if (typeDefRowId == this.TypeDefTable.NumberOfRows)
{
lastFieldRowId = (int)(this.UseFieldPtrTable ? this.FieldPtrTable.NumberOfRows : this.FieldTable.NumberOfRows);
}
else
{
lastFieldRowId = (int)this.TypeDefTable.GetFieldStart(typeDefRowId + 1) - 1;
}
}
internal void GetMethodRange(TypeDefinitionHandle typeDef, out int firstMethodRowId, out int lastMethodRowId)
{
uint typeDefRowId = typeDef.RowId;
firstMethodRowId = (int)this.TypeDefTable.GetMethodStart(typeDefRowId);
if (firstMethodRowId == 0)
{
firstMethodRowId = 1;
lastMethodRowId = 0;
}
else if (typeDefRowId == this.TypeDefTable.NumberOfRows)
{
lastMethodRowId = (int)(this.UseMethodPtrTable ? this.MethodPtrTable.NumberOfRows : this.MethodDefTable.NumberOfRows);
}
else
{
lastMethodRowId = (int)this.TypeDefTable.GetMethodStart(typeDefRowId + 1) - 1;
}
}
internal void GetEventRange(TypeDefinitionHandle typeDef, out int firstEventRowId, out int lastEventRowId)
{
uint eventMapRowId = this.EventMapTable.FindEventMapRowIdFor(typeDef);
if (eventMapRowId == 0)
{
firstEventRowId = 1;
lastEventRowId = 0;
return;
}
firstEventRowId = (int)this.EventMapTable.GetEventListStartFor(eventMapRowId);
if (eventMapRowId == this.EventMapTable.NumberOfRows)
{
lastEventRowId = (int)(this.UseEventPtrTable ? this.EventPtrTable.NumberOfRows : this.EventTable.NumberOfRows);
}
else
{
lastEventRowId = (int)this.EventMapTable.GetEventListStartFor(eventMapRowId + 1) - 1;
}
}
internal void GetPropertyRange(TypeDefinitionHandle typeDef, out int firstPropertyRowId, out int lastPropertyRowId)
{
uint propertyMapRowId = this.PropertyMapTable.FindPropertyMapRowIdFor(typeDef);
if (propertyMapRowId == 0)
{
firstPropertyRowId = 1;
lastPropertyRowId = 0;
return;
}
firstPropertyRowId = (int)this.PropertyMapTable.GetPropertyListStartFor(propertyMapRowId);
if (propertyMapRowId == this.PropertyMapTable.NumberOfRows)
{
lastPropertyRowId = (int)(this.UsePropertyPtrTable ? this.PropertyPtrTable.NumberOfRows : this.PropertyTable.NumberOfRows);
}
else
{
lastPropertyRowId = (int)this.PropertyMapTable.GetPropertyListStartFor(propertyMapRowId + 1) - 1;
}
}
internal void GetParameterRange(MethodDefinitionHandle methodDef, out int firstParamRowId, out int lastParamRowId)
{
uint rid = methodDef.RowId;
firstParamRowId = (int)this.MethodDefTable.GetParamStart(rid);
if (firstParamRowId == 0)
{
firstParamRowId = 1;
lastParamRowId = 0;
}
else if (rid == this.MethodDefTable.NumberOfRows)
{
lastParamRowId = (int)(this.UseParamPtrTable ? this.ParamPtrTable.NumberOfRows : this.ParamTable.NumberOfRows);
}
else
{
lastParamRowId = (int)this.MethodDefTable.GetParamStart(rid + 1) - 1;
}
}
// TODO: move throw helpers to common place.
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowValueArgumentNull()
{
throw new ArgumentNullException("value");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ThrowTableNotSorted(TableIndex tableIndex)
{
throw new BadImageFormatException(string.Format(MetadataResources.MetadataTableNotSorted, (int)tableIndex));
}
#endregion
#region Public APIs
public MetadataReaderOptions Options
{
get { return this.options; }
}
public string MetadataVersion
{
get { return metadataHeader.VersionString; }
}
public MetadataKind MetadataKind
{
get { return metadataKind; }
}
public MetadataStringComparer StringComparer
{
get { return new MetadataStringComparer(this); }
}
public bool IsAssembly
{
get { return this.AssemblyTable.NumberOfRows == 1; }
}
public AssemblyReferenceHandleCollection AssemblyReferences
{
get { return new AssemblyReferenceHandleCollection(this); }
}
public TypeDefinitionHandleCollection TypeDefinitions
{
get { return new TypeDefinitionHandleCollection((int)TypeDefTable.NumberOfRows); }
}
public TypeReferenceHandleCollection TypeReferences
{
get { return new TypeReferenceHandleCollection((int)TypeRefTable.NumberOfRows); }
}
public CustomAttributeHandleCollection CustomAttributes
{
get { return new CustomAttributeHandleCollection(this); }
}
public DeclarativeSecurityAttributeHandleCollection DeclarativeSecurityAttributes
{
get { return new DeclarativeSecurityAttributeHandleCollection(this); }
}
public MemberReferenceHandleCollection MemberReferences
{
get { return new MemberReferenceHandleCollection((int)MemberRefTable.NumberOfRows); }
}
public ManifestResourceHandleCollection ManifestResources
{
get { return new ManifestResourceHandleCollection((int)ManifestResourceTable.NumberOfRows); }
}
public AssemblyFileHandleCollection AssemblyFiles
{
get { return new AssemblyFileHandleCollection((int)FileTable.NumberOfRows); }
}
public ExportedTypeHandleCollection ExportedTypes
{
get { return new ExportedTypeHandleCollection((int)ExportedTypeTable.NumberOfRows); }
}
public MethodDefinitionHandleCollection MethodDefinitions
{
get { return new MethodDefinitionHandleCollection(this); }
}
public FieldDefinitionHandleCollection FieldDefinitions
{
get { return new FieldDefinitionHandleCollection(this); }
}
public EventDefinitionHandleCollection EventDefinitions
{
get { return new EventDefinitionHandleCollection(this); }
}
public PropertyDefinitionHandleCollection PropertyDefinitions
{
get { return new PropertyDefinitionHandleCollection(this); }
}
public AssemblyDefinition GetAssemblyDefinition()
{
if (!IsAssembly)
{
throw new InvalidOperationException(MetadataResources.MetadataImageDoesNotRepresentAnAssembly);
}
return new AssemblyDefinition(this);
}
public string GetString(StringHandle handle)
{
return StringStream.GetString(handle, utf8Decoder);
}
public string GetString(NamespaceDefinitionHandle handle)
{
if (handle.HasFullName)
{
return StringStream.GetString(handle.GetFullName(), utf8Decoder);
}
return namespaceCache.GetFullName(handle);
}
public byte[] GetBlobBytes(BlobHandle handle)
{
return BlobStream.GetBytes(handle);
}
public ImmutableArray<byte> GetBlobContent(BlobHandle handle)
{
// TODO: We can skip a copy for virtual blobs.
byte[] bytes = GetBlobBytes(handle);
return ImmutableArrayInterop.DangerousCreateFromUnderlyingArray(ref bytes);
}
public BlobReader GetBlobReader(BlobHandle handle)
{
return BlobStream.GetBlobReader(handle);
}
public string GetUserString(UserStringHandle handle)
{
return UserStringStream.GetString(handle);
}
public Guid GetGuid(GuidHandle handle)
{
return GuidStream.GetGuid(handle);
}
public ModuleDefinition GetModuleDefinition()
{
return new ModuleDefinition(this);
}
public AssemblyReference GetAssemblyReference(AssemblyReferenceHandle handle)
{
return new AssemblyReference(this, handle.Token & TokenTypeIds.VirtualBitAndRowIdMask);
}
public TypeDefinition GetTypeDefinition(TypeDefinitionHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
return new TypeDefinition(this, GetTypeDefTreatmentAndRowId(handle));
}
public NamespaceDefinition GetNamespaceDefinitionRoot()
{
NamespaceData data = namespaceCache.GetRootNamespace();
return new NamespaceDefinition(data);
}
public NamespaceDefinition GetNamespaceDefinition(NamespaceDefinitionHandle handle)
{
NamespaceData data = namespaceCache.GetNamespaceData(handle);
return new NamespaceDefinition(data);
}
private uint GetTypeDefTreatmentAndRowId(TypeDefinitionHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
if (this.metadataKind == MetadataKind.Ecma335)
{
return handle.RowId;
}
return CalculateTypeDefTreatmentAndRowId(handle);
}
public TypeReference GetTypeReference(TypeReferenceHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
return new TypeReference(this, GetTypeRefTreatmentAndRowId(handle));
}
private uint GetTypeRefTreatmentAndRowId(TypeReferenceHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
if (this.metadataKind == MetadataKind.Ecma335)
{
return handle.RowId;
}
return CalculateTypeRefTreatmentAndRowId(handle);
}
public ExportedType GetExportedType(ExportedTypeHandle handle)
{
return new ExportedType(this, handle.RowId);
}
public CustomAttributeHandleCollection GetCustomAttributes(Handle handle)
{
Debug.Assert(!handle.IsNil);
return new CustomAttributeHandleCollection(this, handle);
}
public CustomAttribute GetCustomAttribute(CustomAttributeHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
return new CustomAttribute(this, GetCustomAttributeTreatmentAndRowId(handle));
}
private uint GetCustomAttributeTreatmentAndRowId(CustomAttributeHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
if (this.metadataKind == MetadataKind.Ecma335)
{
return handle.RowId;
}
return TreatmentAndRowId((byte)CustomAttributeTreatment.WinMD, handle.RowId);
}
public DeclarativeSecurityAttribute GetDeclarativeSecurityAttribute(DeclarativeSecurityAttributeHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
return new DeclarativeSecurityAttribute(this, handle.RowId);
}
public Constant GetConstant(ConstantHandle handle)
{
return new Constant(this, handle.RowId);
}
public MethodDefinition GetMethodDefinition(MethodDefinitionHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
return new MethodDefinition(this, GetMethodDefTreatmentAndRowId(handle));
}
private uint GetMethodDefTreatmentAndRowId(MethodDefinitionHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
if (this.metadataKind == MetadataKind.Ecma335)
{
return handle.RowId;
}
return CalculateMethodDefTreatmentAndRowId(handle);
}
public FieldDefinition GetFieldDefinition(FieldDefinitionHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
return new FieldDefinition(this, GetFieldDefTreatmentAndRowId(handle));
}
private uint GetFieldDefTreatmentAndRowId(FieldDefinitionHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
if (this.metadataKind == MetadataKind.Ecma335)
{
return handle.RowId;
}
return CalculateFieldDefTreatmentAndRowId(handle);
}
public PropertyDefinition GetPropertyDefinition(PropertyDefinitionHandle handle)
{
return new PropertyDefinition(this, handle);
}
public EventDefinition GetEventDefinition(EventDefinitionHandle handle)
{
return new EventDefinition(this, handle);
}
public MethodImplementation GetMethodImplementation(MethodImplementationHandle handle)
{
return new MethodImplementation(this, handle);
}
public MemberReference GetMemberReference(MemberReferenceHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
return new MemberReference(this, GetMemberRefTreatmentAndRowId(handle));
}
private uint GetMemberRefTreatmentAndRowId(MemberReferenceHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
if (this.metadataKind == MetadataKind.Ecma335)
{
return handle.RowId;
}
return CalculateMemberRefTreatmentAndRowId(handle);
}
public MethodSpecification GetMethodSpecification(MethodSpecificationHandle handle)
{
return new MethodSpecification(this, handle);
}
public Parameter GetParameter(ParameterHandle handle)
{
return new Parameter(this, handle);
}
public GenericParameter GetGenericParameter(GenericParameterHandle handle)
{
return new GenericParameter(this, handle);
}
public GenericParameterConstraint GetGenericParameterConstraint(GenericParameterConstraintHandle handle)
{
return new GenericParameterConstraint(this, handle);
}
public ManifestResource GetManifestResource(ManifestResourceHandle handle)
{
return new ManifestResource(this, handle);
}
public AssemblyFile GetAssemblyFile(AssemblyFileHandle handle)
{
return new AssemblyFile(this, handle);
}
public StandaloneSignature GetStandaloneSignature(StandaloneSignatureHandle handle)
{
return new StandaloneSignature(this, handle);
}
public TypeSpecification GetTypeSpecification(TypeSpecificationHandle handle)
{
return new TypeSpecification(this, handle);
}
public ModuleReference GetModuleReference(ModuleReferenceHandle handle)
{
return new ModuleReference(this, handle);
}
public InterfaceImplementation GetInterfaceImplementation(InterfaceImplementationHandle handle)
{
return new InterfaceImplementation(this, handle);
}
internal TypeDefinitionHandle GetDeclaringType(MethodDefinitionHandle methodDef)
{
uint methodRowId;
if (UseMethodPtrTable)
{
methodRowId = MethodPtrTable.GetRowIdForMethodDefRow(methodDef.RowId);
}
else
{
methodRowId = methodDef.RowId;
}
return TypeDefTable.FindTypeContainingMethod(methodRowId, (int)MethodDefTable.NumberOfRows);
}
internal TypeDefinitionHandle GetDeclaringType(FieldDefinitionHandle fieldDef)
{
uint fieldRowId;
if (UseFieldPtrTable)
{
fieldRowId = FieldPtrTable.GetRowIdForFieldDefRow(fieldDef.RowId);
}
else
{
fieldRowId = fieldDef.RowId;
}
return TypeDefTable.FindTypeContainingField(fieldRowId, (int)FieldTable.NumberOfRows);
}
#endregion
#region Nested Types
private void InitializeNestedTypesMap()
{
var groupedNestedTypes = new Dictionary<TypeDefinitionHandle, ImmutableArray<TypeDefinitionHandle>.Builder>();
uint numberOfNestedTypes = NestedClassTable.NumberOfRows;
ImmutableArray<TypeDefinitionHandle>.Builder builder = null;
TypeDefinitionHandle previousEnclosingClass = default(TypeDefinitionHandle);
for (uint i = 1; i <= numberOfNestedTypes; i++)
{
TypeDefinitionHandle enclosingClass = NestedClassTable.GetEnclosingClass(i);
Debug.Assert(!enclosingClass.IsNil);
if (enclosingClass != previousEnclosingClass)
{
if (!groupedNestedTypes.TryGetValue(enclosingClass, out builder))
{
builder = ImmutableArray.CreateBuilder<TypeDefinitionHandle>();
groupedNestedTypes.Add(enclosingClass, builder);
}
previousEnclosingClass = enclosingClass;
}
else
{
Debug.Assert(builder == groupedNestedTypes[enclosingClass]);
}
builder.Add(NestedClassTable.GetNestedClass(i));
}
var nestedTypesMap = new Dictionary<TypeDefinitionHandle, ImmutableArray<TypeDefinitionHandle>>();
foreach (var group in groupedNestedTypes)
{
nestedTypesMap.Add(group.Key, group.Value.ToImmutable());
}
this.lazyNestedTypesMap = nestedTypesMap;
}
/// <summary>
/// Returns an array of types nested in the specified type.
/// </summary>
internal ImmutableArray<TypeDefinitionHandle> GetNestedTypes(TypeDefinitionHandle typeDef)
{
if (this.lazyNestedTypesMap == null)
{
InitializeNestedTypesMap();
}
ImmutableArray<TypeDefinitionHandle> nestedTypes;
if (this.lazyNestedTypesMap.TryGetValue(typeDef, out nestedTypes))
{
return nestedTypes;
}
return ImmutableArray<TypeDefinitionHandle>.Empty;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace RCube
{
/// <summary>
/// Algorithm that makes cube from specified set of sides.
/// </summary>
static class CubeMaker
{
static int[] permSet = { 0, 1, 2, 7, 8, 3, 6, 5, 4 };
static int[] permRotate = { 2, 3, 4, 5, 6, 7, 0, 1, 8 };
public delegate void MakingProgressCallback(int percentage);
public static int[,] Make(int[,] input, MakingProgressCallback callback, out bool moreThanOne)
{
Context c = new Context();
c.callback = callback;
Dictionary<int, int> defined = new Dictionary<int, int>();
c.sides = new List<int[]>[6];
for (int i = 0; i < 6; i++)
{
c.sides[i] = new List<int[]>();
}
for (int i = 0; i < input.GetLength(0); i++)
{
int[] side = new int[9];
for (int j = 0; j < 9; j++)
{
side[permSet[j]] = input[i, j];
}
int sideId = 0;
for (int j = 0; j < 9; j++)
{
sideId = sideId * 9 + side[j];
}
if (defined.ContainsKey(sideId)) continue;
int index = side[8];
c.sides[index].Add(side);
defined.Add(sideId, i);
for (int q = 0; q < 3; q++)
{
int[] newSide = new int[9];
sideId = 0;
for (int j = 0; j < 9; j++)
{
newSide[permRotate[j]] = side[j];
}
side = newSide;
for (int j = 0; j < 9; j++)
{
sideId = sideId * 9 + side[j];
}
if (defined.ContainsKey(sideId)) continue;
c.sides[index].Add(side);
defined.Add(sideId, i);
}
}
c.Rec0();
if (c.solution == null)
{
moreThanOne = false;
return null;
}
else
{
int[,] cube = new int[6, 9];
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 9; j++)
{
cube[i, j] = c.solution[i][j];
}
}
moreThanOne = c.moreThanOne;
return cube;
}
}
private class Context
{
public MakingProgressCallback callback;
public int[][] current = new int[6][];
public int[][] solution = null;
public List<int[]>[] sides;
public bool moreThanOne = false;
public int[] jobParts = new int[3]; // 2,4,3
public void SetPercentage()
{
int p = jobParts[0] * 12 + jobParts[1] * 3 + jobParts[2];
if (callback != null) callback(p * 100 / 24);
}
public void Rec0()
{
for (int i = 0; i < sides[0].Count; i++)
{
current[0] = sides[0][i];
Rec1();
}
}
void Rec1()
{
for (int q = 1; q <= 2; q++)
{
jobParts[0] = q - 1;
for (int i = 0; i < sides[q].Count; i++)
{
current[1] = sides[q][i];
if (current[0][7] == current[1][1] ||
current[0][0] == current[1][0] ||
current[0][6] == current[1][2])
continue;
Rec2(q);
}
}
}
void Rec2(int sel1)
{
for (int q = sel1 + 1; q < 6; q++)
{
jobParts[1] = q - 2;
for (int i = 0; i < sides[q].Count; i++)
{
current[2] = sides[q][i];
if (current[0][1] == current[2][7] ||
current[0][0] == current[2][0] ||
current[0][2] == current[2][6] ||
current[1][7] == current[2][1] ||
current[1][0] == current[2][0] ||
current[1][6] == current[2][2])
continue;
Rec3(sel1, q);
}
}
}
void Rec3(int sel1, int sel2)
{
for (int q = sel1 == 1 ? sel1 + 1 : 1; q < 6; q++)
{
if (q == sel2) continue;
jobParts[2] = q == 1 ? 0 : q - 3;
SetPercentage();
for (int i = 0; i < sides[q].Count; i++)
{
current[3] = sides[q][i];
if (current[1][4] == current[3][6] ||
current[1][5] == current[3][5] ||
current[1][6] == current[3][4] ||
current[2][2] == current[3][4] ||
current[2][3] == current[3][3] ||
current[2][4] == current[3][2])
continue;
Rec4(sel1, sel2, q);
}
if (q == 1) break;
}
}
void Rec4(int sel1, int sel2, int sel3)
{
for (int q = sel1 + 1; q < 6; q++)
{
if (q == sel2 || q == sel3) continue;
for (int i = 0; i < sides[q].Count; i++)
{
current[4] = sides[q][i];
if (current[2][4] == current[4][6] ||
current[2][5] == current[4][5] ||
current[2][6] == current[4][4] ||
current[0][2] == current[4][4] ||
current[0][3] == current[4][3] ||
current[0][4] == current[4][2] ||
current[3][0] == current[4][0] ||
current[3][1] == current[4][7] ||
current[3][2] == current[4][6])
continue;
Rec5(15 - sel1 - sel2 - sel3 - q);
}
}
}
void Rec5(int q)
{
for (int i = 0; i < sides[q].Count; i++)
{
current[5] = sides[q][i];
if (current[0][4] == current[5][6] ||
current[0][5] == current[5][5] ||
current[0][6] == current[5][4] ||
current[1][2] == current[5][4] ||
current[1][3] == current[5][3] ||
current[1][4] == current[5][2] ||
current[4][0] == current[5][0] ||
current[4][1] == current[5][7] ||
current[4][2] == current[5][6] ||
current[3][0] == current[5][0] ||
current[3][7] == current[5][1] ||
current[3][6] == current[5][2]) continue;
Validate();
}
}
void Validate()
{
int[,] sideCube = new int[6, 6];
for (int i = 0; i < 3; i++)
{
sideCube[i, i] = 1;
sideCube[i + 3, i + 3] = 1;
sideCube[current[i][8], current[i + 3][8]] = 1;
sideCube[current[i + 3][8], current[i][8]] = 1;
}
foreach (int[] c in new int[][] {
new int[] {0,7,1,1},
new int[] {0,1,2,7},
new int[] {0,5,5,5},
new int[] {0,3,4,3},
new int[] {3,7,5,1},
new int[] {3,1,4,7},
new int[] {3,5,1,5},
new int[] {3,3,2,3},
new int[] {1,7,2,1},
new int[] {1,3,5,3},
new int[] {4,1,5,7},
new int[] {4,5,2,5}})
{
sideCube[current[c[0]][c[1]], current[c[2]][c[3]]] = 2;
sideCube[current[c[2]][c[3]], current[c[0]][c[1]]] = 2;
}
for (int i = 0; i < 36; i++)
{
if (sideCube[i % 6, i / 6] == 0) return; // invalid
}
List<int[]> conners = new List<int[]>();
conners.Add(new int[] { current[0][0], current[2][0], current[1][0] });
conners.Add(new int[] { current[3][0], current[4][0], current[5][0] });
conners.Add(new int[] { current[0][2], current[4][4], current[2][6] });
conners.Add(new int[] { current[2][2], current[3][4], current[1][6] });
conners.Add(new int[] { current[1][2], current[5][4], current[0][6] });
conners.Add(new int[] { current[4][2], current[0][4], current[5][6] });
conners.Add(new int[] { current[5][2], current[1][4], current[3][6] });
conners.Add(new int[] { current[3][2], current[2][4], current[4][6] });
conners.Add(new int[] { current[0][8], current[2][8], current[1][8] });
conners.Add(new int[] { current[3][8], current[4][8], current[5][8] });
conners.Add(new int[] { current[0][8], current[4][8], current[2][8] });
conners.Add(new int[] { current[2][8], current[3][8], current[1][8] });
conners.Add(new int[] { current[1][8], current[5][8], current[0][8] });
conners.Add(new int[] { current[4][8], current[0][8], current[5][8] });
conners.Add(new int[] { current[5][8], current[1][8], current[3][8] });
conners.Add(new int[] { current[3][8], current[2][8], current[4][8] });
List<int> connersId = new List<int>();
foreach (int[] c in conners)
{
if (c[1] < c[0] && c[1] < c[2])
{
int t = c[1]; c[1] = c[2]; c[2] = c[0]; c[0] = t;
}
else if (c[2] < c[0] && c[2] < c[1])
{
int t = c[2]; c[2] = c[1]; c[1] = c[0]; c[0] = t;
}
connersId.Add(c[0] * 36 + c[1] * 6 + c[2]);
}
connersId.Sort();
for (int i = 0; i < connersId.Count; i += 2)
{
if (connersId[i] != connersId[i + 1])
return;
}
if (solution == null)
solution = (int[][])current.Clone();
else
moreThanOne = true;
}
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the support-2013-04-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.AWSSupport.Model
{
/// <summary>
/// Container for the parameters to the DescribeCases operation.
/// Returns a list of cases that you specify by passing one or more case IDs. In addition,
/// you can filter the cases by date by setting values for the <code>AfterTime</code>
/// and <code>BeforeTime</code> request parameters. You can set values for the <code>IncludeResolvedCases</code>
/// and <code>IncludeCommunications</code> request parameters to control how much information
/// is returned.
///
///
/// <para>
/// Case data is available for 12 months after creation. If a case was created more than
/// 12 months ago, a request for data might cause an error.
/// </para>
///
/// <para>
/// The response returns the following in JSON format:
/// </para>
/// <ol> <li>One or more <a>CaseDetails</a> data types. </li> <li>One or more <code>NextToken</code>
/// values, which specify where to paginate the returned records represented by the <code>CaseDetails</code>
/// objects.</li> </ol>
/// </summary>
public partial class DescribeCasesRequest : AmazonAWSSupportRequest
{
private string _afterTime;
private string _beforeTime;
private List<string> _caseIdList = new List<string>();
private string _displayId;
private bool? _includeCommunications;
private bool? _includeResolvedCases;
private string _language;
private int? _maxResults;
private string _nextToken;
/// <summary>
/// Gets and sets the property AfterTime.
/// <para>
/// The start date for a filtered date search on support case communications. Case communications
/// are available for 12 months after creation.
/// </para>
/// </summary>
public string AfterTime
{
get { return this._afterTime; }
set { this._afterTime = value; }
}
// Check to see if AfterTime property is set
internal bool IsSetAfterTime()
{
return this._afterTime != null;
}
/// <summary>
/// Gets and sets the property BeforeTime.
/// <para>
/// The end date for a filtered date search on support case communications. Case communications
/// are available for 12 months after creation.
/// </para>
/// </summary>
public string BeforeTime
{
get { return this._beforeTime; }
set { this._beforeTime = value; }
}
// Check to see if BeforeTime property is set
internal bool IsSetBeforeTime()
{
return this._beforeTime != null;
}
/// <summary>
/// Gets and sets the property CaseIdList.
/// <para>
/// A list of ID numbers of the support cases you want returned. The maximum number of
/// cases is 100.
/// </para>
/// </summary>
public List<string> CaseIdList
{
get { return this._caseIdList; }
set { this._caseIdList = value; }
}
// Check to see if CaseIdList property is set
internal bool IsSetCaseIdList()
{
return this._caseIdList != null && this._caseIdList.Count > 0;
}
/// <summary>
/// Gets and sets the property DisplayId.
/// <para>
/// The ID displayed for a case in the AWS Support Center user interface.
/// </para>
/// </summary>
public string DisplayId
{
get { return this._displayId; }
set { this._displayId = value; }
}
// Check to see if DisplayId property is set
internal bool IsSetDisplayId()
{
return this._displayId != null;
}
/// <summary>
/// Gets and sets the property IncludeCommunications.
/// <para>
/// Specifies whether communications should be included in the <a>DescribeCases</a> results.
/// The default is <i>true</i>.
/// </para>
/// </summary>
public bool IncludeCommunications
{
get { return this._includeCommunications.GetValueOrDefault(); }
set { this._includeCommunications = value; }
}
// Check to see if IncludeCommunications property is set
internal bool IsSetIncludeCommunications()
{
return this._includeCommunications.HasValue;
}
/// <summary>
/// Gets and sets the property IncludeResolvedCases.
/// <para>
/// Specifies whether resolved support cases should be included in the <a>DescribeCases</a>
/// results. The default is <i>false</i>.
/// </para>
/// </summary>
public bool IncludeResolvedCases
{
get { return this._includeResolvedCases.GetValueOrDefault(); }
set { this._includeResolvedCases = value; }
}
// Check to see if IncludeResolvedCases property is set
internal bool IsSetIncludeResolvedCases()
{
return this._includeResolvedCases.HasValue;
}
/// <summary>
/// Gets and sets the property Language.
/// <para>
/// The ISO 639-1 code for the language in which AWS provides support. AWS Support currently
/// supports English ("en") and Japanese ("ja"). Language parameters must be passed explicitly
/// for operations that take them.
/// </para>
/// </summary>
public string Language
{
get { return this._language; }
set { this._language = value; }
}
// Check to see if Language property is set
internal bool IsSetLanguage()
{
return this._language != null;
}
/// <summary>
/// Gets and sets the property MaxResults.
/// <para>
/// The maximum number of results to return before paginating.
/// </para>
/// </summary>
public int MaxResults
{
get { return this._maxResults.GetValueOrDefault(); }
set { this._maxResults = value; }
}
// Check to see if MaxResults property is set
internal bool IsSetMaxResults()
{
return this._maxResults.HasValue;
}
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// A resumption point for pagination.
/// </para>
/// </summary>
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml.Serialization
{
using System;
using System.Xml;
using System.Globalization;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using System.Collections;
using System.Configuration;
using System.Xml.Serialization.Configuration;
/// <summary>
/// The <see cref="XmlCustomFormatter"/> class provides a set of static methods for converting
/// primitive type values to and from their XML string representations.</summary>
internal class XmlCustomFormatter
{
private static DateTimeSerializationSection.DateTimeSerializationMode s_mode;
private static DateTimeSerializationSection.DateTimeSerializationMode Mode
{
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety")]
get
{
if (s_mode == DateTimeSerializationSection.DateTimeSerializationMode.Default)
{
DateTimeSerializationSection section = PrivilegedConfigurationManager.GetSection(ConfigurationStrings.DateTimeSerializationSectionPath) as DateTimeSerializationSection;
if (section != null)
{
s_mode = section.Mode;
}
else
{
s_mode = DateTimeSerializationSection.DateTimeSerializationMode.Roundtrip;
}
}
return s_mode;
}
}
private XmlCustomFormatter() { }
internal static string FromDefaultValue(object value, string formatter)
{
if (value == null) return null;
Type type = value.GetType();
if (type == typeof(DateTime))
{
if (formatter == "DateTime")
{
return FromDateTime((DateTime)value);
}
if (formatter == "Date")
{
return FromDate((DateTime)value);
}
if (formatter == "Time")
{
return FromTime((DateTime)value);
}
}
else if (type == typeof(string))
{
if (formatter == "XmlName")
{
return FromXmlName((string)value);
}
if (formatter == "XmlNCName")
{
return FromXmlNCName((string)value);
}
if (formatter == "XmlNmToken")
{
return FromXmlNmToken((string)value);
}
if (formatter == "XmlNmTokens")
{
return FromXmlNmTokens((string)value);
}
}
throw new Exception(SR.Format(SR.XmlUnsupportedDefaultType, type.FullName));
}
internal static string FromDate(DateTime value)
{
return XmlConvert.ToString(value, "yyyy-MM-dd");
}
internal static string FromTime(DateTime value)
{
if (!LocalAppContextSwitches.IgnoreKindInUtcTimeSerialization && value.Kind == DateTimeKind.Utc)
{
return XmlConvert.ToString(DateTime.MinValue + value.TimeOfDay, "HH:mm:ss.fffffffZ");
}
else
{
return XmlConvert.ToString(DateTime.MinValue + value.TimeOfDay, "HH:mm:ss.fffffffzzzzzz");
}
}
internal static string FromDateTime(DateTime value)
{
if (Mode == DateTimeSerializationSection.DateTimeSerializationMode.Local)
{
return XmlConvert.ToString(value, "yyyy-MM-ddTHH:mm:ss.fffffffzzzzzz");
}
else
{
// for mode DateTimeSerializationMode.Roundtrip and DateTimeSerializationMode.Default
return XmlConvert.ToString(value, XmlDateTimeSerializationMode.RoundtripKind);
}
}
internal static string FromChar(char value)
{
return XmlConvert.ToString((UInt16)value);
}
internal static string FromXmlName(string name)
{
return XmlConvert.EncodeName(name);
}
internal static string FromXmlNCName(string ncName)
{
return XmlConvert.EncodeLocalName(ncName);
}
internal static string FromXmlNmToken(string nmToken)
{
return XmlConvert.EncodeNmToken(nmToken);
}
internal static string FromXmlNmTokens(string nmTokens)
{
if (nmTokens == null)
return null;
if (nmTokens.IndexOf(' ') < 0)
return FromXmlNmToken(nmTokens);
else
{
string[] toks = nmTokens.Split(new char[] { ' ' });
StringBuilder sb = new StringBuilder();
for (int i = 0; i < toks.Length; i++)
{
if (i > 0) sb.Append(' ');
sb.Append(FromXmlNmToken(toks[i]));
}
return sb.ToString();
}
}
internal static void WriteArrayBase64(XmlWriter writer, byte[] inData, int start, int count)
{
if (inData == null || count == 0)
{
return;
}
writer.WriteBase64(inData, start, count);
}
internal static string FromByteArrayHex(byte[] value)
{
if (value == null)
return null;
if (value.Length == 0)
return "";
return XmlConvert.ToBinHexString(value);
}
internal static string FromEnum(long val, string[] vals, long[] ids, string typeName)
{
#if DEBUG
// use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
if (ids.Length != vals.Length) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "Invalid enum"));
#endif
long originalValue = val;
StringBuilder sb = new StringBuilder();
int iZero = -1;
for (int i = 0; i < ids.Length; i++)
{
if (ids[i] == 0)
{
iZero = i;
continue;
}
if (val == 0)
{
break;
}
if ((ids[i] & originalValue) == ids[i])
{
if (sb.Length != 0)
sb.Append(" ");
sb.Append(vals[i]);
val &= ~ids[i];
}
}
if (val != 0)
{
// failed to parse the enum value
throw new InvalidOperationException(SR.Format(SR.XmlUnknownConstant, originalValue, typeName == null ? "enum" : typeName));
}
if (sb.Length == 0 && iZero >= 0)
{
sb.Append(vals[iZero]);
}
return sb.ToString();
}
internal static object ToDefaultValue(string value, string formatter)
{
if (formatter == "DateTime")
{
return ToDateTime(value);
}
if (formatter == "Date")
{
return ToDate(value);
}
if (formatter == "Time")
{
return ToTime(value);
}
if (formatter == "XmlName")
{
return ToXmlName(value);
}
if (formatter == "XmlNCName")
{
return ToXmlNCName(value);
}
if (formatter == "XmlNmToken")
{
return ToXmlNmToken(value);
}
if (formatter == "XmlNmTokens")
{
return ToXmlNmTokens(value);
}
throw new Exception(SR.Format(SR.XmlUnsupportedDefaultValue, formatter));
// Debug.WriteLineIf(CompModSwitches.XmlSerialization.TraceVerbose, "XmlSerialization::Unhandled default value " + value + " formatter " + formatter);
// return DBNull.Value;
}
private static string[] s_allDateTimeFormats = new string[] {
"yyyy-MM-ddTHH:mm:ss.fffffffzzzzzz",
"yyyy",
"---dd",
"---ddZ",
"---ddzzzzzz",
"--MM-dd",
"--MM-ddZ",
"--MM-ddzzzzzz",
"--MM--",
"--MM--Z",
"--MM--zzzzzz",
"yyyy-MM",
"yyyy-MMZ",
"yyyy-MMzzzzzz",
"yyyyzzzzzz",
"yyyy-MM-dd",
"yyyy-MM-ddZ",
"yyyy-MM-ddzzzzzz",
"HH:mm:ss",
"HH:mm:ss.f",
"HH:mm:ss.ff",
"HH:mm:ss.fff",
"HH:mm:ss.ffff",
"HH:mm:ss.fffff",
"HH:mm:ss.ffffff",
"HH:mm:ss.fffffff",
"HH:mm:ssZ",
"HH:mm:ss.fZ",
"HH:mm:ss.ffZ",
"HH:mm:ss.fffZ",
"HH:mm:ss.ffffZ",
"HH:mm:ss.fffffZ",
"HH:mm:ss.ffffffZ",
"HH:mm:ss.fffffffZ",
"HH:mm:sszzzzzz",
"HH:mm:ss.fzzzzzz",
"HH:mm:ss.ffzzzzzz",
"HH:mm:ss.fffzzzzzz",
"HH:mm:ss.ffffzzzzzz",
"HH:mm:ss.fffffzzzzzz",
"HH:mm:ss.ffffffzzzzzz",
"HH:mm:ss.fffffffzzzzzz",
"yyyy-MM-ddTHH:mm:ss",
"yyyy-MM-ddTHH:mm:ss.f",
"yyyy-MM-ddTHH:mm:ss.ff",
"yyyy-MM-ddTHH:mm:ss.fff",
"yyyy-MM-ddTHH:mm:ss.ffff",
"yyyy-MM-ddTHH:mm:ss.fffff",
"yyyy-MM-ddTHH:mm:ss.ffffff",
"yyyy-MM-ddTHH:mm:ss.fffffff",
"yyyy-MM-ddTHH:mm:ssZ",
"yyyy-MM-ddTHH:mm:ss.fZ",
"yyyy-MM-ddTHH:mm:ss.ffZ",
"yyyy-MM-ddTHH:mm:ss.fffZ",
"yyyy-MM-ddTHH:mm:ss.ffffZ",
"yyyy-MM-ddTHH:mm:ss.fffffZ",
"yyyy-MM-ddTHH:mm:ss.ffffffZ",
"yyyy-MM-ddTHH:mm:ss.fffffffZ",
"yyyy-MM-ddTHH:mm:sszzzzzz",
"yyyy-MM-ddTHH:mm:ss.fzzzzzz",
"yyyy-MM-ddTHH:mm:ss.ffzzzzzz",
"yyyy-MM-ddTHH:mm:ss.fffzzzzzz",
"yyyy-MM-ddTHH:mm:ss.ffffzzzzzz",
"yyyy-MM-ddTHH:mm:ss.fffffzzzzzz",
"yyyy-MM-ddTHH:mm:ss.ffffffzzzzzz",
};
private static string[] s_allDateFormats = new string[] {
"yyyy-MM-ddzzzzzz",
"yyyy-MM-dd",
"yyyy-MM-ddZ",
"yyyy",
"---dd",
"---ddZ",
"---ddzzzzzz",
"--MM-dd",
"--MM-ddZ",
"--MM-ddzzzzzz",
"--MM--",
"--MM--Z",
"--MM--zzzzzz",
"yyyy-MM",
"yyyy-MMZ",
"yyyy-MMzzzzzz",
"yyyyzzzzzz",
};
private static string[] s_allTimeFormats = new string[] {
"HH:mm:ss.fffffffzzzzzz",
"HH:mm:ss",
"HH:mm:ss.f",
"HH:mm:ss.ff",
"HH:mm:ss.fff",
"HH:mm:ss.ffff",
"HH:mm:ss.fffff",
"HH:mm:ss.ffffff",
"HH:mm:ss.fffffff",
"HH:mm:ssZ",
"HH:mm:ss.fZ",
"HH:mm:ss.ffZ",
"HH:mm:ss.fffZ",
"HH:mm:ss.ffffZ",
"HH:mm:ss.fffffZ",
"HH:mm:ss.ffffffZ",
"HH:mm:ss.fffffffZ",
"HH:mm:sszzzzzz",
"HH:mm:ss.fzzzzzz",
"HH:mm:ss.ffzzzzzz",
"HH:mm:ss.fffzzzzzz",
"HH:mm:ss.ffffzzzzzz",
"HH:mm:ss.fffffzzzzzz",
"HH:mm:ss.ffffffzzzzzz",
};
internal static DateTime ToDateTime(string value)
{
if (Mode == DateTimeSerializationSection.DateTimeSerializationMode.Local)
{
return ToDateTime(value, s_allDateTimeFormats);
}
else
{
// for mode DateTimeSerializationMode.Roundtrip and DateTimeSerializationMode.Default
return XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.RoundtripKind);
}
}
internal static DateTime ToDateTime(string value, string[] formats)
{
return XmlConvert.ToDateTime(value, formats);
}
internal static DateTime ToDate(string value)
{
return ToDateTime(value, s_allDateFormats);
}
internal static DateTime ToTime(string value)
{
if (!LocalAppContextSwitches.IgnoreKindInUtcTimeSerialization)
{
return DateTime.ParseExact(value, s_allTimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite | DateTimeStyles.NoCurrentDateDefault | DateTimeStyles.RoundtripKind);
}
else
{
return DateTime.ParseExact(value, s_allTimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite | DateTimeStyles.NoCurrentDateDefault);
}
}
internal static char ToChar(string value)
{
return (char)XmlConvert.ToUInt16(value);
}
internal static string ToXmlName(string value)
{
return XmlConvert.DecodeName(CollapseWhitespace(value));
}
internal static string ToXmlNCName(string value)
{
return XmlConvert.DecodeName(CollapseWhitespace(value));
}
internal static string ToXmlNmToken(string value)
{
return XmlConvert.DecodeName(CollapseWhitespace(value));
}
internal static string ToXmlNmTokens(string value)
{
return XmlConvert.DecodeName(CollapseWhitespace(value));
}
internal static byte[] ToByteArrayBase64(string value)
{
if (value == null) return null;
value = value.Trim();
if (value.Length == 0)
return Array.Empty<byte>();
return Convert.FromBase64String(value);
}
internal static byte[] ToByteArrayHex(string value)
{
if (value == null) return null;
value = value.Trim();
return XmlConvert.FromBinHexString(value);
}
internal static long ToEnum(string val, Hashtable vals, string typeName, bool validate)
{
long value = 0;
string[] parts = val.Split(null);
for (int i = 0; i < parts.Length; i++)
{
object id = vals[parts[i]];
if (id != null)
value |= (long)id;
else if (validate && parts[i].Length > 0)
throw new InvalidOperationException(SR.Format(SR.XmlUnknownConstant, parts[i], typeName));
}
return value;
}
private static string CollapseWhitespace(string value)
{
if (value == null)
return null;
return value.Trim();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Tests.LegacyTests
{
public class ThenByTests
{
// Class which is passed as an argument for EqualityComparer
public class CaseInsensitiveComparer : IComparer<string>
{
public int Compare(string x, string y)
{
return string.Compare(x.ToLower(), y.ToLower());
}
}
private struct Record
{
#pragma warning disable 0649
public string Name;
public string City;
public string Country;
#pragma warning restore 0649
}
public class ThenBy005
{
private static int ThenBy001()
{
var q = from x1 in new int[] { 1, 6, 0, -1, 3 }
from x2 in new int[] { 55, 49, 9, -100, 24, 25 }
select new { a1 = x1, a2 = x2 };
var rst1 = q.OrderByDescending(e => e.a1).ThenBy(f => f.a2);
var rst2 = q.OrderByDescending(e => e.a1).ThenBy(f => f.a2);
return Verification.Allequal(rst1, rst2);
}
private static int ThenBy002()
{
var q = from x1 in new[] { 55, 49, 9, -100, 24, 25, -1, 0 }
from x2 in new[] { "!@#$%^", "C", "AAA", "", null, "Calling Twice", "SoS", String.Empty }
where !String.IsNullOrEmpty(x2)
select new { a1 = x1, a2 = x2 };
var rst1 = q.OrderBy(e => e.a2).ThenBy(f => f.a1);
var rst2 = q.OrderBy(e => e.a2).ThenBy(f => f.a1);
return Verification.Allequal(rst1, rst2);
}
public static int Main()
{
int ret = RunTest(ThenBy001) + RunTest(ThenBy002);
if (0 != ret)
Console.Write(s_errorMessage);
return ret;
}
private static string s_errorMessage = String.Empty;
private delegate int D();
private static int RunTest(D m)
{
int n = m();
if (0 != n)
s_errorMessage += m.ToString() + " - FAILED!\r\n";
return n;
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class ThenBy1
{
// Overload-1: source is empty
public static int Test1()
{
int[] source = { };
int[] expected = { };
var actual = source.OrderBy((e) => e).ThenBy((e) => (e));
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test1();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class ThenBy2
{
// Overload-1: secondary keys are unique
public static int Test2()
{
Record[] source = new Record[]{
new Record{Name = "Jim", City = "Minneapolis", Country = "USA"},
new Record{Name = "Tim", City = "Seattle", Country = "USA"},
new Record{Name = "Philip", City = "Orlando", Country = "USA"},
new Record{Name = "Chris", City = "London", Country = "UK"},
new Record{Name = "Rob", City = "Kent", Country = "UK"}
};
Record[] expected = new Record[]{
new Record{Name = "Rob", City = "Kent", Country = "UK"},
new Record{Name = "Chris", City = "London", Country = "UK"},
new Record{Name = "Jim", City = "Minneapolis", Country = "USA"},
new Record{Name = "Philip", City = "Orlando", Country = "USA"},
new Record{Name = "Tim", City = "Seattle", Country = "USA"}
};
var actual = source.OrderBy((e) => e.Country).ThenBy((e) => e.City);
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test2();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class ThenBy3
{
// Overload-2: OrderBy and ThenBy on the same field
public static int Test3()
{
Record[] source = new Record[]{
new Record{Name = "Jim", City = "Minneapolis", Country = "USA"},
new Record{Name = "Prakash", City = "Chennai", Country = "India"},
new Record{Name = "Rob", City = "Kent", Country = "UK"}
};
Record[] expected = new Record[]{
new Record{Name = "Prakash", City = "Chennai", Country = "India"},
new Record{Name = "Rob", City = "Kent", Country = "UK"},
new Record{Name = "Jim", City = "Minneapolis", Country = "USA"}
};
var actual = source.OrderBy((e) => e.Country).ThenBy((e) => e.Country, null);
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test3();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class ThenBy4
{
// Overload-2: secondary keys repeat across elements with different primary keys
public static int Test4()
{
Record[] source = new Record[]{
new Record{Name = "Jim", City = "Minneapolis", Country = "USA"},
new Record{Name = "Tim", City = "Seattle", Country = "USA"},
new Record{Name = "Philip", City = "Orlando", Country = "USA"},
new Record{Name = "Chris", City = "Minneapolis", Country = "USA"},
new Record{Name = "Rob", City = "Seattle", Country = "USA"}
};
Record[] expected = new Record[]{
new Record{Name = "Chris", City = "Minneapolis", Country = "USA"},
new Record{Name = "Jim", City = "Minneapolis", Country = "USA"},
new Record{Name = "Philip", City = "Orlando", Country = "USA"},
new Record{Name = "Rob", City = "Seattle", Country = "USA"},
new Record{Name = "Tim", City = "Seattle", Country = "USA"}
};
var actual = source.OrderBy((e) => e.Name).ThenBy((e) => e.City, null);
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test4();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
}
}
| |
/*==========================================================================;
*
* This file is part of LATINO. See http://www.latinolib.org
*
* File: SvmBinaryClassifierManaged.cs
* Desc: Fully-managed code for executing SvmLight models
* Created: Jun-2018
*
* Author: Miha Grcar
*
***************************************************************************/
using System;
using System.Collections.Generic;
namespace Latino.Model
{
/* .-----------------------------------------------------------------------
|
| Class SvmBinaryClassifierManaged<LblT>
|
'-----------------------------------------------------------------------
*/
public class SvmBinaryClassifierManaged<LblT> : IModel<LblT, SparseVector<double>>
{
private ArrayList<LblT> mIdxToLbl
= new ArrayList<LblT>();
private IEqualityComparer<LblT> mLblCmp;
private double mC;
private bool mBiasedHyperplane;
private SvmLightKernelType mKernelType;
private double mKernelParamGamma;
private double mKernelParamD;
private double mKernelParamS;
private double mKernelParamC;
private bool mBiasedCostFunction;
private double mEps;
private int mMaxIter;
private string mCustomParams;
private double mBias;
private double[] mLinearWeights;
public SvmBinaryClassifierManaged(BinarySerializer reader)
{
Load(reader); // throws ArgumentNullException, serialization-related exceptions
}
public double C
{
get { return mC; }
}
public bool BiasedHyperplane
{
get { return mBiasedHyperplane; }
}
public SvmLightKernelType KernelType
{
get { return mKernelType; }
}
public double KernelParamGamma
{
get { return mKernelParamGamma; }
}
public double KernelParamD
{
get { return mKernelParamD; }
}
public double KernelParamS
{
get { return mKernelParamD; }
}
public double KernelParamC
{
get { return mKernelParamD; }
}
public double Eps
{
get { return mEps; }
}
public bool BiasedCostFunction
{
get { return mBiasedCostFunction; }
}
public int MaxIter
{
get { return mMaxIter; }
}
public string CustomParams
{
get { return mCustomParams; }
}
public double Bias
{
get { return mBias; }
}
public int GetInternalClassLabel(LblT label)
{
Utils.ThrowException(label == null ? new ArgumentNullException("label") : null);
for (int i = 0; i < mIdxToLbl.Count; i++)
{
if ((mLblCmp != null && mLblCmp.Equals(mIdxToLbl[i], label)) ||
(mLblCmp == null && mIdxToLbl[i].Equals(label))) { return i == 0 ? 1 : -1; }
}
throw new ArgumentValueException("label");
}
// *** IModel<LblT, SparseVector<double>> interface implementation ***
public Type RequiredExampleType
{
get { return typeof(SparseVector<double>); }
}
public bool IsTrained
{
get { return true; } // the only way to create an instance is to load a trained model
}
public void Train(ILabeledExampleCollection<LblT, SparseVector<double>> dataset)
{
throw new NotImplementedException();
}
void IModel<LblT>.Train(ILabeledExampleCollection<LblT> dataset)
{
throw new NotImplementedException();
}
public Prediction<LblT> Predict(SparseVector<double> example)
{
Utils.ThrowException(example == null ? new ArgumentNullException("example") : null);
double score = 0;
for (int i = 0; i < example.Count; i++)
{
score += mLinearWeights[example.InnerIdx[i]] * example.InnerDat[i];
}
score -= mBias;
LblT lbl = mIdxToLbl[score > 0 ? 0 : 1];
LblT otherLbl = mIdxToLbl[score > 0 ? 1 : 0];
Prediction<LblT> result = new Prediction<LblT>();
result.Inner.Add(new KeyDat<double, LblT>(Math.Abs(score), lbl));
result.Inner.Add(new KeyDat<double, LblT>(-Math.Abs(score), otherLbl));
return result;
}
Prediction<LblT> IModel<LblT>.Predict(object example)
{
return Predict((SparseVector<double>)example);
}
// *** ISerializable interface implementation ***
public void Save(BinarySerializer writer)
{
throw new NotImplementedException();
}
public void Load(BinarySerializer reader)
{
Utils.ThrowException(reader == null ? new ArgumentNullException("reader") : null);
// the following statements throw serialization-related exceptions
reader.ReadInt(); // verbosity level (ignore)
mC = reader.ReadDouble();
mBiasedHyperplane = reader.ReadBool();
mKernelType = (SvmLightKernelType)reader.ReadInt();
if (mKernelType != SvmLightKernelType.Linear)
{
throw new Exception("You are trying to load a non-linear model. This implementation does not support non-linear models.");
}
mKernelParamGamma = reader.ReadDouble();
mKernelParamD = reader.ReadDouble();
mKernelParamS = reader.ReadDouble();
mKernelParamC = reader.ReadDouble();
mBiasedCostFunction = reader.ReadBool();
mCustomParams = reader.ReadString();
mEps = reader.ReadDouble();
mMaxIter = reader.ReadInt();
mIdxToLbl.Load(reader);
mLblCmp = reader.ReadObject<IEqualityComparer<LblT>>();
if (!reader.ReadBool())
{
throw new Exception("The model that you are trying to load has not been trained.");
}
// load SvmLight model
int verLen = reader.ReadInt(); // int: version specifier length
reader.ReadBytes(verLen); // byte[]: version specifier
reader.ReadInt(); // long: kernel type (C long is C# int)
reader.ReadInt(); // long: poly degree
reader.ReadDouble(); // double: RBF gamma
reader.ReadDouble(); // double: "coef lin"
reader.ReadDouble(); // double: "coef const"
reader.ReadBytes(50); // byte[50]: custom
int totalWords = reader.ReadInt(); // long: total words
mLinearWeights = new double[totalWords];
reader.ReadInt(); // long: total docs
int numSupVec = reader.ReadInt(); // int: num support vectors
mBias = reader.ReadDouble(); // double: hyperplane bias
for (int i = 0; i < numSupVec - 1; i++)
{
double alpha = reader.ReadDouble(); // double: alpha
int numFeatures = reader.ReadInt(); // int: number of features
for (int j = 0; j < numFeatures; j++)
{
int fnum = reader.ReadInt(); // int32: feature number (1-based)
float fval = reader.ReadFloat(); // float: feature value
mLinearWeights[fnum - 1] += alpha * fval;
}
int commentLen = reader.ReadInt(); // int: comment len
reader.ReadBytes(commentLen); // byte[]: comment
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
class r8NaNdiv
{
//user-defined class that overloads operator /
public class numHolder
{
double d_num;
public numHolder(double d_num)
{
this.d_num = Convert.ToDouble(d_num);
}
public static double operator /(numHolder a, double b)
{
return a.d_num / b;
}
public static double operator /(numHolder a, numHolder b)
{
return a.d_num / b.d_num;
}
}
static double d_s_test1_op1 = Double.NaN;
static double d_s_test1_op2 = Double.NaN;
static double d_s_test2_op1 = 5.12345678F;
static double d_s_test2_op2 = Double.NaN;
static double d_s_test3_op1 = Double.NaN;
static double d_s_test3_op2 = 0;
public static double d_test1_f(String s)
{
if (s == "test1_op1")
return Double.NaN;
else
return Double.NaN;
}
public static double d_test2_f(String s)
{
if (s == "test2_op1")
return 5.12345678F;
else
return Double.NaN;
}
public static double d_test3_f(String s)
{
if (s == "test3_op1")
return Double.NaN;
else
return 0;
}
class CL
{
public double d_cl_test1_op1 = Double.NaN;
public double d_cl_test1_op2 = Double.NaN;
public double d_cl_test2_op1 = 5.12345678F;
public double d_cl_test2_op2 = Double.NaN;
public double d_cl_test3_op1 = Double.NaN;
public double d_cl_test3_op2 = 0;
}
struct VT
{
public double d_vt_test1_op1;
public double d_vt_test1_op2;
public double d_vt_test2_op1;
public double d_vt_test2_op2;
public double d_vt_test3_op1;
public double d_vt_test3_op2;
}
public static int Main()
{
bool passed = true;
//initialize class
CL cl1 = new CL();
//initialize struct
VT vt1;
vt1.d_vt_test1_op1 = Double.NaN;
vt1.d_vt_test1_op2 = Double.NaN;
vt1.d_vt_test2_op1 = 5.12345678F;
vt1.d_vt_test2_op2 = Double.NaN;
vt1.d_vt_test3_op1 = Double.NaN;
vt1.d_vt_test3_op2 = 0;
double[] d_arr1d_test1_op1 = { 0, Double.NaN };
double[,] d_arr2d_test1_op1 = { { 0, Double.NaN }, { 1, 1 } };
double[, ,] d_arr3d_test1_op1 = { { { 0, Double.NaN }, { 1, 1 } } };
double[] d_arr1d_test1_op2 = { Double.NaN, 0, 1 };
double[,] d_arr2d_test1_op2 = { { 0, Double.NaN }, { 1, 1 } };
double[, ,] d_arr3d_test1_op2 = { { { 0, Double.NaN }, { 1, 1 } } };
double[] d_arr1d_test2_op1 = { 0, 5.12345678F };
double[,] d_arr2d_test2_op1 = { { 0, 5.12345678F }, { 1, 1 } };
double[, ,] d_arr3d_test2_op1 = { { { 0, 5.12345678F }, { 1, 1 } } };
double[] d_arr1d_test2_op2 = { Double.NaN, 0, 1 };
double[,] d_arr2d_test2_op2 = { { 0, Double.NaN }, { 1, 1 } };
double[, ,] d_arr3d_test2_op2 = { { { 0, Double.NaN }, { 1, 1 } } };
double[] d_arr1d_test3_op1 = { 0, Double.NaN };
double[,] d_arr2d_test3_op1 = { { 0, Double.NaN }, { 1, 1 } };
double[, ,] d_arr3d_test3_op1 = { { { 0, Double.NaN }, { 1, 1 } } };
double[] d_arr1d_test3_op2 = { 0, 0, 1 };
double[,] d_arr2d_test3_op2 = { { 0, 0 }, { 1, 1 } };
double[, ,] d_arr3d_test3_op2 = { { { 0, 0 }, { 1, 1 } } };
int[,] index = { { 0, 0 }, { 1, 1 } };
{
double d_l_test1_op1 = Double.NaN;
double d_l_test1_op2 = Double.NaN;
if (!Double.IsNaN(d_l_test1_op1 / d_l_test1_op2))
{
Console.WriteLine("Test1_testcase 1 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test1_op1 / d_s_test1_op2))
{
Console.WriteLine("Test1_testcase 2 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test1_op1 / d_test1_f("test1_op2")))
{
Console.WriteLine("Test1_testcase 3 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test1_op1 / cl1.d_cl_test1_op2))
{
Console.WriteLine("Test1_testcase 4 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test1_op1 / vt1.d_vt_test1_op2))
{
Console.WriteLine("Test1_testcase 5 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test1_op1 / d_arr1d_test1_op2[0]))
{
Console.WriteLine("Test1_testcase 6 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test1_op1 / d_arr2d_test1_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test1_testcase 7 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test1_op1 / d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test1_testcase 8 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test1_op1 / d_l_test1_op2))
{
Console.WriteLine("Test1_testcase 9 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test1_op1 / d_s_test1_op2))
{
Console.WriteLine("Test1_testcase 10 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test1_op1 / d_test1_f("test1_op2")))
{
Console.WriteLine("Test1_testcase 11 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test1_op1 / cl1.d_cl_test1_op2))
{
Console.WriteLine("Test1_testcase 12 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test1_op1 / vt1.d_vt_test1_op2))
{
Console.WriteLine("Test1_testcase 13 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test1_op1 / d_arr1d_test1_op2[0]))
{
Console.WriteLine("Test1_testcase 14 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test1_op1 / d_arr2d_test1_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test1_testcase 15 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test1_op1 / d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test1_testcase 16 failed");
passed = false;
}
if (!Double.IsNaN(d_test1_f("test1_op1") / d_l_test1_op2))
{
Console.WriteLine("Test1_testcase 17 failed");
passed = false;
}
if (!Double.IsNaN(d_test1_f("test1_op1") / d_s_test1_op2))
{
Console.WriteLine("Test1_testcase 18 failed");
passed = false;
}
if (!Double.IsNaN(d_test1_f("test1_op1") / d_test1_f("test1_op2")))
{
Console.WriteLine("Test1_testcase 19 failed");
passed = false;
}
if (!Double.IsNaN(d_test1_f("test1_op1") / cl1.d_cl_test1_op2))
{
Console.WriteLine("Test1_testcase 20 failed");
passed = false;
}
if (!Double.IsNaN(d_test1_f("test1_op1") / vt1.d_vt_test1_op2))
{
Console.WriteLine("Test1_testcase 21 failed");
passed = false;
}
if (!Double.IsNaN(d_test1_f("test1_op1") / d_arr1d_test1_op2[0]))
{
Console.WriteLine("Test1_testcase 22 failed");
passed = false;
}
if (!Double.IsNaN(d_test1_f("test1_op1") / d_arr2d_test1_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test1_testcase 23 failed");
passed = false;
}
if (!Double.IsNaN(d_test1_f("test1_op1") / d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test1_testcase 24 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test1_op1 / d_l_test1_op2))
{
Console.WriteLine("Test1_testcase 25 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test1_op1 / d_s_test1_op2))
{
Console.WriteLine("Test1_testcase 26 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test1_op1 / d_test1_f("test1_op2")))
{
Console.WriteLine("Test1_testcase 27 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test1_op1 / cl1.d_cl_test1_op2))
{
Console.WriteLine("Test1_testcase 28 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test1_op1 / vt1.d_vt_test1_op2))
{
Console.WriteLine("Test1_testcase 29 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test1_op1 / d_arr1d_test1_op2[0]))
{
Console.WriteLine("Test1_testcase 30 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test1_op1 / d_arr2d_test1_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test1_testcase 31 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test1_op1 / d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test1_testcase 32 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test1_op1 / d_l_test1_op2))
{
Console.WriteLine("Test1_testcase 33 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test1_op1 / d_s_test1_op2))
{
Console.WriteLine("Test1_testcase 34 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test1_op1 / d_test1_f("test1_op2")))
{
Console.WriteLine("Test1_testcase 35 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test1_op1 / cl1.d_cl_test1_op2))
{
Console.WriteLine("Test1_testcase 36 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test1_op1 / vt1.d_vt_test1_op2))
{
Console.WriteLine("Test1_testcase 37 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test1_op1 / d_arr1d_test1_op2[0]))
{
Console.WriteLine("Test1_testcase 38 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test1_op1 / d_arr2d_test1_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test1_testcase 39 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test1_op1 / d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test1_testcase 40 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test1_op1[1] / d_l_test1_op2))
{
Console.WriteLine("Test1_testcase 41 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test1_op1[1] / d_s_test1_op2))
{
Console.WriteLine("Test1_testcase 42 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test1_op1[1] / d_test1_f("test1_op2")))
{
Console.WriteLine("Test1_testcase 43 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test1_op1[1] / cl1.d_cl_test1_op2))
{
Console.WriteLine("Test1_testcase 44 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test1_op1[1] / vt1.d_vt_test1_op2))
{
Console.WriteLine("Test1_testcase 45 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test1_op1[1] / d_arr1d_test1_op2[0]))
{
Console.WriteLine("Test1_testcase 46 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test1_op1[1] / d_arr2d_test1_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test1_testcase 47 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test1_op1[1] / d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test1_testcase 48 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] / d_l_test1_op2))
{
Console.WriteLine("Test1_testcase 49 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] / d_s_test1_op2))
{
Console.WriteLine("Test1_testcase 50 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] / d_test1_f("test1_op2")))
{
Console.WriteLine("Test1_testcase 51 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] / cl1.d_cl_test1_op2))
{
Console.WriteLine("Test1_testcase 52 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] / vt1.d_vt_test1_op2))
{
Console.WriteLine("Test1_testcase 53 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] / d_arr1d_test1_op2[0]))
{
Console.WriteLine("Test1_testcase 54 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] / d_arr2d_test1_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test1_testcase 55 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] / d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test1_testcase 56 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] / d_l_test1_op2))
{
Console.WriteLine("Test1_testcase 57 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] / d_s_test1_op2))
{
Console.WriteLine("Test1_testcase 58 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] / d_test1_f("test1_op2")))
{
Console.WriteLine("Test1_testcase 59 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] / cl1.d_cl_test1_op2))
{
Console.WriteLine("Test1_testcase 60 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] / vt1.d_vt_test1_op2))
{
Console.WriteLine("Test1_testcase 61 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] / d_arr1d_test1_op2[0]))
{
Console.WriteLine("Test1_testcase 62 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] / d_arr2d_test1_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test1_testcase 63 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] / d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test1_testcase 64 failed");
passed = false;
}
}
{
double d_l_test2_op1 = 5.12345678F;
double d_l_test2_op2 = Double.NaN;
if (!Double.IsNaN(d_l_test2_op1 / d_l_test2_op2))
{
Console.WriteLine("Test2_testcase 1 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test2_op1 / d_s_test2_op2))
{
Console.WriteLine("Test2_testcase 2 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test2_op1 / d_test2_f("test2_op2")))
{
Console.WriteLine("Test2_testcase 3 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test2_op1 / cl1.d_cl_test2_op2))
{
Console.WriteLine("Test2_testcase 4 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test2_op1 / vt1.d_vt_test2_op2))
{
Console.WriteLine("Test2_testcase 5 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test2_op1 / d_arr1d_test2_op2[0]))
{
Console.WriteLine("Test2_testcase 6 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test2_op1 / d_arr2d_test2_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test2_testcase 7 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test2_op1 / d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test2_testcase 8 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test2_op1 / d_l_test2_op2))
{
Console.WriteLine("Test2_testcase 9 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test2_op1 / d_s_test2_op2))
{
Console.WriteLine("Test2_testcase 10 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test2_op1 / d_test2_f("test2_op2")))
{
Console.WriteLine("Test2_testcase 11 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test2_op1 / cl1.d_cl_test2_op2))
{
Console.WriteLine("Test2_testcase 12 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test2_op1 / vt1.d_vt_test2_op2))
{
Console.WriteLine("Test2_testcase 13 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test2_op1 / d_arr1d_test2_op2[0]))
{
Console.WriteLine("Test2_testcase 14 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test2_op1 / d_arr2d_test2_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test2_testcase 15 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test2_op1 / d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test2_testcase 16 failed");
passed = false;
}
if (!Double.IsNaN(d_test2_f("test2_op1") / d_l_test2_op2))
{
Console.WriteLine("Test2_testcase 17 failed");
passed = false;
}
if (!Double.IsNaN(d_test2_f("test2_op1") / d_s_test2_op2))
{
Console.WriteLine("Test2_testcase 18 failed");
passed = false;
}
if (!Double.IsNaN(d_test2_f("test2_op1") / d_test2_f("test2_op2")))
{
Console.WriteLine("Test2_testcase 19 failed");
passed = false;
}
if (!Double.IsNaN(d_test2_f("test2_op1") / cl1.d_cl_test2_op2))
{
Console.WriteLine("Test2_testcase 20 failed");
passed = false;
}
if (!Double.IsNaN(d_test2_f("test2_op1") / vt1.d_vt_test2_op2))
{
Console.WriteLine("Test2_testcase 21 failed");
passed = false;
}
if (!Double.IsNaN(d_test2_f("test2_op1") / d_arr1d_test2_op2[0]))
{
Console.WriteLine("Test2_testcase 22 failed");
passed = false;
}
if (!Double.IsNaN(d_test2_f("test2_op1") / d_arr2d_test2_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test2_testcase 23 failed");
passed = false;
}
if (!Double.IsNaN(d_test2_f("test2_op1") / d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test2_testcase 24 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test2_op1 / d_l_test2_op2))
{
Console.WriteLine("Test2_testcase 25 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test2_op1 / d_s_test2_op2))
{
Console.WriteLine("Test2_testcase 26 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test2_op1 / d_test2_f("test2_op2")))
{
Console.WriteLine("Test2_testcase 27 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test2_op1 / cl1.d_cl_test2_op2))
{
Console.WriteLine("Test2_testcase 28 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test2_op1 / vt1.d_vt_test2_op2))
{
Console.WriteLine("Test2_testcase 29 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test2_op1 / d_arr1d_test2_op2[0]))
{
Console.WriteLine("Test2_testcase 30 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test2_op1 / d_arr2d_test2_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test2_testcase 31 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test2_op1 / d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test2_testcase 32 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test2_op1 / d_l_test2_op2))
{
Console.WriteLine("Test2_testcase 33 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test2_op1 / d_s_test2_op2))
{
Console.WriteLine("Test2_testcase 34 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test2_op1 / d_test2_f("test2_op2")))
{
Console.WriteLine("Test2_testcase 35 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test2_op1 / cl1.d_cl_test2_op2))
{
Console.WriteLine("Test2_testcase 36 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test2_op1 / vt1.d_vt_test2_op2))
{
Console.WriteLine("Test2_testcase 37 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test2_op1 / d_arr1d_test2_op2[0]))
{
Console.WriteLine("Test2_testcase 38 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test2_op1 / d_arr2d_test2_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test2_testcase 39 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test2_op1 / d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test2_testcase 40 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test2_op1[1] / d_l_test2_op2))
{
Console.WriteLine("Test2_testcase 41 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test2_op1[1] / d_s_test2_op2))
{
Console.WriteLine("Test2_testcase 42 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test2_op1[1] / d_test2_f("test2_op2")))
{
Console.WriteLine("Test2_testcase 43 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test2_op1[1] / cl1.d_cl_test2_op2))
{
Console.WriteLine("Test2_testcase 44 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test2_op1[1] / vt1.d_vt_test2_op2))
{
Console.WriteLine("Test2_testcase 45 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test2_op1[1] / d_arr1d_test2_op2[0]))
{
Console.WriteLine("Test2_testcase 46 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test2_op1[1] / d_arr2d_test2_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test2_testcase 47 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test2_op1[1] / d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test2_testcase 48 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] / d_l_test2_op2))
{
Console.WriteLine("Test2_testcase 49 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] / d_s_test2_op2))
{
Console.WriteLine("Test2_testcase 50 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] / d_test2_f("test2_op2")))
{
Console.WriteLine("Test2_testcase 51 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] / cl1.d_cl_test2_op2))
{
Console.WriteLine("Test2_testcase 52 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] / vt1.d_vt_test2_op2))
{
Console.WriteLine("Test2_testcase 53 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] / d_arr1d_test2_op2[0]))
{
Console.WriteLine("Test2_testcase 54 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] / d_arr2d_test2_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test2_testcase 55 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] / d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test2_testcase 56 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] / d_l_test2_op2))
{
Console.WriteLine("Test2_testcase 57 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] / d_s_test2_op2))
{
Console.WriteLine("Test2_testcase 58 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] / d_test2_f("test2_op2")))
{
Console.WriteLine("Test2_testcase 59 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] / cl1.d_cl_test2_op2))
{
Console.WriteLine("Test2_testcase 60 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] / vt1.d_vt_test2_op2))
{
Console.WriteLine("Test2_testcase 61 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] / d_arr1d_test2_op2[0]))
{
Console.WriteLine("Test2_testcase 62 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] / d_arr2d_test2_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test2_testcase 63 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] / d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test2_testcase 64 failed");
passed = false;
}
}
{
double d_l_test3_op1 = Double.NaN;
double d_l_test3_op2 = 0;
if (!Double.IsNaN(d_l_test3_op1 / d_l_test3_op2))
{
Console.WriteLine("Test3_testcase 1 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test3_op1 / d_s_test3_op2))
{
Console.WriteLine("Test3_testcase 2 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test3_op1 / d_test3_f("test3_op2")))
{
Console.WriteLine("Test3_testcase 3 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test3_op1 / cl1.d_cl_test3_op2))
{
Console.WriteLine("Test3_testcase 4 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test3_op1 / vt1.d_vt_test3_op2))
{
Console.WriteLine("Test3_testcase 5 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test3_op1 / d_arr1d_test3_op2[0]))
{
Console.WriteLine("Test3_testcase 6 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test3_op1 / d_arr2d_test3_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test3_testcase 7 failed");
passed = false;
}
if (!Double.IsNaN(d_l_test3_op1 / d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test3_testcase 8 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test3_op1 / d_l_test3_op2))
{
Console.WriteLine("Test3_testcase 9 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test3_op1 / d_s_test3_op2))
{
Console.WriteLine("Test3_testcase 10 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test3_op1 / d_test3_f("test3_op2")))
{
Console.WriteLine("Test3_testcase 11 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test3_op1 / cl1.d_cl_test3_op2))
{
Console.WriteLine("Test3_testcase 12 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test3_op1 / vt1.d_vt_test3_op2))
{
Console.WriteLine("Test3_testcase 13 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test3_op1 / d_arr1d_test3_op2[0]))
{
Console.WriteLine("Test3_testcase 14 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test3_op1 / d_arr2d_test3_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test3_testcase 15 failed");
passed = false;
}
if (!Double.IsNaN(d_s_test3_op1 / d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test3_testcase 16 failed");
passed = false;
}
if (!Double.IsNaN(d_test3_f("test3_op1") / d_l_test3_op2))
{
Console.WriteLine("Test3_testcase 17 failed");
passed = false;
}
if (!Double.IsNaN(d_test3_f("test3_op1") / d_s_test3_op2))
{
Console.WriteLine("Test3_testcase 18 failed");
passed = false;
}
if (!Double.IsNaN(d_test3_f("test3_op1") / d_test3_f("test3_op2")))
{
Console.WriteLine("Test3_testcase 19 failed");
passed = false;
}
if (!Double.IsNaN(d_test3_f("test3_op1") / cl1.d_cl_test3_op2))
{
Console.WriteLine("Test3_testcase 20 failed");
passed = false;
}
if (!Double.IsNaN(d_test3_f("test3_op1") / vt1.d_vt_test3_op2))
{
Console.WriteLine("Test3_testcase 21 failed");
passed = false;
}
if (!Double.IsNaN(d_test3_f("test3_op1") / d_arr1d_test3_op2[0]))
{
Console.WriteLine("Test3_testcase 22 failed");
passed = false;
}
if (!Double.IsNaN(d_test3_f("test3_op1") / d_arr2d_test3_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test3_testcase 23 failed");
passed = false;
}
if (!Double.IsNaN(d_test3_f("test3_op1") / d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test3_testcase 24 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test3_op1 / d_l_test3_op2))
{
Console.WriteLine("Test3_testcase 25 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test3_op1 / d_s_test3_op2))
{
Console.WriteLine("Test3_testcase 26 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test3_op1 / d_test3_f("test3_op2")))
{
Console.WriteLine("Test3_testcase 27 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test3_op1 / cl1.d_cl_test3_op2))
{
Console.WriteLine("Test3_testcase 28 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test3_op1 / vt1.d_vt_test3_op2))
{
Console.WriteLine("Test3_testcase 29 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test3_op1 / d_arr1d_test3_op2[0]))
{
Console.WriteLine("Test3_testcase 30 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test3_op1 / d_arr2d_test3_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test3_testcase 31 failed");
passed = false;
}
if (!Double.IsNaN(cl1.d_cl_test3_op1 / d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test3_testcase 32 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test3_op1 / d_l_test3_op2))
{
Console.WriteLine("Test3_testcase 33 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test3_op1 / d_s_test3_op2))
{
Console.WriteLine("Test3_testcase 34 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test3_op1 / d_test3_f("test3_op2")))
{
Console.WriteLine("Test3_testcase 35 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test3_op1 / cl1.d_cl_test3_op2))
{
Console.WriteLine("Test3_testcase 36 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test3_op1 / vt1.d_vt_test3_op2))
{
Console.WriteLine("Test3_testcase 37 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test3_op1 / d_arr1d_test3_op2[0]))
{
Console.WriteLine("Test3_testcase 38 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test3_op1 / d_arr2d_test3_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test3_testcase 39 failed");
passed = false;
}
if (!Double.IsNaN(vt1.d_vt_test3_op1 / d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test3_testcase 40 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test3_op1[1] / d_l_test3_op2))
{
Console.WriteLine("Test3_testcase 41 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test3_op1[1] / d_s_test3_op2))
{
Console.WriteLine("Test3_testcase 42 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test3_op1[1] / d_test3_f("test3_op2")))
{
Console.WriteLine("Test3_testcase 43 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test3_op1[1] / cl1.d_cl_test3_op2))
{
Console.WriteLine("Test3_testcase 44 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test3_op1[1] / vt1.d_vt_test3_op2))
{
Console.WriteLine("Test3_testcase 45 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test3_op1[1] / d_arr1d_test3_op2[0]))
{
Console.WriteLine("Test3_testcase 46 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test3_op1[1] / d_arr2d_test3_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test3_testcase 47 failed");
passed = false;
}
if (!Double.IsNaN(d_arr1d_test3_op1[1] / d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test3_testcase 48 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] / d_l_test3_op2))
{
Console.WriteLine("Test3_testcase 49 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] / d_s_test3_op2))
{
Console.WriteLine("Test3_testcase 50 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] / d_test3_f("test3_op2")))
{
Console.WriteLine("Test3_testcase 51 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] / cl1.d_cl_test3_op2))
{
Console.WriteLine("Test3_testcase 52 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] / vt1.d_vt_test3_op2))
{
Console.WriteLine("Test3_testcase 53 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] / d_arr1d_test3_op2[0]))
{
Console.WriteLine("Test3_testcase 54 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] / d_arr2d_test3_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test3_testcase 55 failed");
passed = false;
}
if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] / d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test3_testcase 56 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] / d_l_test3_op2))
{
Console.WriteLine("Test3_testcase 57 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] / d_s_test3_op2))
{
Console.WriteLine("Test3_testcase 58 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] / d_test3_f("test3_op2")))
{
Console.WriteLine("Test3_testcase 59 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] / cl1.d_cl_test3_op2))
{
Console.WriteLine("Test3_testcase 60 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] / vt1.d_vt_test3_op2))
{
Console.WriteLine("Test3_testcase 61 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] / d_arr1d_test3_op2[0]))
{
Console.WriteLine("Test3_testcase 62 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] / d_arr2d_test3_op2[index[0, 1], index[1, 0]]))
{
Console.WriteLine("Test3_testcase 63 failed");
passed = false;
}
if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] / d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]]))
{
Console.WriteLine("Test3_testcase 64 failed");
passed = false;
}
}
if (!passed)
{
Console.WriteLine("FAILED");
return 1;
}
else
{
Console.WriteLine("PASSED");
return 100;
}
}
}
| |
//------------------------------------------------------------------------------
// <license file="Decompiler.cs">
//
// The use and distribution terms for this software are contained in the file
// named 'LICENSE', which can be found in the resources directory of this
// distribution.
//
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// </license>
//------------------------------------------------------------------------------
using System;
using EcmaScript.NET.Collections;
namespace EcmaScript.NET
{
/// <summary> The following class save decompilation information about the source.
/// Source information is returned from the parser as a String
/// associated with function nodes and with the toplevel script. When
/// saved in the constant pool of a class, this string will be UTF-8
/// encoded, and token values will occupy a single byte.
/// Source is saved (mostly) as token numbers. The tokens saved pretty
/// much correspond to the token stream of a 'canonical' representation
/// of the input program, as directed by the parser. (There were a few
/// cases where tokens could have been left out where decompiler could
/// easily reconstruct them, but I left them in for clarity). (I also
/// looked adding source collection to TokenStream instead, where I
/// could have limited the changes to a few lines in getToken... but
/// this wouldn't have saved any space in the resulting source
/// representation, and would have meant that I'd have to duplicate
/// parser logic in the decompiler to disambiguate situations where
/// newlines are important.) The function decompile expands the
/// tokens back into their string representations, using simple
/// lookahead to correct spacing and indentation.
///
/// Assignments are saved as two-token pairs (Token.ASSIGN, op). Number tokens
/// are stored inline, as a NUMBER token, a character representing the type, and
/// either 1 or 4 characters representing the bit-encoding of the number. String
/// types NAME, STRING and OBJECT are currently stored as a token type,
/// followed by a character giving the length of the string (assumed to
/// be less than 2^16), followed by the characters of the string
/// inlined into the source string. Changing this to some reference to
/// to the string in the compiled class' constant pool would probably
/// save a lot of space... but would require some method of deriving
/// the final constant pool entry from information available at parse
/// time.
/// </summary>
public class Decompiler
{
internal string EncodedSource
{
get
{
return SourceToString(0);
}
}
internal int CurrentOffset
{
get
{
return sourceTop;
}
}
/// <summary> Flag to indicate that the decompilation should omit the
/// function header and trailing brace.
/// </summary>
public const int ONLY_BODY_FLAG = 1 << 0;
/// <summary> Flag to indicate that the decompilation generates toSource result.</summary>
public const int TO_SOURCE_FLAG = 1 << 1;
public const int TO_STRING_FLAG = 1 << 2;
/// <summary> Decompilation property to specify initial ident value.</summary>
public const int INITIAL_INDENT_PROP = 1;
/// <summary> Decompilation property to specify default identation offset.</summary>
public const int INDENT_GAP_PROP = 2;
/// <summary> Decompilation property to specify identation offset for case labels.</summary>
public const int CASE_GAP_PROP = 3;
// Marker to denote the last RC of function so it can be distinguished from
// the last RC of object literals in case of function expressions
private const int FUNCTION_END = 147;
internal int MarkFunctionStart(int functionType)
{
int savedOffset = CurrentOffset;
AddToken(Token.FUNCTION);
Append((char)functionType);
return savedOffset;
}
internal int MarkFunctionEnd(int functionStart)
{
int offset = CurrentOffset;
Append((char)FUNCTION_END);
return offset;
}
internal void AddToken(int token)
{
if (!(0 <= token && token <= Token.LAST_TOKEN))
throw new ArgumentException();
Append((char)token);
}
internal void AddEol(int token)
{
if (!(0 <= token && token <= Token.LAST_TOKEN))
throw new ArgumentException();
Append((char)token);
Append((char)Token.EOL);
}
internal void AddName(string str)
{
AddToken(Token.NAME);
AppendString(str);
}
internal void AddString(string str)
{
AddToken(Token.STRING);
AppendString(str);
}
internal void AddRegexp(string regexp, string flags)
{
AddToken(Token.REGEXP);
AppendString('/' + regexp + '/' + flags);
}
internal void AddJScriptConditionalComment(String str)
{
AddToken(Token.CONDCOMMENT);
AppendString(str);
}
internal void AddPreservedComment(String str)
{
AddToken(Token.KEEPCOMMENT);
AppendString(str);
}
internal void AddNumber(double n)
{
AddToken(Token.NUMBER);
/* encode the number in the source stream.
* Save as NUMBER type (char | char char char char)
* where type is
* 'D' - double, 'S' - short, 'J' - long.
* We need to retain float vs. integer type info to keep the
* behavior of liveconnect type-guessing the same after
* decompilation. (Liveconnect tries to present 1.0 to Java
* as a float/double)
* OPT: This is no longer true. We could compress the format.
* This may not be the most space-efficient encoding;
* the chars created below may take up to 3 bytes in
* constant pool UTF-8 encoding, so a Double could take
* up to 12 bytes.
*/
long lbits = (long)n;
if (lbits != n)
{
// if it's floating point, save as a Double bit pattern.
// (12/15/97 our scanner only returns Double for f.p.)
lbits = BitConverter.DoubleToInt64Bits(n);
Append('D');
Append((char)(lbits >> 48));
Append((char)(lbits >> 32));
Append((char)(lbits >> 16));
Append((char)lbits);
}
else
{
// we can ignore negative values, bc they're already prefixed
// by NEG
if (lbits < 0)
Context.CodeBug();
// will it fit in a char?
// this gives a short encoding for integer values up to 2^16.
if (lbits <= char.MaxValue)
{
Append('S');
Append((char)lbits);
}
else
{
// Integral, but won't fit in a char. Store as a long.
Append('J');
Append((char)(lbits >> 48));
Append((char)(lbits >> 32));
Append((char)(lbits >> 16));
Append((char)lbits);
}
}
}
private void AppendString(string str)
{
int L = str.Length;
int lengthEncodingSize = 1;
if (L >= 0x8000)
{
lengthEncodingSize = 2;
}
int nextTop = sourceTop + lengthEncodingSize + L;
if (nextTop > sourceBuffer.Length)
{
IncreaseSourceCapacity(nextTop);
}
if (L >= 0x8000)
{
// Use 2 chars to encode strings exceeding 32K, were the highest
// bit in the first char indicates presence of the next byte
sourceBuffer[sourceTop] = (char)(0x8000 | (int)((uint)L >> 16));
++sourceTop;
}
sourceBuffer[sourceTop] = (char)L;
++sourceTop;
str.ToCharArray(0, L).CopyTo(sourceBuffer, sourceTop);
sourceTop = nextTop;
}
private void Append(char c)
{
if (sourceTop == sourceBuffer.Length)
{
IncreaseSourceCapacity(sourceTop + 1);
}
sourceBuffer[sourceTop] = c;
++sourceTop;
}
private void IncreaseSourceCapacity(int minimalCapacity)
{
// Call this only when capacity increase is must
if (minimalCapacity <= sourceBuffer.Length)
Context.CodeBug();
int newCapacity = sourceBuffer.Length * 2;
if (newCapacity < minimalCapacity)
{
newCapacity = minimalCapacity;
}
char[] tmp = new char[newCapacity];
Array.Copy(sourceBuffer, 0, tmp, 0, sourceTop);
sourceBuffer = tmp;
}
private string SourceToString(int offset)
{
if (offset < 0 || sourceTop < offset)
Context.CodeBug();
return new string(sourceBuffer, offset, sourceTop - offset);
}
/// <summary> Decompile the source information associated with this js
/// function/script back into a string. For the most part, this
/// just means translating tokens back to their string
/// representations; there's a little bit of lookahead logic to
/// decide the proper spacing/indentation. Most of the work in
/// mapping the original source to the prettyprinted decompiled
/// version is done by the parser.
///
/// </summary>
/// <param name="source">encoded source tree presentation
///
/// </param>
/// <param name="flags">flags to select output format
///
/// </param>
/// <param name="properties">indentation properties
///
/// </param>
public static string Decompile(string source, int flags, UintMap properties)
{
int length = source.Length;
if (length == 0)
{
return "";
}
int indent = properties.getInt(INITIAL_INDENT_PROP, 0);
if (indent < 0)
throw new ArgumentException();
int indentGap = properties.getInt(INDENT_GAP_PROP, 4);
if (indentGap < 0)
throw new ArgumentException();
int caseGap = properties.getInt(CASE_GAP_PROP, 2);
if (caseGap < 0)
throw new ArgumentException();
System.Text.StringBuilder result = new System.Text.StringBuilder();
bool justFunctionBody = (0 != (flags & Decompiler.ONLY_BODY_FLAG));
bool toSource = (0 != (flags & Decompiler.TO_SOURCE_FLAG));
bool toString = (0 != (flags & Decompiler.TO_STRING_FLAG));
// Spew tokens in source, for debugging.
// as TYPE number char
if (printSource)
{
System.Console.Error.WriteLine("length:" + length);
for (int i = 0; i < length; ++i)
{
// Note that tokenToName will fail unless Context.printTrees
// is true.
string tokenname = null;
if (Token.printNames)
{
tokenname = Token.name(source[i]);
}
if (tokenname == null)
{
tokenname = "---";
}
string pad = tokenname.Length > 7 ? "\t" : "\t\t";
System.Console.Error.WriteLine(tokenname + pad + (int)source[i] + "\t'" + ScriptRuntime.escapeString(source.Substring(i, (i + 1) - (i))) + "'");
}
System.Console.Error.WriteLine();
}
int braceNesting = 0;
bool afterFirstEOL = false;
int i2 = 0;
int topFunctionType;
if (source[i2] == Token.SCRIPT)
{
++i2;
topFunctionType = -1;
}
else
{
topFunctionType = source[i2 + 1];
}
if (!toSource)
{
if (!toString)
{
// add an initial newline to exactly match js.
result.Append('\n');
}
for (int j = 0; j < indent; j++)
result.Append(' ');
}
else
{
if (topFunctionType == FunctionNode.FUNCTION_EXPRESSION)
{
result.Append('(');
}
}
while (i2 < length)
{
switch (source[i2])
{
case (char)(Token.NAME):
case (char)(Token.REGEXP): // re-wrapped in '/'s in parser...
i2 = PrintSourceString(source, i2 + 1, false, result);
continue;
case (char)(Token.STRING):
i2 = PrintSourceString(source, i2 + 1, true, result);
continue;
case (char)(Token.NUMBER):
i2 = PrintSourceNumber(source, i2 + 1, result);
continue;
case (char)(Token.TRUE):
result.Append("true");
break;
case (char)(Token.FALSE):
result.Append("false");
break;
case (char)(Token.NULL):
result.Append("null");
break;
case (char)(Token.THIS):
result.Append("this");
break;
case (char)(Token.FUNCTION):
++i2; // skip function type
result.Append("function ");
break;
case (char)(FUNCTION_END):
// Do nothing
break;
case (char)(Token.COMMA):
result.Append(", ");
break;
case (char)(Token.LC):
++braceNesting;
if (Token.EOL == GetNext(source, length, i2))
indent += indentGap;
result.Append('{');
break;
case (char)(Token.RC):
{
--braceNesting;
/* don't print the closing RC if it closes the
* toplevel function and we're called from
* decompileFunctionBody.
*/
if (justFunctionBody && braceNesting == 0)
break;
result.Append('}');
switch (GetNext(source, length, i2))
{
case Token.EOL:
case FUNCTION_END:
indent -= indentGap;
break;
case Token.WHILE:
case Token.ELSE:
indent -= indentGap;
result.Append(' ');
break;
}
break;
}
case (char)(Token.LP):
result.Append('(');
break;
case (char)(Token.RP):
result.Append(')');
if (Token.LC == GetNext(source, length, i2))
result.Append(' ');
break;
case (char)(Token.LB):
result.Append('[');
break;
case (char)(Token.RB):
result.Append(']');
break;
case (char)(Token.EOL):
{
if (toSource)
break;
bool newLine = true;
if (!afterFirstEOL)
{
afterFirstEOL = true;
if (justFunctionBody)
{
/* throw away just added 'function name(...) {'
* and restore the original indent
*/
result.Length = 0;
indent -= indentGap;
newLine = false;
}
}
if (newLine)
{
result.Append('\n');
}
/* add indent if any tokens remain,
* less setback if next token is
* a label, case or default.
*/
if (i2 + 1 < length)
{
int less = 0;
int nextToken = source[i2 + 1];
if (nextToken == Token.CASE || nextToken == Token.DEFAULT)
{
less = indentGap - caseGap;
}
else if (nextToken == Token.RC)
{
less = indentGap;
}
/* elaborate check against label... skip past a
* following inlined NAME and look for a COLON.
*/
else if (nextToken == Token.NAME)
{
int afterName = GetSourceStringEnd(source, i2 + 2);
if (source[afterName] == Token.COLON)
less = indentGap;
}
for (; less < indent; less++)
result.Append(' ');
}
break;
}
case (char)(Token.DOT):
result.Append('.');
break;
case (char)(Token.NEW):
result.Append("new ");
break;
case (char)(Token.DELPROP):
result.Append("delete ");
break;
case (char)(Token.IF):
result.Append("if ");
break;
case (char)(Token.ELSE):
result.Append("else ");
break;
case (char)(Token.FOR):
result.Append("for ");
break;
case (char)(Token.IN):
result.Append(" in ");
break;
case (char)(Token.WITH):
result.Append("with ");
break;
case (char)(Token.WHILE):
result.Append("while ");
break;
case (char)(Token.DO):
result.Append("do ");
break;
case (char)(Token.TRY):
result.Append("try ");
break;
case (char)(Token.CATCH):
result.Append("catch ");
break;
case (char)(Token.FINALLY):
result.Append("finally ");
break;
case (char)(Token.THROW):
result.Append("throw ");
break;
case (char)(Token.SWITCH):
result.Append("switch ");
break;
case (char)(Token.BREAK):
result.Append("break");
if (Token.NAME == GetNext(source, length, i2))
result.Append(' ');
break;
case (char)(Token.CONTINUE):
result.Append("continue");
if (Token.NAME == GetNext(source, length, i2))
result.Append(' ');
break;
case (char)(Token.CASE):
result.Append("case ");
break;
case (char)(Token.DEFAULT):
result.Append("default");
break;
case (char)(Token.RETURN):
result.Append("return");
if (Token.SEMI != GetNext(source, length, i2))
result.Append(' ');
break;
case (char)(Token.VAR):
result.Append("var ");
break;
case (char)(Token.SEMI):
result.Append(';');
if (Token.EOL != GetNext(source, length, i2))
{
// separators in FOR
result.Append(' ');
}
break;
case (char)(Token.ASSIGN):
result.Append(" = ");
break;
case (char)(Token.ASSIGN_ADD):
result.Append(" += ");
break;
case (char)(Token.ASSIGN_SUB):
result.Append(" -= ");
break;
case (char)(Token.ASSIGN_MUL):
result.Append(" *= ");
break;
case (char)(Token.ASSIGN_DIV):
result.Append(" /= ");
break;
case (char)(Token.ASSIGN_MOD):
result.Append(" %= ");
break;
case (char)(Token.ASSIGN_BITOR):
result.Append(" |= ");
break;
case (char)(Token.ASSIGN_BITXOR):
result.Append(" ^= ");
break;
case (char)(Token.ASSIGN_BITAND):
result.Append(" &= ");
break;
case (char)(Token.ASSIGN_LSH):
result.Append(" <<= ");
break;
case (char)(Token.ASSIGN_RSH):
result.Append(" >>= ");
break;
case (char)(Token.ASSIGN_URSH):
result.Append(" >>>= ");
break;
case (char)(Token.HOOK):
result.Append(" ? ");
break;
case (char)(Token.OBJECTLIT):
// pun OBJECTLIT to mean colon in objlit property
// initialization.
// This needs to be distinct from COLON in the general case
// to distinguish from the colon in a ternary... which needs
// different spacing.
result.Append(':');
break;
case (char)(Token.COLON):
if (Token.EOL == GetNext(source, length, i2))
// it's the end of a label
result.Append(':');
// it's the middle part of a ternary
else
result.Append(" : ");
break;
case (char)(Token.OR):
result.Append(" || ");
break;
case (char)(Token.AND):
result.Append(" && ");
break;
case (char)(Token.BITOR):
result.Append(" | ");
break;
case (char)(Token.BITXOR):
result.Append(" ^ ");
break;
case (char)(Token.BITAND):
result.Append(" & ");
break;
case (char)(Token.SHEQ):
result.Append(" === ");
break;
case (char)(Token.SHNE):
result.Append(" !== ");
break;
case (char)(Token.EQ):
result.Append(" == ");
break;
case (char)(Token.NE):
result.Append(" != ");
break;
case (char)(Token.LE):
result.Append(" <= ");
break;
case (char)(Token.LT):
result.Append(" < ");
break;
case (char)(Token.GE):
result.Append(" >= ");
break;
case (char)(Token.GT):
result.Append(" > ");
break;
case (char)(Token.INSTANCEOF):
result.Append(" instanceof ");
break;
case (char)(Token.LSH):
result.Append(" << ");
break;
case (char)(Token.RSH):
result.Append(" >> ");
break;
case (char)(Token.URSH):
result.Append(" >>> ");
break;
case (char)(Token.TYPEOF):
result.Append("typeof ");
break;
case (char)(Token.VOID):
result.Append("void ");
break;
case (char)(Token.NOT):
result.Append('!');
break;
case (char)(Token.BITNOT):
result.Append('~');
break;
case (char)(Token.POS):
result.Append('+');
break;
case (char)(Token.NEG):
result.Append('-');
break;
case (char)(Token.INC):
result.Append("++");
break;
case (char)(Token.DEC):
result.Append("--");
break;
case (char)(Token.ADD):
result.Append(" + ");
break;
case (char)(Token.SUB):
result.Append(" - ");
break;
case (char)(Token.MUL):
result.Append(" * ");
break;
case (char)(Token.DIV):
result.Append(" / ");
break;
case (char)(Token.MOD):
result.Append(" % ");
break;
case (char)(Token.COLONCOLON):
result.Append("::");
break;
case (char)(Token.DOTDOT):
result.Append("..");
break;
case (char)(Token.DOTQUERY):
result.Append(".(");
break;
case (char)(Token.XMLATTR):
result.Append('@');
break;
default:
// If we don't know how to decompile it, raise an exception.
throw new ApplicationException();
}
++i2;
}
if (!toSource)
{
// add that trailing newline if it's an outermost function.
if (!justFunctionBody && !toString)
result.Append('\n');
}
else
{
if (topFunctionType == FunctionNode.FUNCTION_EXPRESSION)
{
result.Append(')');
}
}
return result.ToString();
}
private static int GetNext(string source, int length, int i)
{
return (i + 1 < length) ? source[i + 1] : Token.EOF;
}
private static int GetSourceStringEnd(string source, int offset)
{
return PrintSourceString(source, offset, false, null);
}
private static int PrintSourceString(string source, int offset, bool asQuotedString, System.Text.StringBuilder sb)
{
int length = source[offset];
++offset;
if ((0x8000 & length) != 0)
{
length = ((0x7FFF & length) << 16) | source[offset];
++offset;
}
if (sb != null)
{
string str = source.Substring(offset, (offset + length) - (offset));
if (!asQuotedString)
{
sb.Append(str);
}
else
{
sb.Append('"');
sb.Append(ScriptRuntime.escapeString(str));
sb.Append('"');
}
}
return offset + length;
}
private static int PrintSourceNumber(string source, int offset, System.Text.StringBuilder sb)
{
double number = 0.0;
char type = source[offset];
++offset;
if (type == 'S')
{
if (sb != null)
{
int ival = source[offset];
number = ival;
}
++offset;
}
else if (type == 'J' || type == 'D')
{
if (sb != null)
{
long lbits;
lbits = (long)source[offset] << 48;
lbits |= (long)source[offset + 1] << 32;
lbits |= (long)source[offset + 2] << 16;
lbits |= (long)source[offset + 3];
if (type == 'J')
{
number = lbits;
}
else
{
number = BitConverter.Int64BitsToDouble(lbits);
}
}
offset += 4;
}
else
{
// Bad source
throw new ApplicationException();
}
if (sb != null)
{
sb.Append(ScriptConvert.ToString(number, 10));
}
return offset;
}
private char[] sourceBuffer = new char[128];
// Per script/function source buffer top: parent source does not include a
// nested functions source and uses function index as a reference instead.
private int sourceTop;
// whether to do a debug print of the source information, when decompiling.
private static bool printSource = false; // TODO: make preprocessor directive
}
}
| |
using System;
using System.Data;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using PCSComUtils.Common;
using PCSComUtils.PCSExc;
using PCSUtils.Log;
using PCSUtils.Utils;
namespace PCSMaterials.ActualCost
{
/// <summary>
/// Summary description for NotSetupSTDItems.
/// </summary>
public class NotSetupSTDItems : System.Windows.Forms.Form
{
private System.Windows.Forms.Label lblMessage;
private System.Windows.Forms.Button btnClose;
private C1.Win.C1TrueDBGrid.C1TrueDBGrid dgrdData;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
const string THIS = "PCSMaterials.ActualCost.NotSetupSTDItems";
private DataTable m_dtbNotSTDCost;
public NotSetupSTDItems(DataTable pdtbNotSTDCost) : this ()
{
m_dtbNotSTDCost = pdtbNotSTDCost;
}
public NotSetupSTDItems()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <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 Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(NotSetupSTDItems));
this.lblMessage = new System.Windows.Forms.Label();
this.btnClose = new System.Windows.Forms.Button();
this.dgrdData = new C1.Win.C1TrueDBGrid.C1TrueDBGrid();
((System.ComponentModel.ISupportInitialize)(this.dgrdData)).BeginInit();
this.SuspendLayout();
//
// lblMessage
//
this.lblMessage.AccessibleDescription = resources.GetString("lblMessage.AccessibleDescription");
this.lblMessage.AccessibleName = resources.GetString("lblMessage.AccessibleName");
this.lblMessage.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("lblMessage.Anchor")));
this.lblMessage.AutoSize = ((bool)(resources.GetObject("lblMessage.AutoSize")));
this.lblMessage.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("lblMessage.Dock")));
this.lblMessage.Enabled = ((bool)(resources.GetObject("lblMessage.Enabled")));
this.lblMessage.Font = ((System.Drawing.Font)(resources.GetObject("lblMessage.Font")));
this.lblMessage.Image = ((System.Drawing.Image)(resources.GetObject("lblMessage.Image")));
this.lblMessage.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("lblMessage.ImageAlign")));
this.lblMessage.ImageIndex = ((int)(resources.GetObject("lblMessage.ImageIndex")));
this.lblMessage.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("lblMessage.ImeMode")));
this.lblMessage.Location = ((System.Drawing.Point)(resources.GetObject("lblMessage.Location")));
this.lblMessage.Name = "lblMessage";
this.lblMessage.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("lblMessage.RightToLeft")));
this.lblMessage.Size = ((System.Drawing.Size)(resources.GetObject("lblMessage.Size")));
this.lblMessage.TabIndex = ((int)(resources.GetObject("lblMessage.TabIndex")));
this.lblMessage.Text = resources.GetString("lblMessage.Text");
this.lblMessage.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("lblMessage.TextAlign")));
this.lblMessage.Visible = ((bool)(resources.GetObject("lblMessage.Visible")));
//
// btnClose
//
this.btnClose.AccessibleDescription = resources.GetString("btnClose.AccessibleDescription");
this.btnClose.AccessibleName = resources.GetString("btnClose.AccessibleName");
this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("btnClose.Anchor")));
this.btnClose.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnClose.BackgroundImage")));
this.btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnClose.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("btnClose.Dock")));
this.btnClose.Enabled = ((bool)(resources.GetObject("btnClose.Enabled")));
this.btnClose.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("btnClose.FlatStyle")));
this.btnClose.Font = ((System.Drawing.Font)(resources.GetObject("btnClose.Font")));
this.btnClose.Image = ((System.Drawing.Image)(resources.GetObject("btnClose.Image")));
this.btnClose.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnClose.ImageAlign")));
this.btnClose.ImageIndex = ((int)(resources.GetObject("btnClose.ImageIndex")));
this.btnClose.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("btnClose.ImeMode")));
this.btnClose.Location = ((System.Drawing.Point)(resources.GetObject("btnClose.Location")));
this.btnClose.Name = "btnClose";
this.btnClose.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("btnClose.RightToLeft")));
this.btnClose.Size = ((System.Drawing.Size)(resources.GetObject("btnClose.Size")));
this.btnClose.TabIndex = ((int)(resources.GetObject("btnClose.TabIndex")));
this.btnClose.Text = resources.GetString("btnClose.Text");
this.btnClose.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnClose.TextAlign")));
this.btnClose.Visible = ((bool)(resources.GetObject("btnClose.Visible")));
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
//
// dgrdData
//
this.dgrdData.AccessibleDescription = resources.GetString("dgrdData.AccessibleDescription");
this.dgrdData.AccessibleName = resources.GetString("dgrdData.AccessibleName");
this.dgrdData.AllowAddNew = ((bool)(resources.GetObject("dgrdData.AllowAddNew")));
this.dgrdData.AllowArrows = ((bool)(resources.GetObject("dgrdData.AllowArrows")));
this.dgrdData.AllowColMove = ((bool)(resources.GetObject("dgrdData.AllowColMove")));
this.dgrdData.AllowColSelect = ((bool)(resources.GetObject("dgrdData.AllowColSelect")));
this.dgrdData.AllowDelete = ((bool)(resources.GetObject("dgrdData.AllowDelete")));
this.dgrdData.AllowDrag = ((bool)(resources.GetObject("dgrdData.AllowDrag")));
this.dgrdData.AllowFilter = ((bool)(resources.GetObject("dgrdData.AllowFilter")));
this.dgrdData.AllowHorizontalSplit = ((bool)(resources.GetObject("dgrdData.AllowHorizontalSplit")));
this.dgrdData.AllowRowSelect = ((bool)(resources.GetObject("dgrdData.AllowRowSelect")));
this.dgrdData.AllowSort = ((bool)(resources.GetObject("dgrdData.AllowSort")));
this.dgrdData.AllowUpdate = ((bool)(resources.GetObject("dgrdData.AllowUpdate")));
this.dgrdData.AllowUpdateOnBlur = ((bool)(resources.GetObject("dgrdData.AllowUpdateOnBlur")));
this.dgrdData.AllowVerticalSplit = ((bool)(resources.GetObject("dgrdData.AllowVerticalSplit")));
this.dgrdData.AlternatingRows = ((bool)(resources.GetObject("dgrdData.AlternatingRows")));
this.dgrdData.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("dgrdData.Anchor")));
this.dgrdData.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("dgrdData.BackgroundImage")));
this.dgrdData.BorderStyle = ((System.Windows.Forms.BorderStyle)(resources.GetObject("dgrdData.BorderStyle")));
this.dgrdData.Caption = resources.GetString("dgrdData.Caption");
this.dgrdData.CaptionHeight = ((int)(resources.GetObject("dgrdData.CaptionHeight")));
this.dgrdData.CellTipsDelay = ((int)(resources.GetObject("dgrdData.CellTipsDelay")));
this.dgrdData.CellTipsWidth = ((int)(resources.GetObject("dgrdData.CellTipsWidth")));
this.dgrdData.ChildGrid = ((C1.Win.C1TrueDBGrid.C1TrueDBGrid)(resources.GetObject("dgrdData.ChildGrid")));
this.dgrdData.CollapseColor = ((System.Drawing.Color)(resources.GetObject("dgrdData.CollapseColor")));
this.dgrdData.ColumnFooters = ((bool)(resources.GetObject("dgrdData.ColumnFooters")));
this.dgrdData.ColumnHeaders = ((bool)(resources.GetObject("dgrdData.ColumnHeaders")));
this.dgrdData.DefColWidth = ((int)(resources.GetObject("dgrdData.DefColWidth")));
this.dgrdData.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("dgrdData.Dock")));
this.dgrdData.EditDropDown = ((bool)(resources.GetObject("dgrdData.EditDropDown")));
this.dgrdData.EmptyRows = ((bool)(resources.GetObject("dgrdData.EmptyRows")));
this.dgrdData.Enabled = ((bool)(resources.GetObject("dgrdData.Enabled")));
this.dgrdData.ExpandColor = ((System.Drawing.Color)(resources.GetObject("dgrdData.ExpandColor")));
this.dgrdData.ExposeCellMode = ((C1.Win.C1TrueDBGrid.ExposeCellModeEnum)(resources.GetObject("dgrdData.ExposeCellMode")));
this.dgrdData.ExtendRightColumn = ((bool)(resources.GetObject("dgrdData.ExtendRightColumn")));
this.dgrdData.FetchRowStyles = ((bool)(resources.GetObject("dgrdData.FetchRowStyles")));
this.dgrdData.FilterBar = ((bool)(resources.GetObject("dgrdData.FilterBar")));
this.dgrdData.FlatStyle = ((C1.Win.C1TrueDBGrid.FlatModeEnum)(resources.GetObject("dgrdData.FlatStyle")));
this.dgrdData.Font = ((System.Drawing.Font)(resources.GetObject("dgrdData.Font")));
this.dgrdData.GroupByAreaVisible = ((bool)(resources.GetObject("dgrdData.GroupByAreaVisible")));
this.dgrdData.GroupByCaption = resources.GetString("dgrdData.GroupByCaption");
this.dgrdData.Images.Add(((System.Drawing.Image)(resources.GetObject("resource"))));
this.dgrdData.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("dgrdData.ImeMode")));
this.dgrdData.LinesPerRow = ((int)(resources.GetObject("dgrdData.LinesPerRow")));
this.dgrdData.Location = ((System.Drawing.Point)(resources.GetObject("dgrdData.Location")));
this.dgrdData.MarqueeStyle = C1.Win.C1TrueDBGrid.MarqueeEnum.DottedCellBorder;
this.dgrdData.MultiSelect = C1.Win.C1TrueDBGrid.MultiSelectEnum.None;
this.dgrdData.Name = "dgrdData";
this.dgrdData.PictureAddnewRow = ((System.Drawing.Image)(resources.GetObject("dgrdData.PictureAddnewRow")));
this.dgrdData.PictureCurrentRow = ((System.Drawing.Image)(resources.GetObject("dgrdData.PictureCurrentRow")));
this.dgrdData.PictureFilterBar = ((System.Drawing.Image)(resources.GetObject("dgrdData.PictureFilterBar")));
this.dgrdData.PictureFooterRow = ((System.Drawing.Image)(resources.GetObject("dgrdData.PictureFooterRow")));
this.dgrdData.PictureHeaderRow = ((System.Drawing.Image)(resources.GetObject("dgrdData.PictureHeaderRow")));
this.dgrdData.PictureModifiedRow = ((System.Drawing.Image)(resources.GetObject("dgrdData.PictureModifiedRow")));
this.dgrdData.PictureStandardRow = ((System.Drawing.Image)(resources.GetObject("dgrdData.PictureStandardRow")));
this.dgrdData.PreviewInfo.AllowSizing = ((bool)(resources.GetObject("dgrdData.PreviewInfo.AllowSizing")));
this.dgrdData.PreviewInfo.Caption = resources.GetString("dgrdData.PreviewInfo.Caption");
this.dgrdData.PreviewInfo.Location = ((System.Drawing.Point)(resources.GetObject("dgrdData.PreviewInfo.Location")));
this.dgrdData.PreviewInfo.Size = ((System.Drawing.Size)(resources.GetObject("dgrdData.PreviewInfo.Size")));
this.dgrdData.PreviewInfo.ToolBars = ((bool)(resources.GetObject("dgrdData.PreviewInfo.ToolBars")));
this.dgrdData.PreviewInfo.UIStrings.Content = ((string[])(resources.GetObject("dgrdData.PreviewInfo.UIStrings.Content")));
this.dgrdData.PreviewInfo.ZoomFactor = ((System.Double)(resources.GetObject("dgrdData.PreviewInfo.ZoomFactor")));
this.dgrdData.PrintInfo.MaxRowHeight = ((int)(resources.GetObject("dgrdData.PrintInfo.MaxRowHeight")));
this.dgrdData.PrintInfo.OwnerDrawPageFooter = ((bool)(resources.GetObject("dgrdData.PrintInfo.OwnerDrawPageFooter")));
this.dgrdData.PrintInfo.OwnerDrawPageHeader = ((bool)(resources.GetObject("dgrdData.PrintInfo.OwnerDrawPageHeader")));
this.dgrdData.PrintInfo.PageFooter = resources.GetString("dgrdData.PrintInfo.PageFooter");
this.dgrdData.PrintInfo.PageFooterHeight = ((int)(resources.GetObject("dgrdData.PrintInfo.PageFooterHeight")));
this.dgrdData.PrintInfo.PageHeader = resources.GetString("dgrdData.PrintInfo.PageHeader");
this.dgrdData.PrintInfo.PageHeaderHeight = ((int)(resources.GetObject("dgrdData.PrintInfo.PageHeaderHeight")));
this.dgrdData.PrintInfo.PrintHorizontalSplits = ((bool)(resources.GetObject("dgrdData.PrintInfo.PrintHorizontalSplits")));
this.dgrdData.PrintInfo.ProgressCaption = resources.GetString("dgrdData.PrintInfo.ProgressCaption");
this.dgrdData.PrintInfo.RepeatColumnFooters = ((bool)(resources.GetObject("dgrdData.PrintInfo.RepeatColumnFooters")));
this.dgrdData.PrintInfo.RepeatColumnHeaders = ((bool)(resources.GetObject("dgrdData.PrintInfo.RepeatColumnHeaders")));
this.dgrdData.PrintInfo.RepeatGridHeader = ((bool)(resources.GetObject("dgrdData.PrintInfo.RepeatGridHeader")));
this.dgrdData.PrintInfo.RepeatSplitHeaders = ((bool)(resources.GetObject("dgrdData.PrintInfo.RepeatSplitHeaders")));
this.dgrdData.PrintInfo.ShowOptionsDialog = ((bool)(resources.GetObject("dgrdData.PrintInfo.ShowOptionsDialog")));
this.dgrdData.PrintInfo.ShowProgressForm = ((bool)(resources.GetObject("dgrdData.PrintInfo.ShowProgressForm")));
this.dgrdData.PrintInfo.ShowSelection = ((bool)(resources.GetObject("dgrdData.PrintInfo.ShowSelection")));
this.dgrdData.PrintInfo.UseGridColors = ((bool)(resources.GetObject("dgrdData.PrintInfo.UseGridColors")));
this.dgrdData.RecordSelectors = ((bool)(resources.GetObject("dgrdData.RecordSelectors")));
this.dgrdData.RecordSelectorWidth = ((int)(resources.GetObject("dgrdData.RecordSelectorWidth")));
this.dgrdData.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("dgrdData.RightToLeft")));
this.dgrdData.RowDivider.Color = ((System.Drawing.Color)(resources.GetObject("resource.Color")));
this.dgrdData.RowDivider.Style = ((C1.Win.C1TrueDBGrid.LineStyleEnum)(resources.GetObject("resource.Style")));
this.dgrdData.RowHeight = ((int)(resources.GetObject("dgrdData.RowHeight")));
this.dgrdData.RowSubDividerColor = ((System.Drawing.Color)(resources.GetObject("dgrdData.RowSubDividerColor")));
this.dgrdData.ScrollTips = ((bool)(resources.GetObject("dgrdData.ScrollTips")));
this.dgrdData.ScrollTrack = ((bool)(resources.GetObject("dgrdData.ScrollTrack")));
this.dgrdData.Size = ((System.Drawing.Size)(resources.GetObject("dgrdData.Size")));
this.dgrdData.SpringMode = ((bool)(resources.GetObject("dgrdData.SpringMode")));
this.dgrdData.TabAcrossSplits = ((bool)(resources.GetObject("dgrdData.TabAcrossSplits")));
this.dgrdData.TabIndex = ((int)(resources.GetObject("dgrdData.TabIndex")));
this.dgrdData.Text = resources.GetString("dgrdData.Text");
this.dgrdData.ViewCaptionWidth = ((int)(resources.GetObject("dgrdData.ViewCaptionWidth")));
this.dgrdData.ViewColumnWidth = ((int)(resources.GetObject("dgrdData.ViewColumnWidth")));
this.dgrdData.Visible = ((bool)(resources.GetObject("dgrdData.Visible")));
this.dgrdData.WrapCellPointer = ((bool)(resources.GetObject("dgrdData.WrapCellPointer")));
this.dgrdData.PropBag = resources.GetString("dgrdData.PropBag");
//
// NotSetupSTDItems
//
this.AccessibleDescription = resources.GetString("$this.AccessibleDescription");
this.AccessibleName = resources.GetString("$this.AccessibleName");
this.AutoScaleBaseSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScaleBaseSize")));
this.AutoScroll = ((bool)(resources.GetObject("$this.AutoScroll")));
this.AutoScrollMargin = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMargin")));
this.AutoScrollMinSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMinSize")));
this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage")));
this.CancelButton = this.btnClose;
this.ClientSize = ((System.Drawing.Size)(resources.GetObject("$this.ClientSize")));
this.Controls.Add(this.lblMessage);
this.Controls.Add(this.btnClose);
this.Controls.Add(this.dgrdData);
this.Enabled = ((bool)(resources.GetObject("$this.Enabled")));
this.Font = ((System.Drawing.Font)(resources.GetObject("$this.Font")));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("$this.ImeMode")));
this.Location = ((System.Drawing.Point)(resources.GetObject("$this.Location")));
this.MaximumSize = ((System.Drawing.Size)(resources.GetObject("$this.MaximumSize")));
this.MinimumSize = ((System.Drawing.Size)(resources.GetObject("$this.MinimumSize")));
this.Name = "NotSetupSTDItems";
this.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("$this.RightToLeft")));
this.StartPosition = ((System.Windows.Forms.FormStartPosition)(resources.GetObject("$this.StartPosition")));
this.Text = resources.GetString("$this.Text");
this.Load += new System.EventHandler(this.NotSetupSTDItems_Load);
((System.ComponentModel.ISupportInitialize)(this.dgrdData)).EndInit();
this.ResumeLayout(false);
}
#endregion
private void NotSetupSTDItems_Load(object sender, System.EventArgs e)
{
const string METHOD_NAME = THIS + ".NotSetupSTDItems_Load()";
try
{
Security objSecurity = new Security();
this.Name = THIS;
if (objSecurity.SetRightForUserOnForm(this, SystemProperty.UserName) == 0)
{
this.Close();
return;
}
if (m_dtbNotSTDCost != null)
{
DataTable dtbLayout = FormControlComponents.StoreGridLayout(dgrdData);
dgrdData.DataSource = m_dtbNotSTDCost;
FormControlComponents.RestoreGridLayout(dgrdData,dtbLayout);
}
}
catch (PCSException ex)
{
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
private void btnClose_Click(object sender, System.EventArgs e)
{
this.Close();
}
}
}
| |
//-----------------------------------------------------------------------
// Copyright (c) 2011, Elmar Langholz
// Copyright (c) 2011, Oliver M. Haynold
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Text;
namespace RserveCLI2
{
/// <summary>
/// DES Encryption algorithm.
/// Based on FreeBSD's libcrypt:
/// secure/lib/libcrypt/crypt-des.c
/// </summary>
internal class DES
{
#region Constants and Fields
private readonly byte[] _ip = new byte[]
{
58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48,
40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13
, 5, 63, 55, 47, 39, 31, 23, 15, 7
};
private readonly byte[] ascii64 = new[]
{
(byte)'.', (byte)'/', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6',
(byte)'7', (byte)'8', (byte)'9', (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F',
(byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O',
(byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X',
(byte)'Y', (byte)'Z', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p',
(byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y',
(byte)'z'
};
private readonly uint[] bits32 = new uint[]
{
0x80000000, 0x40000000, 0x20000000, 0x10000000, 0x08000000, 0x04000000, 0x02000000, 0x01000000, 0x00800000
, 0x00400000, 0x00200000, 0x00100000, 0x00080000, 0x00040000, 0x00020000, 0x00010000, 0x00008000,
0x00004000, 0x00002000, 0x00001000, 0x00000800, 0x00000400, 0x00000200, 0x00000100, 0x00000080, 0x00000040
, 0x00000020, 0x00000010, 0x00000008, 0x00000004, 0x00000002, 0x00000001
};
private readonly byte[] bits8 = new byte[] { 0x80 , 0x40 , 0x20 , 0x10 , 0x08 , 0x04 , 0x02 , 0x01 };
private readonly uint[ , ] compMaskl = new uint[ 8 , 128 ];
private readonly uint[ , ] compMaskr = new uint[ 8 , 128 ];
private readonly byte[] compPerm = new byte[]
{
14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47
, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32
};
private readonly uint[] deKeysl = new uint[ 16 ];
private readonly uint[] deKeysr = new uint[ 16 ];
private readonly uint[] enKeysl = new uint[ 16 ];
private readonly uint[] enKeysr = new uint[ 16 ];
private readonly byte[] finalPerm = new byte[ 64 ];
private readonly uint[ , ] fpMaskl = new uint[ 8 , 256 ];
private readonly uint[ , ] fpMaskr = new uint[ 8 , 256 ];
private readonly byte[] initPerm = new byte[ 64 ];
private readonly byte[] invCompPerm = new byte[ 56 ];
private readonly byte[] invKeyPerm = new byte[ 64 ];
private readonly uint[ , ] ipMaskl = new uint[ 8 , 256 ];
private readonly uint[ , ] ipMaskr = new uint[ 8 , 256 ];
private readonly byte[] keyPerm = new byte[]
{
57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36
, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12,
4
};
private readonly uint[ , ] keyPermMaskl = new uint[ 8 , 128 ];
private readonly uint[ , ] keyPermMaskr = new uint[ 8 , 128 ];
private readonly byte[] keyShifts = new byte[] { 1 , 1 , 2 , 2 , 2 , 2 , 2 , 2 , 1 , 2 , 2 , 2 , 2 , 2 , 2 , 1 };
private readonly byte[ , ] mSbox = new byte[ 4 , 4096 ];
private readonly byte[] pbox = new byte[]
{
16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22
, 11, 4, 25
};
private readonly uint[ , ] psbox = new uint[ 4 , 256 ];
private readonly byte[ , ] sbox = new byte[ 8 , 64 ]
{
{
14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7, 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5,
3, 8, 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0, 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10
, 0, 6, 13
},
{
15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10, 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9,
11, 5, 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15, 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12,
0, 5, 14, 9
},
{
10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8, 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11,
15, 1, 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7, 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3,
11, 5, 2, 12
},
{
7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15, 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10,
14, 9, 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4, 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11,
12, 7, 2, 14
},
{
2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9, 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9,
8, 6, 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14, 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9,
10, 4, 5, 3
},
{
12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11, 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11,
3, 8, 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6, 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6
, 0, 8, 13
},
{
4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1, 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15,
8, 6, 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2, 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14
, 2, 3, 12
},
{
13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7, 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14,
9, 2, 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8, 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3
, 5, 6, 11
}
};
private readonly byte[ , ] uSbox = new byte[ 8 , 64 ];
private readonly byte[] unPbox = new byte[ 32 ];
private int desInitialised;
private uint oldRawkey0;
private uint oldRawkey1;
private uint oldSalt;
private uint saltbits;
#endregion
#region Public Methods
/// <summary>
/// This method encrypt the given string with the salt indicated, using DES Algorithm
/// </summary>
/// <param name="k">
/// The string to be encrypted.
/// </param>
/// <param name="s">
/// The salt.
/// </param>
/// <returns>
/// The encrypted string.
/// </returns>
public string Encrypt( string k , string s )
{
var desHash = string.Empty;
uint count , salt , r0 = 0 , r1 = 0;
var it = 0;
var q = new byte[ 8 ];
var key = ( new ASCIIEncoding() ).GetBytes( k );
var setting = ( new ASCIIEncoding() ).GetBytes( s );
if ( !Convert.ToBoolean( desInitialised ) )
{
DESInit();
}
for ( var i = 0 ; i < 8 && i < key.Length ; i++ )
{
q[ i ] = ( byte )( key[ it = i ] << 1 );
}
it++;
for ( var i = key.Length ; i < 8 ; i++ )
{
q[ i ] = 0;
}
if ( Convert.ToBoolean( DESSetkey( q ) ) )
{
return null;
}
if ( setting[ 0 ] == '_' )
{
count = 0;
for ( int i = 1 ; i < 5 ; i++ )
{
count |= ( uint )( AsciiToBin( ( char )setting[ i ] ) << ( ( i - 1 ) * 6 ) );
}
salt = 0;
for ( int i = 5 ; i < 9 ; i++ )
{
salt |= ( uint )( AsciiToBin( ( char )setting[ i ] ) << ( ( i - 5 ) * 6 ) );
}
for ( int i = it ; i < key.Length ; )
{
if ( Convert.ToBoolean( DESCipher( q , ref q , 0 , 1 ) ) )
{
return null;
}
for ( int j = 0 ; j < 8 && i < key.Length ; )
{
q[ j++ ] ^= ( byte )( key[ i++ ] << 1 );
}
if ( Convert.ToBoolean( DESSetkey( q ) ) )
{
return null;
}
}
for ( int i = 0 ; i < 9 ; i++ )
{
desHash += ( char )setting[ i ];
}
}
else
{
count = 25;
salt = ( uint )( ( AsciiToBin( ( char )setting[ 1 ] ) << 6 ) | AsciiToBin( ( char )setting[ 0 ] ) );
desHash += ( char )setting[ 0 ];
desHash += ( char )( Convert.ToBoolean( setting[ 1 ] ) ? setting[ 1 ] : setting[ 0 ] );
}
SetupSalt( salt );
if ( Convert.ToBoolean( DoDES( 0 , 0 , ref r0 , ref r1 , ( int )count ) ) )
{
return null;
}
uint l = r0 >> 8;
desHash += ( char )ascii64[ ( l >> 18 ) & 0x3f ];
desHash += ( char )ascii64[ ( l >> 12 ) & 0x3f ];
desHash += ( char )ascii64[ ( l >> 6 ) & 0x3f ];
desHash += ( char )ascii64[ l & 0x3f ];
l = ( r0 << 16 ) | ( ( r1 >> 16 ) & 0xffff );
desHash += ( char )ascii64[ ( l >> 18 ) & 0x3f ];
desHash += ( char )ascii64[ ( l >> 12 ) & 0x3f ];
desHash += ( char )ascii64[ ( l >> 6 ) & 0x3f ];
desHash += ( char )ascii64[ l & 0x3f ];
l = r1 << 2;
desHash += ( char )ascii64[ ( l >> 12 ) & 0x3f ];
desHash += ( char )ascii64[ ( l >> 6 ) & 0x3f ];
desHash += ( char )ascii64[ l & 0x3f ];
return desHash;
}
#endregion
#region Methods
private static int AsciiToBin( char ch )
{
if ( ch > 'z' )
{
return 0;
}
if ( ch >= 'a' )
{
return ch - 'a' + 38;
}
if ( ch > 'Z' )
{
return 0;
}
if ( ch >= 'A' )
{
return ch - 'A' + 12;
}
if ( ch > '9' )
{
return 0;
}
if ( ch >= '.' )
{
return ch - '.';
}
return 0;
}
private int DESCipher( byte[] @in , ref byte[] @out , ulong salt , int count )
{
uint lOut = 0 , rOut = 0;
if ( !Convert.ToBoolean( desInitialised ) )
{
DESInit();
}
SetupSalt( ( uint )salt );
var rawl = ( uint )( @in[ 0 ] << 24 | @in[ 1 ] << 16 | @in[ 2 ] << 8 | @in[ 3 ] );
var rawr = ( uint )( @in[ 4 ] << 24 | @in[ 5 ] << 16 | @in[ 6 ] << 8 | @in[ 7 ] );
int retval = DoDES( rawl , rawr , ref lOut , ref rOut , count );
@out[ 3 ] = ( byte )( lOut >> 24 );
@out[ 2 ] = ( byte )( lOut >> 16 );
@out[ 1 ] = ( byte )( lOut >> 8 );
@out[ 0 ] = ( byte )lOut;
@out[ 7 ] = ( byte )( rOut >> 24 );
@out[ 6 ] = ( byte )( rOut >> 16 );
@out[ 5 ] = ( byte )( rOut >> 8 );
@out[ 4 ] = ( byte )rOut;
return retval;
}
private void DESInit()
{
int b;
oldRawkey0 = oldRawkey1 = 0;
saltbits = 0;
oldSalt = 0;
for ( int i = 0 ; i < 8 ; i++ )
{
for ( int j = 0 ; j < 64 ; j++ )
{
b = ( j & 0x20 ) | ( ( j & 1 ) << 4 ) | ( ( j >> 1 ) & 0xf );
uSbox[ i , j ] = sbox[ i , b ];
}
}
for ( b = 0 ; b < 4 ; b++ )
{
for ( int i = 0 ; i < 64 ; i++ )
{
for ( int j = 0 ; j < 64 ; j++ )
{
mSbox[ b , ( i << 6 ) | j ] =
( byte )( ( uSbox[ b << 1 , i ] << 4 ) | uSbox[ ( b << 1 ) + 1 , j ] );
}
}
}
for ( int i = 0 ; i < 64 ; i++ )
{
finalPerm[ i ] = ( byte )( _ip[ i ] - 1 );
initPerm[ finalPerm[ i ] ] = ( byte )i;
invKeyPerm[ i ] = 255;
}
for ( int i = 0 ; i < 56 ; i++ )
{
invKeyPerm[ keyPerm[ i ] - 1 ] = ( byte )i;
invCompPerm[ i ] = 255;
}
for ( int i = 0 ; i < 48 ; i++ )
{
invCompPerm[ compPerm[ i ] - 1 ] = ( byte )i;
}
for ( int k = 0 ; k < 8 ; k++ )
{
int inbit;
int obit;
for ( int i = 0 ; i < 256 ; i++ )
{
ipMaskl[ k , i ] = 0;
ipMaskr[ k , i ] = 0;
fpMaskl[ k , i ] = 0;
fpMaskr[ k , i ] = 0;
for ( int j = 0 ; j < 8 ; j++ )
{
inbit = 8 * k + j;
if ( !Convert.ToBoolean( i & bits8[ j ] ) )
{
continue;
}
if ( ( obit = initPerm[ inbit ] ) < 32 )
{
ipMaskl[ k , i ] |= bits32[ obit ];
}
else
{
ipMaskr[ k , i ] |= bits32[ obit - 32 ];
}
if ( ( obit = finalPerm[ inbit ] ) < 32 )
{
fpMaskl[ k , i ] |= bits32[ obit ];
}
else
{
fpMaskr[ k , i ] |= bits32[ obit - 32 ];
}
}
}
for ( int i = 0 ; i < 128 ; i++ )
{
keyPermMaskl[ k , i ] = 0;
keyPermMaskr[ k , i ] = 0;
for ( int j = 0 ; j < 7 ; j++ )
{
inbit = 8 * k + j;
if ( !Convert.ToBoolean( i & bits8[ j + 1 ] ) )
{
continue;
}
if ( ( obit = invKeyPerm[ inbit ] ) == 255 )
{
continue;
}
if ( obit < 28 )
{
keyPermMaskl[ k , i ] |= bits32[ 4 + obit ];
}
else
{
keyPermMaskr[ k , i ] |= bits32[ 4 + obit - 28 ];
}
}
compMaskl[ k , i ] = 0;
compMaskr[ k , i ] = 0;
for ( int j = 0 ; j < 7 ; j++ )
{
inbit = 7 * k + j;
if ( !Convert.ToBoolean( i & bits8[ j + 1 ] ) )
{
continue;
}
if ( ( obit = invCompPerm[ inbit ] ) == 255 )
{
continue;
}
if ( obit < 24 )
{
compMaskl[ k , i ] |= bits32[ 8 + obit ];
}
else
{
compMaskr[ k , i ] |= bits32[ 8 + obit - 24 ];
}
}
}
}
for ( int i = 0 ; i < 32 ; i++ )
{
unPbox[ pbox[ i ] - 1 ] = ( byte )i;
}
for ( b = 0 ; b < 4 ; b++ )
{
for ( int i = 0 ; i < 256 ; i++ )
{
psbox[ b , i ] = 0;
for ( int j = 0 ; j < 8 ; j++ )
{
if ( Convert.ToBoolean( i & bits8[ j ] ) )
{
psbox[ b , i ] |= bits32[ unPbox[ 8 * b + j ] ];
}
}
}
}
desInitialised = 1;
}
private int DESSetkey( byte[] k )
{
if ( !Convert.ToBoolean( desInitialised ) )
{
DESInit();
}
var rawkey0 = ( uint )( k[ 0 ] << 24 | k[ 1 ] << 16 | k[ 2 ] << 8 | k[ 3 ] );
var rawkey1 = ( uint )( k[ 4 ] << 24 | k[ 5 ] << 16 | k[ 6 ] << 8 | k[ 7 ] );
if ( Convert.ToBoolean( rawkey0 | rawkey1 ) && rawkey0 == oldRawkey0 && rawkey1 == oldRawkey1 )
{
return 0;
}
oldRawkey0 = rawkey0;
oldRawkey1 = rawkey1;
uint k0 = keyPermMaskl[ 0 , rawkey0 >> 25 ] | keyPermMaskl[ 1 , ( rawkey0 >> 17 ) & 0x7f ] |
keyPermMaskl[ 2 , ( rawkey0 >> 9 ) & 0x7f ] | keyPermMaskl[ 3 , ( rawkey0 >> 1 ) & 0x7f ] |
keyPermMaskl[ 4 , rawkey1 >> 25 ] | keyPermMaskl[ 5 , ( rawkey1 >> 17 ) & 0x7f ] |
keyPermMaskl[ 6 , ( rawkey1 >> 9 ) & 0x7f ] | keyPermMaskl[ 7 , ( rawkey1 >> 1 ) & 0x7f ];
uint k1 = keyPermMaskr[ 0 , rawkey0 >> 25 ] | keyPermMaskr[ 1 , ( rawkey0 >> 17 ) & 0x7f ] |
keyPermMaskr[ 2 , ( rawkey0 >> 9 ) & 0x7f ] | keyPermMaskr[ 3 , ( rawkey0 >> 1 ) & 0x7f ] |
keyPermMaskr[ 4 , rawkey1 >> 25 ] | keyPermMaskr[ 5 , ( rawkey1 >> 17 ) & 0x7f ] |
keyPermMaskr[ 6 , ( rawkey1 >> 9 ) & 0x7f ] | keyPermMaskr[ 7 , ( rawkey1 >> 1 ) & 0x7f ];
int shifts = 0;
for ( int round = 0 ; round < 16 ; round++ )
{
shifts += keyShifts[ round ];
uint t0 = ( k0 << shifts ) | ( k0 >> ( 28 - shifts ) );
uint t1 = ( k1 << shifts ) | ( k1 >> ( 28 - shifts ) );
deKeysl[ 15 - round ] =
enKeysl[ round ] =
compMaskl[ 0 , ( t0 >> 21 ) & 0x7f ] | compMaskl[ 1 , ( t0 >> 14 ) & 0x7f ] |
compMaskl[ 2 , ( t0 >> 7 ) & 0x7f ] | compMaskl[ 3 , t0 & 0x7f ] |
compMaskl[ 4 , ( t1 >> 21 ) & 0x7f ] | compMaskl[ 5 , ( t1 >> 14 ) & 0x7f ] |
compMaskl[ 6 , ( t1 >> 7 ) & 0x7f ] | compMaskl[ 7 , t1 & 0x7f ];
deKeysr[ 15 - round ] =
enKeysr[ round ] =
compMaskr[ 0 , ( t0 >> 21 ) & 0x7f ] | compMaskr[ 1 , ( t0 >> 14 ) & 0x7f ] |
compMaskr[ 2 , ( t0 >> 7 ) & 0x7f ] | compMaskr[ 3 , t0 & 0x7f ] |
compMaskr[ 4 , ( t1 >> 21 ) & 0x7f ] | compMaskr[ 5 , ( t1 >> 14 ) & 0x7f ] |
compMaskr[ 6 , ( t1 >> 7 ) & 0x7f ] | compMaskr[ 7 , t1 & 0x7f ];
}
return 0;
}
private int DoDES( uint lIn , uint rIn , ref uint lOut , ref uint rOut , int count )
{
uint f = 0;
uint[] kl1 , kr1;
if ( count == 0 )
{
return 1;
}
if ( count > 0 )
{
kl1 = enKeysl;
kr1 = enKeysr;
}
else
{
count = -count;
kl1 = deKeysl;
kr1 = deKeysr;
}
uint l = ipMaskl[ 0 , lIn >> 24 ] | ipMaskl[ 1 , ( lIn >> 16 ) & 0xff ] |
ipMaskl[ 2 , ( lIn >> 8 ) & 0xff ] | ipMaskl[ 3 , lIn & 0xff ] | ipMaskl[ 4 , rIn >> 24 ] |
ipMaskl[ 5 , ( rIn >> 16 ) & 0xff ] | ipMaskl[ 6 , ( rIn >> 8 ) & 0xff ] |
ipMaskl[ 7 , rIn & 0xff ];
uint r = ipMaskr[ 0 , lIn >> 24 ] | ipMaskr[ 1 , ( lIn >> 16 ) & 0xff ] |
ipMaskr[ 2 , ( lIn >> 8 ) & 0xff ] | ipMaskr[ 3 , lIn & 0xff ] | ipMaskr[ 4 , rIn >> 24 ] |
ipMaskr[ 5 , ( rIn >> 16 ) & 0xff ] | ipMaskr[ 6 , ( rIn >> 8 ) & 0xff ] |
ipMaskr[ 7 , rIn & 0xff ];
while ( Convert.ToBoolean( count-- ) )
{
uint[] kl = kl1;
uint[] kr = kr1;
uint j = 0;
int round = 16;
while ( Convert.ToBoolean( round-- ) )
{
uint r48L = ( ( r & 0x00000001 ) << 23 ) | ( ( r & 0xf8000000 ) >> 9 ) | ( ( r & 0x1f800000 ) >> 11 ) |
( ( r & 0x01f80000 ) >> 13 ) | ( ( r & 0x001f8000 ) >> 15 );
uint r48R = ( ( r & 0x0001f800 ) << 7 ) | ( ( r & 0x00001f80 ) << 5 ) | ( ( r & 0x000001f8 ) << 3 ) |
( ( r & 0x0000001f ) << 1 ) | ( ( r & 0x80000000 ) >> 31 );
f = ( r48L ^ r48R ) & saltbits;
r48L ^= f ^ kl[ j ];
r48R ^= f ^ kr[ j++ ];
f = psbox[ 0 , mSbox[ 0 , r48L >> 12 ] ] | psbox[ 1 , mSbox[ 1 , r48L & 0xfff ] ] |
psbox[ 2 , mSbox[ 2 , r48R >> 12 ] ] | psbox[ 3 , mSbox[ 3 , r48R & 0xfff ] ];
f ^= l;
l = r;
r = f;
}
r = l;
l = f;
}
lOut = fpMaskl[ 0 , l >> 24 ] | fpMaskl[ 1 , ( l >> 16 ) & 0xff ] | fpMaskl[ 2 , ( l >> 8 ) & 0xff ] |
fpMaskl[ 3 , l & 0xff ] | fpMaskl[ 4 , r >> 24 ] | fpMaskl[ 5 , ( r >> 16 ) & 0xff ] |
fpMaskl[ 6 , ( r >> 8 ) & 0xff ] | fpMaskl[ 7 , r & 0xff ];
rOut = fpMaskr[ 0 , l >> 24 ] | fpMaskr[ 1 , ( l >> 16 ) & 0xff ] | fpMaskr[ 2 , ( l >> 8 ) & 0xff ] |
fpMaskr[ 3 , l & 0xff ] | fpMaskr[ 4 , r >> 24 ] | fpMaskr[ 5 , ( r >> 16 ) & 0xff ] |
fpMaskr[ 6 , ( r >> 8 ) & 0xff ] | fpMaskr[ 7 , r & 0xff ];
return 0;
}
private void SetupSalt( uint salt )
{
if ( salt == oldSalt )
{
return;
}
oldSalt = salt;
saltbits = 0;
uint saltbit = 1;
uint obit = 0x800000;
for ( int i = 0 ; i < 24 ; i++ )
{
if ( Convert.ToBoolean( salt & saltbit ) )
{
saltbits |= obit;
}
saltbit <<= 1;
obit >>= 1;
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Management.Automation;
using System.Management.Automation.Host;
using Dbg = System.Management.Automation.Diagnostics;
namespace Microsoft.PowerShell
{
/// <summary>
/// ProgressPane is a class that represents the "window" in which outstanding activities for which the host has received
/// progress updates are shown.
///
///</summary>
internal
class ProgressPane
{
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="ui">
/// An implementation of the PSHostRawUserInterface with which the pane will be shown and hidden.
/// </param>
internal
ProgressPane(ConsoleHostUserInterface ui)
{
if (ui == null) throw new ArgumentNullException(nameof(ui));
_ui = ui;
_rawui = ui.RawUI;
}
/// <summary>
/// Indicates whether the pane is visible on the screen buffer or not.
/// </summary>
/// <value>
/// true if the pane is visible, false if not.
///
///</value>
internal
bool
IsShowing
{
get
{
return (_savedRegion != null);
}
}
/// <summary>
/// Shows the pane in the screen buffer. Saves off the content of the region of the buffer that will be overwritten so
/// that it can be restored again.
/// </summary>
internal
void
Show()
{
if (!IsShowing)
{
// Get temporary reference to the progress region since it can be
// changed at any time by a call to WriteProgress.
BufferCell[,] tempProgressRegion = _progressRegion;
if (tempProgressRegion == null)
{
return;
}
// The location where we show ourselves is always relative to the screen buffer's current window position.
int rows = tempProgressRegion.GetLength(0);
int cols = tempProgressRegion.GetLength(1);
if (ProgressNode.IsMinimalProgressRenderingEnabled())
{
rows = _content.Length;
cols = PSStyle.Instance.Progress.MaxWidth;
if (cols > _bufSize.Width)
{
cols = _bufSize.Width;
}
}
_savedCursor = _rawui.CursorPosition;
_location.X = 0;
if (!Platform.IsWindows || ProgressNode.IsMinimalProgressRenderingEnabled())
{
_location.Y = _rawui.CursorPosition.Y;
// if cursor is not on left edge already move down one line
if (_rawui.CursorPosition.X != 0)
{
_location.Y++;
_rawui.CursorPosition = _location;
}
// if the cursor is at the bottom, create screen buffer space by scrolling
int scrollRows = rows - ((_rawui.BufferSize.Height - 1) - _location.Y);
if (scrollRows > 0)
{
// Scroll the console screen up by 'scrollRows'
var bottomLocation = _location;
bottomLocation.Y = _rawui.BufferSize.Height - 1;
_rawui.CursorPosition = bottomLocation;
for (int i = 0; i < scrollRows; i++)
{
Console.Out.Write('\n');
}
_location.Y -= scrollRows;
_savedCursor.Y -= scrollRows;
}
// create cleared region to clear progress bar later
_savedRegion = tempProgressRegion;
if (PSStyle.Instance.Progress.View != ProgressView.Minimal)
{
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < cols; col++)
{
_savedRegion[row, col].Character = ' ';
}
}
}
// put cursor back to where output should be
_rawui.CursorPosition = _location;
}
else
{
_location = _rawui.WindowPosition;
// We have to show the progress pane in the first column, as the screen buffer at any point might contain
// a CJK double-cell characters, which makes it impractical to try to find a position where the pane would
// not slice a character. Column 0 is the only place where we know for sure we can place the pane.
_location.Y = Math.Min(_location.Y + 2, _bufSize.Height);
// Save off the current contents of the screen buffer in the region that we will occupy
_savedRegion =
_rawui.GetBufferContents(
new Rectangle(_location.X, _location.Y, _location.X + cols - 1, _location.Y + rows - 1));
}
if (ProgressNode.IsMinimalProgressRenderingEnabled())
{
WriteContent();
}
else
{
// replace the saved region in the screen buffer with our progress display
_rawui.SetBufferContents(_location, tempProgressRegion);
}
}
}
/// <summary>
/// Hides the pane by restoring the saved contents of the region of the buffer that the pane occupies. If the pane is
/// not showing, then does nothing.
/// </summary>
internal
void
Hide()
{
if (IsShowing)
{
if (ProgressNode.IsMinimalProgressRenderingEnabled())
{
_rawui.CursorPosition = _location;
int maxWidth = PSStyle.Instance.Progress.MaxWidth;
if (maxWidth > _bufSize.Width)
{
maxWidth = _bufSize.Width;
}
for (int i = 0; i < _savedRegion.GetLength(1); i++)
{
if (i < _savedRegion.GetLength(1) - 1)
{
Console.Out.WriteLine(string.Empty.PadRight(maxWidth));
}
else
{
Console.Out.Write(string.Empty.PadRight(maxWidth));
}
}
}
else
{
// It would be nice if we knew that the saved region could be kept for the next time Show is called, but alas,
// we have no way of knowing if the screen buffer has changed since we were hidden. By "no good way" I mean that
// detecting a change would be at least as expensive as chucking the savedRegion and rebuilding it. And it would
// be very complicated.
_rawui.SetBufferContents(_location, _savedRegion);
}
_savedRegion = null;
_rawui.CursorPosition = _savedCursor;
}
}
/// <summary>
/// Updates the pane with the rendering of the supplied PendingProgress, and shows it.
/// </summary>
/// <param name="pendingProgress">
/// A PendingProgress instance that represents the outstanding activities that should be shown.
/// </param>
internal
void
Show(PendingProgress pendingProgress)
{
Dbg.Assert(pendingProgress != null, "pendingProgress may not be null");
_bufSize = _rawui.BufferSize;
// In order to keep from slicing any CJK double-cell characters that might be present in the screen buffer,
// we use the full width of the buffer.
int maxWidth = _bufSize.Width;
int maxHeight = Math.Max(5, _rawui.WindowSize.Height / 3);
_content = pendingProgress.Render(maxWidth, maxHeight, _rawui);
if (_content == null)
{
// There's nothing to show.
Hide();
_progressRegion = null;
return;
}
BufferCell[,] newRegion;
if (ProgressNode.IsMinimalProgressRenderingEnabled())
{
// Legacy progress rendering relies on a BufferCell which defines a character, foreground color, and background color
// per cell. This model doesn't work with ANSI escape sequences. However, there is existing logic on rendering that
// relies on the existence of the BufferCell to know if something has been rendered previously. Here we are creating
// an empty BufferCell, but using the second dimension to capture the number of rows so that we can clear that many
// elsewhere in Hide().
newRegion = new BufferCell[0, _content.Length];
}
else
{
newRegion = _rawui.NewBufferCellArray(_content, _ui.ProgressForegroundColor, _ui.ProgressBackgroundColor);
}
Dbg.Assert(newRegion != null, "NewBufferCellArray has failed!");
if (_progressRegion == null)
{
// we've never shown this pane before.
_progressRegion = newRegion;
Show();
}
else
{
// We have shown the pane before. We have to be smart about when we restore the saved region to minimize
// flicker. We need to decide if the new contents will change the dimensions of the progress pane
// currently being shown. If it will, then restore the saved region, and show the new one. Otherwise,
// just blast the new one on top of the last one shown.
// We're only checking size, not content, as we assume that the content will always change upon receipt
// of a new ProgressRecord. That's not guaranteed, of course, but it's a good bet. So checking content
// would usually result in detection of a change, so why bother?
bool sizeChanged =
(newRegion.GetLength(0) != _progressRegion.GetLength(0))
|| (newRegion.GetLength(1) != _progressRegion.GetLength(1));
_progressRegion = newRegion;
if (sizeChanged)
{
if (IsShowing)
{
Hide();
}
Show();
}
else
{
if (ProgressNode.IsMinimalProgressRenderingEnabled())
{
WriteContent();
}
else
{
_rawui.SetBufferContents(_location, _progressRegion);
}
}
}
}
private void WriteContent()
{
if (_content is not null)
{
Console.CursorVisible = false;
var currentPosition = _rawui.CursorPosition;
_rawui.CursorPosition = _location;
for (int i = 0; i < _content.Length; i++)
{
if (i < _content.Length - 1)
{
Console.Out.WriteLine(_content[i]);
}
else
{
Console.Out.Write(_content[i]);
}
}
_rawui.CursorPosition = currentPosition;
Console.CursorVisible = true;
}
}
private Coordinates _location = new Coordinates(0, 0);
private Coordinates _savedCursor;
private Size _bufSize;
private BufferCell[,] _savedRegion;
private BufferCell[,] _progressRegion;
private string[] _content;
private readonly PSHostRawUserInterface _rawui;
private readonly ConsoleHostUserInterface _ui;
}
} // namespace
| |
function ObjectBuilderGui::init(%this) {
%this.baseOffsetX = 5;
%this.baseOffsetY = 5;
%this.defaultObjectName = "";
%this.defaultFieldStep = 22;
%this.columnOffset = 110;
%this.fieldNameExtent = "105 18";
%this.textEditExtent = "122 18";
%this.checkBoxExtent = "13 18";
%this.popupMenuExtent = "122 18";
%this.fileButtonExtent = "122 18";
%this.matButtonExtent = "17 18";
//
%this.numControls = 0;
%this.lastPath = "";
%this.reset();
}
function ObjectBuilderGui::reset(%this) {
%this.objectGroup = "";
%this.curXPos = %this.baseOffsetX;
%this.curYPos = %this.baseOffsetY;
%this.createFunction = "";
%this.createCallback = "";
%this.currentControl = 0;
//
OBObjectName.setValue(%this.defaultObjectName);
//
%this.newObject = 0;
%this.objectClassName = "";
%this.numFields = 0;
//
for(%i = 0; %i < %this.numControls; %i++) {
%this.textControls[%i].delete();
%this.controls[%i].delete();
}
%this.numControls = 0;
}
//------------------------------------------------------------------------------
function ObjectBuilderGui::createFileType(%this, %index) {
if(%index >= %this.numFields || %this.field[%index, name] $= "") {
error("ObjectBuilderGui::createFileType: invalid field");
return;
}
//
if(%this.field[%index, text] $= "")
%name = %this.field[%index, name];
else
%name = %this.field[%index, text];
//
%this.textControls[%this.numControls] = new GuiTextCtrl() {
profile = "ToolsGuiTextRightProfile";
text = %name;
extent = %this.fieldNameExtent;
position = %this.curXPos @ " " @ %this.curYPos;
modal = "1";
};
//
%this.controls[%this.numControls] = new GuiButtonCtrl() {
HorizSizing = "width";
profile = "ToolsButtonProfile";
extent = %this.fileButtonExtent;
position = %this.curXPos + %this.columnOffset @ " " @ %this.curYPos;
modal = "1";
command = %this @ ".getFileName(" @ %index @ ");";
};
%val = %this.field[%index, value];
%this.controls[%this.numControls].setValue(fileBase(%val) @ fileExt(%val));
%this.numControls++;
%this.curYPos += %this.defaultFieldStep;
}
function ObjectBuilderGui::getFileName(%this, %index) {
if(%index >= %this.numFields || %this.field[%index, name] $= "") {
error("ObjectBuilderGui::getFileName: invalid field");
return;
}
%val = %this.field[%index, ext];
//%path = filePath(%val);
//%ext = fileExt(%val);
%this.currentControl = %index;
getLoadFilename( %val @ "|" @ %val, %this @ ".gotFileName", %this.lastPath );
}
function ObjectBuilderGui::gotFileName(%this, %name) {
%index = %this.currentControl;
%name = makeRelativePath(%name,getWorkingDirectory());
%this.field[%index, value] = %name;
%this.controls[%this.currentControl].setText(fileBase(%name) @ fileExt(%name));
%this.lastPath = %name;
// This doesn't work for button controls as getValue returns their state!
//%this.controls[%this.currentControl].setValue(%name);
}
//------------------------------------------------------------------------------
function ObjectBuilderGui::createMaterialNameType(%this, %index) {
if(%index >= %this.numFields || %this.field[%index, name] $= "") {
error("ObjectBuilderGui::createMaterialNameType: invalid field");
return;
}
//
if(%this.field[%index, text] $= "")
%name = %this.field[%index, name];
else
%name = %this.field[%index, text];
//
%this.textControls[%this.numControls] = new GuiTextCtrl() {
profile = "ToolsGuiTextRightProfile";
text = %name;
extent = %this.fieldNameExtent;
position = %this.curXPos @ " " @ %this.curYPos;
modal = "1";
};
//
%this.controls[%this.numControls] = new GuiControl() {
HorizSizing = "width";
profile = "ToolsDefaultProfile";
extent = %this.textEditExtent;
position = %this.curXPos + %this.columnOffset @ " " @ %this.curYPos;
modal = "1";
};
%text = new GuiTextEditCtrl() {
class = ObjectBuilderGuiTextEditCtrl;
internalName = "MatText";
HorizSizing = "width";
profile = "ToolsTextEdit";
extent = getWord(%this.textEditExtent,0) - getWord(%this.matButtonExtent,0) - 2 @ " " @ getWord(%this.textEditExtent,1);
text = %this.field[%index, value];
position = "0 0";
modal = "1";
};
%this.controls[%this.numControls].addGuiControl(%text);
%button = new GuiBitmapButtonCtrl() {
internalName = "MatButton";
HorizSizing = "left";
profile = "ToolsButtonProfile";
extent = %this.matButtonExtent;
position = getWord(%this.textEditExtent,0) - getWord(%this.matButtonExtent,0) @ " 0";
modal = "1";
command = %this @ ".getMaterialName(" @ %index @ ");";
};
%button.setBitmap("tlab/materialEditor/assets/change-material-btn");
%this.controls[%this.numControls].addGuiControl(%button);
//%val = %this.field[%index, value];
//%this.controls[%this.numControls].setValue(%val);
//%this.controls[%this.numControls].setBitmap("tlab/materialEditor/assets/change-material-btn");
%this.numControls++;
%this.curYPos += %this.defaultFieldStep;
}
function ObjectBuilderGui::getMaterialName(%this, %index) {
if(%index >= %this.numFields || %this.field[%index, name] $= "") {
error("ObjectBuilderGui::getMaterialName: invalid field");
return;
}
%this.currentControl = %index;
MaterialSelector.showDialog(%this @ ".gotMaterialName", "name");
}
function ObjectBuilderGui::gotMaterialName(%this, %name) {
%index = %this.currentControl;
%this.field[%index, value] = %name;
%this.controls[%index]-->MatText.setText(%name);
}
//------------------------------------------------------------------------------
function ObjectBuilderGui::createDataBlockType(%this, %index) {
if(%index >= %this.numFields || %this.field[%index, name] $= "") {
error("ObjectBuilderGui::createDataBlockType: invalid field");
return;
}
//
if(%this.field[%index, text] $= "")
%name = %this.field[%index, name];
else
%name = %this.field[%index, text];
//
%this.textControls[%this.numControls] = new GuiTextCtrl() {
profile = "ToolsGuiTextRightProfile";
text = %name;
extent = %this.fieldNameExtent;
position = %this.curXPos @ " " @ %this.curYPos;
modal = "1";
};
//
%this.controls[%this.numControls] = new GuiPopupMenuCtrl() {
HorizSizing = "width";
profile = "ToolsDropdownProfile";
extent = %this.popupMenuExtent;
position = %this.curXPos + %this.columnOffset @ " " @ %this.curYPos;
modal = "1";
maxPopupHeight = "200";
};
%classname = getWord(%this.field[%index, value], 0);
%classname_alt = getWord(%this.field[%index, value], 1);
%this.controls[%this.numControls].add("", -1);
// add the datablocks
for(%i = 0; %i < DataBlockGroup.getCount(); %i++) {
%obj = DataBlockGroup.getObject(%i);
if( isMemberOfClass( %obj.getClassName(), %classname ) || isMemberOfClass ( %obj.getClassName(), %classname_alt ) )
%this.controls[%this.numControls].add(%obj.getName(), %i);
}
%this.controls[%this.numControls].setValue(getWord(%this.field[%index, value], 1));
%this.numControls++;
%this.curYPos += %this.defaultFieldStep;
}
function ObjectBuilderGui::createBoolType(%this, %index) {
if(%index >= %this.numFields || %this.field[%index, name] $= "") {
error("ObjectBuilderGui::createBoolType: invalid field");
return;
}
//
if(%this.field[%index, value] $= "")
%value = 0;
else
%value = %this.field[%index, value];
//
if(%this.field[%index, text] $= "")
%name = %this.field[%index, name];
else
%name = %this.field[%index, text];
//
%this.textControls[%this.numControls] = new GuiTextCtrl() {
profile = "ToolsGuiTextRightProfile";
text = %name;
extent = %this.fieldNameExtent;
position = %this.curXPos @ " " @ %this.curYPos;
modal = "1";
};
//
%this.controls[%this.numControls] = new GuiCheckBoxCtrl() {
profile = "ToolsCheckBoxProfile";
extent = %this.checkBoxExtent;
position = %this.curXPos + %this.columnOffset @ " " @ %this.curYPos;
modal = "1";
};
%this.controls[%this.numControls].setValue(%value);
%this.numControls++;
%this.curYPos += %this.defaultFieldStep;
}
function ObjectBuilderGuiTextEditCtrl::onGainFirstResponder(%this) {
%this.selectAllText();
}
function ObjectBuilderGui::createStringType(%this, %index) {
if(%index >= %this.numFields || %this.field[%index, name] $= "") {
error("ObjectBuilderGui::createStringType: invalid field");
return;
}
//
if(%this.field[%index, text] $= "")
%name = %this.field[%index, name];
else
%name = %this.field[%index, text];
//
%this.textControls[%this.numControls] = new GuiTextCtrl() {
profile = "ToolsGuiTextRightProfile";
text = %name;
extent = %this.fieldNameExtent;
position = %this.curXPos @ " " @ %this.curYPos;
modal = "1";
};
//
%this.controls[%this.numControls] = new GuiTextEditCtrl() {
class = ObjectBuilderGuiTextEditCtrl;
HorizSizing = "width";
profile = "ToolsTextEdit";
extent = %this.textEditExtent;
text = %this.field[%index, value];
position = %this.curXPos + %this.columnOffset @ " " @ %this.curYPos;
modal = "1";
};
%this.numControls++;
%this.curYPos += %this.defaultFieldStep;
}
//------------------------------------------------------------------------------
function ObjectBuilderGui::adjustSizes(%this) {
if(%this.numControls == 0)
%this.curYPos = 0;
OBTargetWindow.extent = getWord(OBTargetWindow.extent, 0) SPC %this.curYPos + 88;
OBContentWindow.extent = getWord(OBContentWindow.extent, 0) SPC %this.curYPos;
OBOKButton.position = getWord(OBOKButton.position, 0) SPC %this.curYPos + 57;
OBCancelButton.position = getWord(OBCancelButton.position, 0) SPC %this.curYPos + 57;
}
function ObjectBuilderGui::process(%this) {
if(%this.objectClassName $= "") {
error("ObjectBuilderGui::process: classname is not specified");
return;
}
OBTargetWindow.text = "Create Object: " @ %this.objectClassName;
%name = getUniqueName(%this.objectClassName@"_1");
OBObjectName.setText(%name);
//
for(%i = 0; %i < %this.numFields; %i++) {
switch$(%this.field[%i, type]) {
case "TypeBool":
%this.createBoolType(%i);
case "TypeDataBlock":
%this.createDataBlockType(%i);
case "TypeFile":
%this.createFileType(%i);
case "TypeMaterialName":
%this.createMaterialNameType(%i);
default:
%this.createStringType(%i);
}
}
// add the controls
for(%i = 0; %i < %this.numControls; %i++) {
OBContentWindow.add(%this.textControls[%i]);
OBContentWindow.add(%this.controls[%i]);
}
//
%this.adjustSizes();
//
Canvas.pushDialog(%this);
}
function ObjectBuilderGui::processNewObject(%this, %obj) {
if ( %this.createCallback !$= "" )
eval( %this.createCallback );
// Skip out if nothing was created.
if ( !isObject( %obj ) )
return;
// Add the object to the group.
if( %this.objectGroup !$= "" )
%this.objectGroup.add( %obj );
else
Scene.getActiveSimGroup().add( %obj );
// If we were given a callback to call after the
// object has been created, do so now. Also clear
// the callback to make sure it's valid only for
// a single invocation.
%callback = %this.newObjectCallback;
%this.newObjectCallback = "";
if( %callback !$= "" )
eval( %callback @ "( " @ %obj @ " );" );
}
function ObjectBuilderGui::onOK(%this) {
// Error out if the given object name is not valid or not unique.
%objectName = OBObjectName.getValue();
if( !Lab::validateObjectName( %objectName, false ))
return;
// get current values
for(%i = 0; %i < %this.numControls; %i++) {
// uses button type where getValue returns button state!
if (%this.field[%i, type] $= "TypeFile") {
if (strchr(%this.field[%i, value],"*") !$= "")
%this.field[%i, value] = "";
continue;
}
if (%this.field[%i, type] $= "TypeMaterialName") {
%this.field[%i, value] = %this.controls[%i]-->MatText.getValue();
continue;
}
%this.field[%i, value] = %this.controls[%i].getValue();
}
// If we have a special creation function then
// let it do the construction.
if ( %this.createFunction !$= "" )
eval( %this.createFunction );
else {
// Else we use the memento.
%memento = %this.buildMemento();
eval( %memento );
}
if(%this.newObject != 0)
%this.processNewObject(%this.newObject);
%this.reset();
Canvas.popDialog(%this);
}
function ObjectBuilderGui::onCancel(%this) {
%this.reset();
Canvas.popDialog(%this);
}
function ObjectBuilderGui::addField(%this, %name, %type, %text, %value, %ext) {
%this.field[%this.numFields, name] = %name;
%this.field[%this.numFields, type] = %type;
%this.field[%this.numFields, text] = %text;
%this.field[%this.numFields, value] = %value;
%this.field[%this.numFields, ext] = %ext;
%this.numFields++;
}
// *-OFF
function ObjectBuilderGui::buildMemento(%this) {
// Build the object into a string.
%this.memento = %this @ ".newObject = new " @ %this.objectClassName @ "(" @ OBObjectName.getValue() @ ") { ";
for( %i = 0; %i < %this.numFields; %i++ )
%this.memento = %this.memento @ %this.field[%i, name] @ " = \"" @ %this.field[%i, value] @ "\"; ";
%this.memento = %this.memento @ "};";
return %this.memento;
}
// *-ON
| |
// 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 System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.ExtractMethod;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod
{
internal partial class CSharpMethodExtractor
{
private partial class CSharpCodeGenerator
{
private class ExpressionCodeGenerator : CSharpCodeGenerator
{
public ExpressionCodeGenerator(
InsertionPoint insertionPoint,
SelectionResult selectionResult,
AnalyzerResult analyzerResult) :
base(insertionPoint, selectionResult, analyzerResult)
{
}
public static bool IsExtractMethodOnExpression(SelectionResult code)
{
return code.SelectionInExpression;
}
protected override SyntaxToken CreateMethodName()
{
var methodName = "NewMethod";
var containingScope = this.CSharpSelectionResult.GetContainingScope();
methodName = GetMethodNameBasedOnExpression(methodName, containingScope);
var semanticModel = this.SemanticDocument.SemanticModel;
var nameGenerator = new UniqueNameGenerator(semanticModel);
return SyntaxFactory.Identifier(nameGenerator.CreateUniqueMethodName(containingScope, methodName));
}
private static string GetMethodNameBasedOnExpression(string methodName, SyntaxNode expression)
{
if (expression.Parent != null &&
expression.Parent.Kind() == SyntaxKind.EqualsValueClause &&
expression.Parent.Parent != null &&
expression.Parent.Parent.Kind() == SyntaxKind.VariableDeclarator)
{
var name = ((VariableDeclaratorSyntax)expression.Parent.Parent).Identifier.ValueText;
return (name != null && name.Length > 0) ? MakeMethodName("Get", name) : methodName;
}
if (expression is MemberAccessExpressionSyntax)
{
expression = ((MemberAccessExpressionSyntax)expression).Name;
}
if (expression is NameSyntax)
{
SimpleNameSyntax unqualifiedName;
switch (expression.Kind())
{
case SyntaxKind.IdentifierName:
case SyntaxKind.GenericName:
unqualifiedName = (SimpleNameSyntax)expression;
break;
case SyntaxKind.QualifiedName:
unqualifiedName = ((QualifiedNameSyntax)expression).Right;
break;
case SyntaxKind.AliasQualifiedName:
unqualifiedName = ((AliasQualifiedNameSyntax)expression).Name;
break;
default:
throw new System.NotSupportedException("Unexpected name kind: " + expression.Kind().ToString());
}
var unqualifiedNameIdentifierValueText = unqualifiedName.Identifier.ValueText;
return (unqualifiedNameIdentifierValueText != null && unqualifiedNameIdentifierValueText.Length > 0) ? MakeMethodName("Get", unqualifiedNameIdentifierValueText) : methodName;
}
return methodName;
}
protected override IEnumerable<StatementSyntax> GetInitialStatementsForMethodDefinitions()
{
Contract.ThrowIfFalse(IsExtractMethodOnExpression(this.CSharpSelectionResult));
ExpressionSyntax expression = null;
// special case for array initializer
var returnType = this.AnalyzerResult.ReturnType;
var containingScope = this.CSharpSelectionResult.GetContainingScope();
if (returnType.TypeKind == TypeKind.Array && containingScope is InitializerExpressionSyntax)
{
var typeSyntax = returnType.GenerateTypeSyntax();
expression = SyntaxFactory.ArrayCreationExpression(typeSyntax as ArrayTypeSyntax, containingScope as InitializerExpressionSyntax);
}
else
{
expression = containingScope as ExpressionSyntax;
}
if (this.AnalyzerResult.HasReturnType)
{
return SpecializedCollections.SingletonEnumerable<StatementSyntax>(
SyntaxFactory.ReturnStatement(
WrapInCheckedExpressionIfNeeded(expression)));
}
else
{
return SpecializedCollections.SingletonEnumerable<StatementSyntax>(
SyntaxFactory.ExpressionStatement(
WrapInCheckedExpressionIfNeeded(expression)));
}
}
private ExpressionSyntax WrapInCheckedExpressionIfNeeded(ExpressionSyntax expression)
{
var kind = this.CSharpSelectionResult.UnderCheckedExpressionContext();
if (kind == SyntaxKind.None)
{
return expression;
}
return SyntaxFactory.CheckedExpression(kind, expression);
}
protected override SyntaxNode GetOutermostCallSiteContainerToProcess(CancellationToken cancellationToken)
{
var callSiteContainer = GetCallSiteContainerFromOutermostMoveInVariable(cancellationToken);
if (callSiteContainer != null)
{
return callSiteContainer;
}
else
{
return GetCallSiteContainerFromExpression();
}
}
private SyntaxNode GetCallSiteContainerFromExpression()
{
var container = this.CSharpSelectionResult.GetInnermostStatementContainer();
Contract.ThrowIfNull(container);
Contract.ThrowIfFalse(container.IsStatementContainerNode() ||
container is TypeDeclarationSyntax ||
container is ConstructorDeclarationSyntax ||
container is CompilationUnitSyntax);
return container;
}
protected override SyntaxNode GetFirstStatementOrInitializerSelectedAtCallSite()
{
var scope = (SyntaxNode)this.CSharpSelectionResult.GetContainingScopeOf<StatementSyntax>();
if (scope == null)
{
scope = this.CSharpSelectionResult.GetContainingScopeOf<FieldDeclarationSyntax>();
}
if (scope == null)
{
scope = this.CSharpSelectionResult.GetContainingScopeOf<ConstructorInitializerSyntax>();
}
if (scope == null)
{
// This is similar to FieldDeclaration case but we only want to do this if the member has an expression body.
scope = this.CSharpSelectionResult.GetContainingScopeOf<ArrowExpressionClauseSyntax>().Parent;
}
return scope;
}
protected override SyntaxNode GetLastStatementOrInitializerSelectedAtCallSite()
{
return GetFirstStatementOrInitializerSelectedAtCallSite();
}
protected override async Task<SyntaxNode> GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(
SyntaxAnnotation callSiteAnnotation, CancellationToken cancellationToken)
{
var enclosingStatement = GetFirstStatementOrInitializerSelectedAtCallSite();
var callSignature = CreateCallSignature().WithAdditionalAnnotations(callSiteAnnotation);
var invocation = callSignature.IsKind(SyntaxKind.AwaitExpression) ? ((AwaitExpressionSyntax)callSignature).Expression : callSignature;
var sourceNode = this.CSharpSelectionResult.GetContainingScope();
Contract.ThrowIfTrue(
sourceNode.Parent is MemberAccessExpressionSyntax && ((MemberAccessExpressionSyntax)sourceNode.Parent).Name == sourceNode,
"invalid scope. given scope is not an expression");
// To lower the chances that replacing sourceNode with callSignature will break the user's
// code, we make the enclosing statement semantically explicit. This ends up being a little
// bit more work because we need to annotate the sourceNode so that we can get back to it
// after rewriting the enclosing statement.
var updatedDocument = this.SemanticDocument.Document;
var sourceNodeAnnotation = new SyntaxAnnotation();
var enclosingStatementAnnotation = new SyntaxAnnotation();
var newEnclosingStatement = enclosingStatement
.ReplaceNode(sourceNode, sourceNode.WithAdditionalAnnotations(sourceNodeAnnotation))
.WithAdditionalAnnotations(enclosingStatementAnnotation);
updatedDocument = await updatedDocument.ReplaceNodeAsync(enclosingStatement, newEnclosingStatement, cancellationToken).ConfigureAwait(false);
var updatedRoot = await updatedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
newEnclosingStatement = updatedRoot.GetAnnotatedNodesAndTokens(enclosingStatementAnnotation).Single().AsNode();
// because of the complexification we cannot guarantee that there is only one annotation.
// however complexification of names is prepended, so the last annotation should be the original one.
sourceNode = updatedRoot.GetAnnotatedNodesAndTokens(sourceNodeAnnotation).Last().AsNode();
// we want to replace the old identifier with a invocation expression, but because of MakeExplicit we might have
// a member access now instead of the identifier. So more syntax fiddling is needed.
if (sourceNode.Parent.Kind() == SyntaxKind.SimpleMemberAccessExpression &&
((ExpressionSyntax)sourceNode).IsRightSideOfDot())
{
var explicitMemberAccess = (MemberAccessExpressionSyntax)sourceNode.Parent;
var replacementMemberAccess = explicitMemberAccess.CopyAnnotationsTo(
SyntaxFactory.MemberAccessExpression(
sourceNode.Parent.Kind(),
explicitMemberAccess.Expression,
(SimpleNameSyntax)((InvocationExpressionSyntax)invocation).Expression));
var newInvocation = SyntaxFactory.InvocationExpression(
replacementMemberAccess,
((InvocationExpressionSyntax)invocation).ArgumentList);
var newCallSignature = callSignature != invocation ?
callSignature.ReplaceNode(invocation, newInvocation) : invocation.CopyAnnotationsTo(newInvocation);
sourceNode = sourceNode.Parent;
callSignature = newCallSignature;
}
return newEnclosingStatement.ReplaceNode(sourceNode, callSignature);
}
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//
// This source file is marked up so that it can be built both as part of the BCL and as part of the fx tree
// as well. Since the security annotation process is different between the two trees, SecurityCritical
// attributes appear directly in this file, instead of being marked up by the BCL annotator tool.
//
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.ConstrainedExecution;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics.Contracts;
namespace System.Security.Cryptography {
/// <summary>
/// Native interop with CAPI. Native code definitions can be found in wincrypt.h
/// </summary>
internal static class CapiNative {
/// <summary>
/// Class fields for CAPI algorithm identifiers
/// </summary>
internal enum AlgorithmClass
{
Any = (0 << 13), // ALG_CLASS_ANY
Signature = (1 << 13), // ALG_CLASS_SIGNATURE
Hash = (4 << 13), // ALG_CLASS_HASH
KeyExchange = (5 << 13), // ALG_CLASS_KEY_EXCHANGE
}
/// <summary>
/// Type identifier fields for CAPI algorithm identifiers
/// </summary>
internal enum AlgorithmType
{
Any = (0 << 9), // ALG_TYPE_ANY
Rsa = (2 << 9), // ALG_TYPE_RSA
}
/// <summary>
/// Sub identifiers for CAPI algorithm identifiers
/// </summary>
internal enum AlgorithmSubId
{
Any = 0, // ALG_SID_ANY
RsaAny = 0, // ALG_SID_RSA_ANY
Sha1 = 4, // ALG_SID_SHA1
Sha256 = 12, // ALG_SID_SHA_256
Sha384 = 13, // ALG_SID_SHA_384
Sha512 = 14, // ALG_SID_SHA_512
}
/// <summary>
/// CAPI algorithm identifiers
/// </summary>
internal enum AlgorithmID
{
None = 0,
RsaSign = (AlgorithmClass.Signature | AlgorithmType.Rsa | AlgorithmSubId.RsaAny), // CALG_RSA_SIGN
RsaKeyExchange = (AlgorithmClass.KeyExchange | AlgorithmType.Rsa | AlgorithmSubId.RsaAny), // CALG_RSA_KEYX
Sha1 = (AlgorithmClass.Hash | AlgorithmType.Any | AlgorithmSubId.Sha1), // CALG_SHA1
Sha256 = (AlgorithmClass.Hash | AlgorithmType.Any | AlgorithmSubId.Sha256), // CALG_SHA_256
Sha384 = (AlgorithmClass.Hash | AlgorithmType.Any | AlgorithmSubId.Sha384), // CALG_SHA_384
Sha512 = (AlgorithmClass.Hash | AlgorithmType.Any | AlgorithmSubId.Sha512), // CALG_SHA_512
}
/// <summary>
/// Flags for the CryptAcquireContext API
/// </summary>
[Flags]
internal enum CryptAcquireContextFlags {
None = 0x00000000,
NewKeyset = 0x00000008, // CRYPT_NEWKEYSET
DeleteKeyset = 0x00000010, // CRYPT_DELETEKEYSET
MachineKeyset = 0x00000020, // CRYPT_MACHINE_KEYSET
Silent = 0x00000040, // CRYPT_SILENT
VerifyContext = unchecked((int)0xF0000000) // CRYPT_VERIFYCONTEXT
}
/// <summary>
/// Error codes returned by CAPI
/// </summary>
internal enum ErrorCode {
Ok = 0x00000000,
MoreData = 0x000000ea, // ERROR_MORE_DATA
BadHash = unchecked((int)0x80090002), // NTE_BAD_HASH
BadData = unchecked((int)0x80090005), // NTE_BAD_DATA
BadSignature = unchecked((int)0x80090006), // NTE_BAD_SIGNATURE
NoKey = unchecked((int)0x8009000d) // NTE_NO_KEY
}
/// <summary>
/// Properties of CAPI hash objects
/// </summary>
internal enum HashProperty {
None = 0,
HashValue = 0x0002, // HP_HASHVAL
HashSize = 0x0004, // HP_HASHSIZE
}
/// <summary>
/// Flags for the CryptGenKey API
/// </summary>
[Flags]
internal enum KeyGenerationFlags {
None = 0x00000000,
Exportable = 0x00000001, // CRYPT_EXPORTABLE
UserProtected = 0x00000002, // CRYPT_USER_PROTECTED
Archivable = 0x00004000 // CRYPT_ARCHIVABLE
}
/// <summary>
/// Properties that can be read or set on a key
/// </summary>
internal enum KeyProperty {
None = 0,
AlgorithmID = 7, // KP_ALGID
KeyLength = 9 // KP_KEYLEN
}
/// <summary>
/// Key numbers for identifying specific keys within a single container
/// </summary>
internal enum KeySpec {
KeyExchange = 1, // AT_KEYEXCHANGE
Signature = 2 // AT_SIGNATURE
}
/// <summary>
/// Well-known names of crypto service providers
/// </summary>
internal static class ProviderNames {
// MS_ENHANCED_PROV
internal const string MicrosoftEnhanced = "Microsoft Enhanced Cryptographic Provider v1.0";
}
/// <summary>
/// Provider type accessed in a crypto service provider. These provide the set of algorithms
/// available to use for an application.
/// </summary>
internal enum ProviderType {
RsaFull = 1 // PROV_RSA_FULL
}
[System.Security.SecurityCritical]
internal static class UnsafeNativeMethods {
/// <summary>
/// Open a crypto service provider, if a key container is specified KeyContainerPermission
/// should be demanded.
/// </summary>
[DllImport("advapi32", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CryptAcquireContext([Out] out SafeCspHandle phProv,
string pszContainer,
string pszProvider,
ProviderType dwProvType,
CryptAcquireContextFlags dwFlags);
/// <summary>
/// Create an object to hash data with
/// </summary>
[DllImport("advapi32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CryptCreateHash(SafeCspHandle hProv,
AlgorithmID Algid,
IntPtr hKey, // SafeCspKeyHandle
int dwFlags,
[Out] out SafeCspHashHandle phHash);
/// <summary>
/// Create a new key in the given key container
/// </summary>
[DllImport("advapi32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CryptGenKey(SafeCspHandle hProv,
int Algid,
uint dwFlags,
[Out] out SafeCspKeyHandle phKey);
/// <summary>
/// Fill a buffer with randomly generated data
/// </summary>
[DllImport("advapi32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CryptGenRandom(SafeCspHandle hProv,
int dwLen,
[In, Out, MarshalAs(UnmanagedType.LPArray)] byte[] pbBuffer);
/// <summary>
/// Fill a buffer with randomly generated data
/// </summary>
[DllImport("advapi32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern unsafe bool CryptGenRandom(SafeCspHandle hProv,
int dwLen,
byte* pbBuffer);
/// <summary>
/// Read the value of a property from a hash object
/// </summary>
[DllImport("advapi32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CryptGetHashParam(SafeCspHashHandle hHash,
HashProperty dwParam,
[In, Out, MarshalAs(UnmanagedType.LPArray)] byte[] pbData,
[In, Out] ref int pdwDataLen,
int dwFlags);
/// <summary>
/// Read the value of a property from a key
/// </summary>
[DllImport("advapi32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CryptGetKeyParam(SafeCspKeyHandle hKey,
KeyProperty dwParam,
[In, Out, MarshalAs(UnmanagedType.LPArray)] byte[] pbData,
[In, Out] ref int pdwDataLen,
int dwFlags);
/// <summary>
/// Import a key blob into a CSP
/// </summary>
[DllImport("advapi32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CryptImportKey(SafeCspHandle hProv,
[In, MarshalAs(UnmanagedType.LPArray)] byte[] pbData,
int pdwDataLen,
IntPtr hPubKey, // SafeCspKeyHandle
KeyGenerationFlags dwFlags,
[Out] out SafeCspKeyHandle phKey);
/// <summary>
/// Set the value of a property on a hash object
/// </summary>
[DllImport("advapi32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CryptSetHashParam(SafeCspHashHandle hHash,
HashProperty dwParam,
[In, MarshalAs(UnmanagedType.LPArray)] byte[] pbData,
int dwFlags);
/// <summary>
/// Verify the a digital signature
/// </summary>
[DllImport("advapi32", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CryptVerifySignature(SafeCspHashHandle hHash,
[In, MarshalAs(UnmanagedType.LPArray)] byte[] pbSignature,
int dwSigLen,
SafeCspKeyHandle hPubKey,
string sDescription,
int dwFlags);
}
/// <summary>
/// Acquire a handle to a crypto service provider and optionally a key container
/// </summary>
[SecurityCritical]
internal static SafeCspHandle AcquireCsp(string keyContainer,
string providerName,
ProviderType providerType,
CryptAcquireContextFlags flags) {
Contract.Assert(keyContainer == null, "Key containers are not supported");
// Specifying both verify context (for an ephemeral key) and machine keyset (for a persisted machine key)
// does not make sense. Additionally, Widows is beginning to lock down against uses of MACHINE_KEYSET
// (for instance in the app container), even if verify context is present. Therefore, if we're using
// an ephemeral key, strip out MACHINE_KEYSET from the flags.
if (((flags & CryptAcquireContextFlags.VerifyContext) == CryptAcquireContextFlags.VerifyContext) &&
((flags & CryptAcquireContextFlags.MachineKeyset) == CryptAcquireContextFlags.MachineKeyset)) {
flags &= ~CryptAcquireContextFlags.MachineKeyset;
}
SafeCspHandle cspHandle = null;
if (!UnsafeNativeMethods.CryptAcquireContext(out cspHandle,
keyContainer,
providerName,
providerType,
flags)) {
throw new CryptographicException(Marshal.GetLastWin32Error());
}
return cspHandle;
}
/// <summary>
/// Create a CSP hash object for the specified hash algorithm
/// </summary>
[SecurityCritical]
internal static SafeCspHashHandle CreateHashAlgorithm(SafeCspHandle cspHandle, AlgorithmID algorithm) {
Contract.Assert(cspHandle != null && !cspHandle.IsInvalid, "cspHandle != null && !cspHandle.IsInvalid");
Contract.Assert(((AlgorithmClass)algorithm & AlgorithmClass.Hash) == AlgorithmClass.Hash, "Invalid hash algorithm");
SafeCspHashHandle hashHandle = null;
if (!UnsafeNativeMethods.CryptCreateHash(cspHandle, algorithm, IntPtr.Zero, 0, out hashHandle)) {
throw new CryptographicException(Marshal.GetLastWin32Error());
}
return hashHandle;
}
/// <summary>
/// Fill a buffer with random data generated by the CSP
/// </summary>
[SecurityCritical]
internal static void GenerateRandomBytes(SafeCspHandle cspHandle, byte[] buffer) {
Contract.Assert(cspHandle != null && !cspHandle.IsInvalid, "cspHandle != null && !cspHandle.IsInvalid");
Contract.Assert(buffer != null && buffer.Length > 0, "buffer != null && buffer.Length > 0");
if (!UnsafeNativeMethods.CryptGenRandom(cspHandle, buffer.Length, buffer)) {
throw new CryptographicException(Marshal.GetLastWin32Error());
}
}
/// <summary>
/// Fill part of a buffer with random data generated by the CSP
/// </summary>
[SecurityCritical]
internal static unsafe void GenerateRandomBytes(SafeCspHandle cspHandle, byte[] buffer, int offset, int count)
{
Contract.Assert(cspHandle != null && !cspHandle.IsInvalid, "cspHandle != null && !cspHandle.IsInvalid");
Contract.Assert(buffer != null && buffer.Length > 0, "buffer != null && buffer.Length > 0");
Contract.Assert(offset >= 0 && count > 0, "offset >= 0 && count > 0");
Contract.Assert(buffer.Length >= offset + count, "buffer.Length >= offset + count");
fixed (byte* pBuffer = &buffer[offset])
{
if (!UnsafeNativeMethods.CryptGenRandom(cspHandle, count, pBuffer))
{
throw new CryptographicException(Marshal.GetLastWin32Error());
}
}
}
/// <summary>
/// Get a DWORD sized property of a hash object
/// </summary>
[SecurityCritical]
internal static int GetHashPropertyInt32(SafeCspHashHandle hashHandle, HashProperty property) {
byte[] rawProperty = GetHashProperty(hashHandle, property);
Contract.Assert(rawProperty.Length == sizeof(int) || rawProperty.Length == 0, "Unexpected property size");
return rawProperty.Length == sizeof(int) ? BitConverter.ToInt32(rawProperty, 0) : 0;
}
/// <summary>
/// Get an arbitrary property of a hash object
/// </summary>
[SecurityCritical]
internal static byte[] GetHashProperty(SafeCspHashHandle hashHandle, HashProperty property) {
Contract.Assert(hashHandle != null && !hashHandle.IsInvalid, "keyHandle != null && !keyHandle.IsInvalid");
int bufferSize = 0;
byte[] buffer = null;
// Figure out how big of a buffer we need to hold the property
if (!UnsafeNativeMethods.CryptGetHashParam(hashHandle, property, buffer, ref bufferSize, 0)) {
int errorCode = Marshal.GetLastWin32Error();
if (errorCode != (int)ErrorCode.MoreData) {
throw new CryptographicException(errorCode);
}
}
// Now get the property bytes directly
buffer = new byte[bufferSize];
if (!UnsafeNativeMethods.CryptGetHashParam(hashHandle, property, buffer, ref bufferSize, 0)) {
throw new CryptographicException(Marshal.GetLastWin32Error());
}
return buffer;
}
/// <summary>
/// Get a DWORD sized property of a key stored in a CSP
/// </summary>
[SecurityCritical]
internal static int GetKeyPropertyInt32(SafeCspKeyHandle keyHandle, KeyProperty property) {
byte[] rawProperty = GetKeyProperty(keyHandle, property);
Contract.Assert(rawProperty.Length == sizeof(int) || rawProperty.Length == 0, "Unexpected property size");
return rawProperty.Length == sizeof(int) ? BitConverter.ToInt32(rawProperty, 0) : 0;
}
/// <summary>
/// Get an arbitrary property of a key stored in a CSP
/// </summary>
[SecurityCritical]
internal static byte[] GetKeyProperty(SafeCspKeyHandle keyHandle, KeyProperty property) {
Contract.Assert(keyHandle != null && !keyHandle.IsInvalid, "keyHandle != null && !keyHandle.IsInvalid");
int bufferSize = 0;
byte[] buffer = null;
// Figure out how big of a buffer we need to hold the property
if (!UnsafeNativeMethods.CryptGetKeyParam(keyHandle, property, buffer, ref bufferSize, 0)) {
int errorCode = Marshal.GetLastWin32Error();
if (errorCode != (int)ErrorCode.MoreData) {
throw new CryptographicException(errorCode);
}
}
// Now get the property bytes directly
buffer = new byte[bufferSize];
if (!UnsafeNativeMethods.CryptGetKeyParam(keyHandle, property, buffer, ref bufferSize, 0)) {
throw new CryptographicException(Marshal.GetLastWin32Error());
}
return buffer;
}
/// <summary>
/// Set an arbitrary property on a hash object
/// </summary>
[SecurityCritical]
internal static void SetHashProperty(SafeCspHashHandle hashHandle,
HashProperty property,
byte[] value) {
Contract.Assert(hashHandle != null && !hashHandle.IsInvalid, "hashHandle != null && !hashHandle.IsInvalid");
if (!UnsafeNativeMethods.CryptSetHashParam(hashHandle, property, value, 0)) {
throw new CryptographicException(Marshal.GetLastWin32Error());
}
}
/// <summary>
/// Verify that the digital signature created with the specified hash and asymmetric algorithm
/// is valid for the given hash value.
/// </summary>
[SecurityCritical]
internal static bool VerifySignature(SafeCspHandle cspHandle,
SafeCspKeyHandle keyHandle,
AlgorithmID signatureAlgorithm,
AlgorithmID hashAlgorithm,
byte[] hashValue,
byte[] signature) {
Contract.Assert(cspHandle != null && !cspHandle.IsInvalid, "cspHandle != null && !cspHandle.IsInvalid");
Contract.Assert(keyHandle != null && !keyHandle.IsInvalid, "keyHandle != null && !keyHandle.IsInvalid");
Contract.Assert(((AlgorithmClass)signatureAlgorithm & AlgorithmClass.Signature) == AlgorithmClass.Signature, "Invalid signature algorithm");
Contract.Assert(((AlgorithmClass)hashAlgorithm & AlgorithmClass.Hash) == AlgorithmClass.Hash, "Invalid hash algorithm");
Contract.Assert(hashValue != null, "hashValue != null");
Contract.Assert(signature != null, "signature != null");
// CAPI and the CLR have inverse byte orders for signatures, so we need to reverse before verifying
byte[] signatureValue = new byte[signature.Length];
Array.Copy(signature, signatureValue, signatureValue.Length);
Array.Reverse(signatureValue);
using (SafeCspHashHandle hashHandle = CreateHashAlgorithm(cspHandle, hashAlgorithm)) {
// Make sure the hash value is the correct size and import it into the CSP
if (hashValue.Length != GetHashPropertyInt32(hashHandle, HashProperty.HashSize)) {
throw new CryptographicException((int)ErrorCode.BadHash);
}
SetHashProperty(hashHandle, HashProperty.HashValue, hashValue);
// Do the signature verification. A TRUE result means that the signature was valid. A FALSE
// result either means an invalid signature or some other error, so we need to check the last
// error to see which occured.
if (UnsafeNativeMethods.CryptVerifySignature(hashHandle,
signatureValue,
signatureValue.Length,
keyHandle,
null,
0)) {
return true;
}
else {
int error = Marshal.GetLastWin32Error();
if (error != (int)ErrorCode.BadSignature) {
throw new CryptographicException(error);
}
return false;
}
}
}
}
/// <summary>
/// SafeHandle representing a native HCRYPTPROV on Windows, or representing all state associated with
/// loading a CSSM CSP on the Mac. The HCRYPTPROV SafeHandle usage is straightforward, however CSSM
/// usage is slightly different.
///
/// For CSSM we hold three pieces of state:
/// * m_initializedCssm - a flag indicating that CSSM_Init() was successfully called
/// * m_cspModuleGuid - the module GUID of the CSP we loaded, if that CSP was successfully loaded
/// * handle - handle resulting from attaching to the CSP
///
/// We need to keep all three pieces of state, since we need to teardown in a specific order. If
/// these pieces of state were in seperate SafeHandles we could not guarantee their order of
/// finalization.
/// </summary>
[SecurityCritical]
internal sealed class SafeCspHandle : SafeHandleZeroOrMinusOneIsInvalid {
private SafeCspHandle() : base(true) {
}
[DllImport("advapi32")]
#if FEATURE_CORECLR || FEATURE_CER
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif // FEATURE_CORECLR || FEATURE_CER
[return: MarshalAs(UnmanagedType.Bool)]
private extern static bool CryptReleaseContext(IntPtr hProv, int dwFlags);
/// <summary>
/// Clean up the safe handle's resources.
///
/// On Windows the cleanup is a straightforward release of the HCRYPTPROV handle. However, on
/// the Mac, CSSM requires that we release resources in the following order:
///
/// 1. Detach from the CSP
/// 2. Unload the CSP
/// 3. Terminate CSSM
///
/// Both the unload and terminate operations are ref-counted by CSSM, so it is safe to do these
/// even if other handles are open on the CSP or other CSSM objects are in use.
/// </summary>
[SecurityCritical]
protected override bool ReleaseHandle() {
return CryptReleaseContext(handle, 0);
}
}
/// <summary>
/// SafeHandle representing a native HCRYPTHASH
/// </summary>
[SecurityCritical]
internal sealed class SafeCspHashHandle : SafeHandleZeroOrMinusOneIsInvalid {
private SafeCspHashHandle() : base(true) {
}
[DllImport("advapi32")]
#if FEATURE_CORECLR || FEATURE_CER
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif // FEATURE_CORECLR || FEATURE_CER
[return: MarshalAs(UnmanagedType.Bool)]
private extern static bool CryptDestroyHash(IntPtr hKey);
[SecurityCritical]
protected override bool ReleaseHandle() {
return CryptDestroyHash(handle);
}
}
/// <summary>
/// SafeHandle representing a native HCRYPTKEY on Windows.
///
/// On the Mac, we generate our keys by hand, so they are really just CSSM_KEY structures along with
/// the associated data blobs. Because of this, the only resource that needs to be released when the
/// key is freed is the memory associated with the key blob.
///
/// However, in order for a SafeCspKeyHandle to marshal as a CSSM_KEY_PTR, as one would expect, the
/// handle value on the Mac is actually a pointer to the CSSM_KEY. We maintain a seperate m_data
/// pointer which is the buffer holding the actual key data.
///
/// Both of these details add a further invarient that on the Mac a SafeCspKeyHandle may never be an
/// [out] parameter from an API. This is because we always expect that we control the memory buffer
/// that the CSSM_KEY resides in and that we don't have to call CSSM_FreeKey on the data.
///
/// Keeping this in a SafeHandle rather than just marshaling the key structure direclty buys us a
/// level of abstraction, in that if we ever do need to work with keys that require a CSSM_FreeKey
/// call, we can continue to use the same key handle object. It also means that keys are represented
/// by the same type on both Windows and Mac, so that consumers of the CapiNative layer don't have
/// to know the difference between the two.
/// </summary>
[SecurityCritical]
internal sealed class SafeCspKeyHandle : SafeHandleZeroOrMinusOneIsInvalid {
internal SafeCspKeyHandle() : base(true) {
}
[DllImport("advapi32")]
#if FEATURE_CORECLR || FEATURE_CER
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif // FEATURE_CORECLR || FEATURE_CER
[return: MarshalAs(UnmanagedType.Bool)]
private extern static bool CryptDestroyKey(IntPtr hKey);
[SecurityCritical]
protected override bool ReleaseHandle() {
return CryptDestroyKey(handle);
}
}
}
| |
//
// https://github.com/NServiceKit/NServiceKit.Text
// NServiceKit.Text: .NET C# POCO JSON, JSV and CSV Text Serializers.
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2012 ServiceStack Ltd.
//
// Licensed under the same terms of ServiceStack: new BSD license.
//
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Threading;
namespace NServiceKit.Text.Common
{
/// <summary>A deserialize array with elements.</summary>
/// <typeparam name="TSerializer">Type of the serializer.</typeparam>
internal static class DeserializeArrayWithElements<TSerializer>
where TSerializer : ITypeSerializer
{
/// <summary>The parse delegate cache.</summary>
private static Dictionary<Type, ParseArrayOfElementsDelegate> ParseDelegateCache
= new Dictionary<Type, ParseArrayOfElementsDelegate>();
/// <summary>Parse array of elements delegate.</summary>
/// <param name="value"> The value.</param>
/// <param name="parseFn">The parse function.</param>
/// <returns>An object.</returns>
private delegate object ParseArrayOfElementsDelegate(string value, ParseStringDelegate parseFn);
/// <summary>Gets parse function.</summary>
/// <param name="type">The type.</param>
/// <returns>The parse function.</returns>
public static Func<string, ParseStringDelegate, object> GetParseFn(Type type)
{
ParseArrayOfElementsDelegate parseFn;
if (ParseDelegateCache.TryGetValue(type, out parseFn)) return parseFn.Invoke;
var genericType = typeof(DeserializeArrayWithElements<,>).MakeGenericType(type, typeof(TSerializer));
#if NETFX_CORE
var mi = genericType.GetRuntimeMethods().First(p => p.Name.Equals("ParseGenericArray"));
parseFn = (ParseArrayOfElementsDelegate)mi.CreateDelegate(typeof(ParseArrayOfElementsDelegate));
#else
var mi = genericType.GetMethod("ParseGenericArray", BindingFlags.Public | BindingFlags.Static);
parseFn = (ParseArrayOfElementsDelegate)Delegate.CreateDelegate(typeof(ParseArrayOfElementsDelegate), mi);
#endif
Dictionary<Type, ParseArrayOfElementsDelegate> snapshot, newCache;
do
{
snapshot = ParseDelegateCache;
newCache = new Dictionary<Type, ParseArrayOfElementsDelegate>(ParseDelegateCache);
newCache[type] = parseFn;
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref ParseDelegateCache, newCache, snapshot), snapshot));
return parseFn.Invoke;
}
}
/// <summary>A deserialize array with elements.</summary>
/// <typeparam name="T"> Generic type parameter.</typeparam>
/// <typeparam name="TSerializer">Type of the serializer.</typeparam>
internal static class DeserializeArrayWithElements<T, TSerializer>
where TSerializer : ITypeSerializer
{
/// <summary>The serializer.</summary>
private static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer<TSerializer>();
/// <summary>Parse generic array.</summary>
/// <param name="value"> The value.</param>
/// <param name="elementParseFn">The element parse function.</param>
/// <returns>A T[].</returns>
public static T[] ParseGenericArray(string value, ParseStringDelegate elementParseFn)
{
if ((value = DeserializeListWithElements<TSerializer>.StripList(value)) == null) return null;
if (value == string.Empty) return new T[0];
if (value[0] == JsWriter.MapStartChar)
{
var itemValues = new List<string>();
var i = 0;
do
{
itemValues.Add(Serializer.EatTypeValue(value, ref i));
Serializer.EatItemSeperatorOrMapEndChar(value, ref i);
} while (i < value.Length);
var results = new T[itemValues.Count];
for (var j = 0; j < itemValues.Count; j++)
{
results[j] = (T)elementParseFn(itemValues[j]);
}
return results;
}
else
{
var to = new List<T>();
var valueLength = value.Length;
var i = 0;
while (i < valueLength)
{
var elementValue = Serializer.EatValue(value, ref i);
var listValue = elementValue;
to.Add((T)elementParseFn(listValue));
if (Serializer.EatItemSeperatorOrMapEndChar(value, ref i)
&& i == valueLength)
{
// If we ate a separator and we are at the end of the value,
// it means the last element is empty => add default
to.Add(default(T));
}
}
return to.ToArray();
}
}
}
/// <summary>A deserialize array.</summary>
/// <typeparam name="TSerializer">Type of the serializer.</typeparam>
internal static class DeserializeArray<TSerializer>
where TSerializer : ITypeSerializer
{
/// <summary>The parse delegate cache.</summary>
private static Dictionary<Type, ParseStringDelegate> ParseDelegateCache = new Dictionary<Type, ParseStringDelegate>();
/// <summary>Gets parse function.</summary>
/// <param name="type">The type.</param>
/// <returns>The parse function.</returns>
public static ParseStringDelegate GetParseFn(Type type)
{
ParseStringDelegate parseFn;
if (ParseDelegateCache.TryGetValue(type, out parseFn)) return parseFn;
var genericType = typeof(DeserializeArray<,>).MakeGenericType(type, typeof(TSerializer));
var mi = genericType.GetPublicStaticMethod("GetParseFn");
var parseFactoryFn = (Func<ParseStringDelegate>)mi.MakeDelegate(
typeof(Func<ParseStringDelegate>));
parseFn = parseFactoryFn();
Dictionary<Type, ParseStringDelegate> snapshot, newCache;
do
{
snapshot = ParseDelegateCache;
newCache = new Dictionary<Type, ParseStringDelegate>(ParseDelegateCache);
newCache[type] = parseFn;
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref ParseDelegateCache, newCache, snapshot), snapshot));
return parseFn;
}
}
/// <summary>A deserialize array.</summary>
/// <typeparam name="T"> Generic type parameter.</typeparam>
/// <typeparam name="TSerializer">Type of the serializer.</typeparam>
internal static class DeserializeArray<T, TSerializer>
where TSerializer : ITypeSerializer
{
/// <summary>The serializer.</summary>
private static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer<TSerializer>();
/// <summary>The cache function.</summary>
private static readonly ParseStringDelegate CacheFn;
/// <summary>
/// Initializes static members of the NServiceKit.Text.Common.DeserializeArray<T,
/// TSerializer> class.
/// </summary>
static DeserializeArray()
{
CacheFn = GetParseFn();
}
/// <summary>Gets the parse.</summary>
/// <value>The parse.</value>
public static ParseStringDelegate Parse
{
get { return CacheFn; }
}
/// <summary>Gets parse function.</summary>
/// <exception cref="ArgumentException">Thrown when one or more arguments have unsupported or
/// illegal values.</exception>
/// <returns>The parse function.</returns>
public static ParseStringDelegate GetParseFn()
{
var type = typeof(T);
if (!type.IsArray)
throw new ArgumentException(string.Format("Type {0} is not an Array type", type.FullName));
if (type == typeof(string[]))
return ParseStringArray;
if (type == typeof(byte[]))
return ParseByteArray;
var elementType = type.GetElementType();
var elementParseFn = Serializer.GetParseFn(elementType);
if (elementParseFn != null)
{
var parseFn = DeserializeArrayWithElements<TSerializer>.GetParseFn(elementType);
return value => parseFn(value, elementParseFn);
}
return null;
}
/// <summary>Parse string array.</summary>
/// <param name="value">The value.</param>
/// <returns>A string[].</returns>
public static string[] ParseStringArray(string value)
{
if ((value = DeserializeListWithElements<TSerializer>.StripList(value)) == null) return null;
return value == string.Empty
? new string[0]
: DeserializeListWithElements<TSerializer>.ParseStringList(value).ToArray();
}
/// <summary>Parse byte array.</summary>
/// <param name="value">The value.</param>
/// <returns>A byte[].</returns>
public static byte[] ParseByteArray(string value)
{
if ((value = DeserializeListWithElements<TSerializer>.StripList(value)) == null) return null;
if ((value = Serializer.UnescapeSafeString(value)) == null) return null;
return value == string.Empty
? new byte[0]
: Convert.FromBase64String(value);
}
}
}
| |
namespace HearThis.Publishing
{
partial class PublishDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing)
components?.Dispose();
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Windows.Forms.Label label4;
this._saberRadio = new System.Windows.Forms.RadioButton();
this._megaVoiceRadio = new System.Windows.Forms.RadioButton();
this._mp3Radio = new System.Windows.Forms.RadioButton();
this._oggRadio = new System.Windows.Forms.RadioButton();
this._publishButton = new System.Windows.Forms.Button();
this._destinationLabel = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this._openFolderLink = new System.Windows.Forms.LinkLabel();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
this._flacRadio = new System.Windows.Forms.RadioButton();
this._audiBibleRadio = new System.Windows.Forms.RadioButton();
this._none = new System.Windows.Forms.RadioButton();
this._cancelButton = new System.Windows.Forms.Button();
this._logBox = new SIL.Windows.Forms.Progress.LogBox();
this._changeDestinationLink = new System.Windows.Forms.LinkLabel();
this.l10NSharpExtender1 = new L10NSharp.UI.L10NSharpExtender(this.components);
this.label1 = new System.Windows.Forms.Label();
this._cueSheet = new System.Windows.Forms.RadioButton();
this._audacityLabelFile = new System.Windows.Forms.RadioButton();
this._lblBooksToPublish = new System.Windows.Forms.Label();
this._rdoAllBooks = new System.Windows.Forms.RadioButton();
this._rdoCurrentBook = new System.Windows.Forms.RadioButton();
this._scrAppBuilderRadio = new System.Windows.Forms.RadioButton();
this._includePhraseLevelLabels = new System.Windows.Forms.CheckBox();
this.tableLayoutPanelMain = new System.Windows.Forms.TableLayoutPanel();
this.tableLayoutPanelAudioFormat = new System.Windows.Forms.TableLayoutPanel();
this._tableLayoutRight = new System.Windows.Forms.TableLayoutPanel();
this.tableLayoutPanelVerseIndexFormat = new System.Windows.Forms.TableLayoutPanel();
this._tableLayoutPanelBooksToPublish = new System.Windows.Forms.TableLayoutPanel();
label4 = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.l10NSharpExtender1)).BeginInit();
this.tableLayoutPanelMain.SuspendLayout();
this.tableLayoutPanelAudioFormat.SuspendLayout();
this._tableLayoutRight.SuspendLayout();
this.tableLayoutPanelVerseIndexFormat.SuspendLayout();
this._tableLayoutPanelBooksToPublish.SuspendLayout();
this.SuspendLayout();
//
// label4
//
label4.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
label4.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.l10NSharpExtender1.SetLocalizableToolTip(label4, null);
this.l10NSharpExtender1.SetLocalizationComment(label4, null);
this.l10NSharpExtender1.SetLocalizationPriority(label4, L10NSharp.LocalizationPriority.NotLocalizable);
this.l10NSharpExtender1.SetLocalizingId(label4, "PublishDialog.label4");
label4.Location = new System.Drawing.Point(30, 237);
label4.Name = "label4";
label4.Size = new System.Drawing.Size(610, 2);
label4.TabIndex = 17;
//
// _saberRadio
//
this._saberRadio.AutoSize = true;
this._saberRadio.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.l10NSharpExtender1.SetLocalizableToolTip(this._saberRadio, "");
this.l10NSharpExtender1.SetLocalizationComment(this._saberRadio, "Product name (but might be confused in Spanish with the verb \"saber\")");
this.l10NSharpExtender1.SetLocalizationPriority(this._saberRadio, L10NSharp.LocalizationPriority.NotLocalizable);
this.l10NSharpExtender1.SetLocalizingId(this._saberRadio, "PublishDialog.Saber");
this._saberRadio.Location = new System.Drawing.Point(3, 77);
this._saberRadio.Name = "_saberRadio";
this._saberRadio.Size = new System.Drawing.Size(60, 21);
this._saberRadio.TabIndex = 2;
this._saberRadio.Text = "Saber";
this.toolTip1.SetToolTip(this._saberRadio, "https://globalrecordings.net/en/saber");
this._saberRadio.UseVisualStyleBackColor = true;
//
// _megaVoiceRadio
//
this._megaVoiceRadio.AutoSize = true;
this._megaVoiceRadio.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.l10NSharpExtender1.SetLocalizableToolTip(this._megaVoiceRadio, null);
this.l10NSharpExtender1.SetLocalizationComment(this._megaVoiceRadio, "Product name");
this.l10NSharpExtender1.SetLocalizationPriority(this._megaVoiceRadio, L10NSharp.LocalizationPriority.NotLocalizable);
this.l10NSharpExtender1.SetLocalizingId(this._megaVoiceRadio, "PublishDialog.Megavoice");
this._megaVoiceRadio.Location = new System.Drawing.Point(3, 50);
this._megaVoiceRadio.Name = "_megaVoiceRadio";
this._megaVoiceRadio.Size = new System.Drawing.Size(91, 21);
this._megaVoiceRadio.TabIndex = 1;
this._megaVoiceRadio.Text = "MegaVoice";
this.toolTip1.SetToolTip(this._megaVoiceRadio, "https://www.megavoice.com/");
this._megaVoiceRadio.UseVisualStyleBackColor = true;
//
// _mp3Radio
//
this._mp3Radio.AutoSize = true;
this._mp3Radio.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.l10NSharpExtender1.SetLocalizableToolTip(this._mp3Radio, null);
this.l10NSharpExtender1.SetLocalizationComment(this._mp3Radio, null);
this.l10NSharpExtender1.SetLocalizingId(this._mp3Radio, "PublishDialog.Mp3");
this._mp3Radio.Location = new System.Drawing.Point(3, 131);
this._mp3Radio.Name = "_mp3Radio";
this._mp3Radio.Size = new System.Drawing.Size(118, 21);
this._mp3Radio.TabIndex = 3;
this._mp3Radio.Text = "Folder of MP3\'s";
this.toolTip1.SetToolTip(this._mp3Radio, "https://en.wikipedia.org/wiki/MP3");
this._mp3Radio.UseVisualStyleBackColor = true;
//
// _oggRadio
//
this._oggRadio.AutoSize = true;
this._oggRadio.Checked = true;
this._oggRadio.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.l10NSharpExtender1.SetLocalizableToolTip(this._oggRadio, null);
this.l10NSharpExtender1.SetLocalizationComment(this._oggRadio, null);
this.l10NSharpExtender1.SetLocalizingId(this._oggRadio, "PublishDialog.Ogg");
this._oggRadio.Location = new System.Drawing.Point(3, 158);
this._oggRadio.Name = "_oggRadio";
this._oggRadio.Size = new System.Drawing.Size(118, 21);
this._oggRadio.TabIndex = 4;
this._oggRadio.TabStop = true;
this._oggRadio.Text = "Folder of Ogg\'s";
this.toolTip1.SetToolTip(this._oggRadio, "https://xiph.org/ogg/");
this._oggRadio.UseVisualStyleBackColor = true;
//
// _publishButton
//
this._publishButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this._publishButton.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.l10NSharpExtender1.SetLocalizableToolTip(this._publishButton, null);
this.l10NSharpExtender1.SetLocalizationComment(this._publishButton, null);
this.l10NSharpExtender1.SetLocalizingId(this._publishButton, "PublishDialog.ExportButton");
this._publishButton.Location = new System.Drawing.Point(479, 278);
this._publishButton.Name = "_publishButton";
this._publishButton.Size = new System.Drawing.Size(80, 33);
this._publishButton.TabIndex = 9;
this._publishButton.Text = "&Export";
this._publishButton.UseVisualStyleBackColor = true;
this._publishButton.Click += new System.EventHandler(this._publishButton_Click);
//
// _destinationLabel
//
this._destinationLabel.AutoEllipsis = true;
this._destinationLabel.AutoSize = true;
this._destinationLabel.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.l10NSharpExtender1.SetLocalizableToolTip(this._destinationLabel, null);
this.l10NSharpExtender1.SetLocalizationComment(this._destinationLabel, null);
this.l10NSharpExtender1.SetLocalizationPriority(this._destinationLabel, L10NSharp.LocalizationPriority.NotLocalizable);
this.l10NSharpExtender1.SetLocalizingId(this._destinationLabel, "PublishDialog.DestinationPath");
this._destinationLabel.Location = new System.Drawing.Point(27, 278);
this._destinationLabel.MaximumSize = new System.Drawing.Size(386, 17);
this._destinationLabel.Name = "_destinationLabel";
this._destinationLabel.Size = new System.Drawing.Size(64, 17);
this._destinationLabel.TabIndex = 8;
this._destinationLabel.Text = "C:\\foobar";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.l10NSharpExtender1.SetLocalizableToolTip(this.label2, null);
this.l10NSharpExtender1.SetLocalizationComment(this.label2, null);
this.l10NSharpExtender1.SetLocalizingId(this.label2, "PublishDialog.DestinationLabel");
this.label2.Location = new System.Drawing.Point(27, 252);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(80, 17);
this.label2.TabIndex = 9;
this.label2.Text = "Destination";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.l10NSharpExtender1.SetLocalizableToolTip(this.label3, null);
this.l10NSharpExtender1.SetLocalizationComment(this.label3, null);
this.l10NSharpExtender1.SetLocalizingId(this.label3, "PublishDialog.AudioFormat");
this.label3.Location = new System.Drawing.Point(3, 0);
this.label3.Name = "label3";
this.label3.Padding = new System.Windows.Forms.Padding(0, 0, 0, 3);
this.label3.Size = new System.Drawing.Size(93, 20);
this.label3.TabIndex = 11;
this.label3.Text = "Audio Format";
//
// _openFolderLink
//
this._openFolderLink.AutoEllipsis = true;
this._openFolderLink.AutoSize = true;
this._openFolderLink.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.l10NSharpExtender1.SetLocalizableToolTip(this._openFolderLink, null);
this.l10NSharpExtender1.SetLocalizationComment(this._openFolderLink, null);
this.l10NSharpExtender1.SetLocalizingId(this._openFolderLink, "PublishDialog.OpenFolderLink");
this._openFolderLink.Location = new System.Drawing.Point(27, 278);
this._openFolderLink.MaximumSize = new System.Drawing.Size(386, 17);
this._openFolderLink.Name = "_openFolderLink";
this._openFolderLink.Size = new System.Drawing.Size(189, 17);
this._openFolderLink.TabIndex = 8;
this._openFolderLink.TabStop = true;
this._openFolderLink.Text = "Open folder of exported audio";
this._openFolderLink.Visible = false;
this._openFolderLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this._openFolderLink_LinkClicked);
//
// _flacRadio
//
this._flacRadio.AutoSize = true;
this._flacRadio.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.l10NSharpExtender1.SetLocalizableToolTip(this._flacRadio, null);
this.l10NSharpExtender1.SetLocalizationComment(this._flacRadio, null);
this.l10NSharpExtender1.SetLocalizingId(this._flacRadio, "PublishDialog.Flac");
this._flacRadio.Location = new System.Drawing.Point(3, 185);
this._flacRadio.Name = "_flacRadio";
this._flacRadio.Size = new System.Drawing.Size(120, 21);
this._flacRadio.TabIndex = 5;
this._flacRadio.Text = "Folder of FLAC\'s";
this.toolTip1.SetToolTip(this._flacRadio, "https://xiph.org/flac/");
this._flacRadio.UseVisualStyleBackColor = true;
//
// _audiBibleRadio
//
this._audiBibleRadio.AutoSize = true;
this._audiBibleRadio.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.l10NSharpExtender1.SetLocalizableToolTip(this._audiBibleRadio, null);
this.l10NSharpExtender1.SetLocalizationComment(this._audiBibleRadio, "Product name");
this.l10NSharpExtender1.SetLocalizationPriority(this._audiBibleRadio, L10NSharp.LocalizationPriority.NotLocalizable);
this.l10NSharpExtender1.SetLocalizingId(this._audiBibleRadio, "PublishDialog.AudiBible");
this._audiBibleRadio.Location = new System.Drawing.Point(3, 23);
this._audiBibleRadio.Name = "_audiBibleRadio";
this._audiBibleRadio.Size = new System.Drawing.Size(80, 21);
this._audiBibleRadio.TabIndex = 0;
this._audiBibleRadio.Text = "AudiBible";
this.toolTip1.SetToolTip(this._audiBibleRadio, "https://www.davarpartners.com/audibible/");
this._audiBibleRadio.UseVisualStyleBackColor = true;
//
// _none
//
this._none.AutoSize = true;
this._none.Checked = true;
this._none.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.l10NSharpExtender1.SetLocalizableToolTip(this._none, null);
this.l10NSharpExtender1.SetLocalizationComment(this._none, "");
this.l10NSharpExtender1.SetLocalizingId(this._none, "PublishDialog._none");
this._none.Location = new System.Drawing.Point(18, 23);
this._none.Name = "_none";
this._none.Size = new System.Drawing.Size(58, 21);
this._none.TabIndex = 1;
this._none.TabStop = true;
this._none.Text = "None";
this._none.UseVisualStyleBackColor = true;
//
// _cancelButton
//
this._cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this._cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this._cancelButton.Font = new System.Drawing.Font("Segoe UI", 9.75F);
this.l10NSharpExtender1.SetLocalizableToolTip(this._cancelButton, null);
this.l10NSharpExtender1.SetLocalizationComment(this._cancelButton, null);
this.l10NSharpExtender1.SetLocalizingId(this._cancelButton, "Common.Cancel");
this._cancelButton.Location = new System.Drawing.Point(565, 278);
this._cancelButton.Name = "_cancelButton";
this._cancelButton.Size = new System.Drawing.Size(75, 33);
this._cancelButton.TabIndex = 10;
this._cancelButton.Text = "&Cancel";
this._cancelButton.UseVisualStyleBackColor = true;
this._cancelButton.Click += new System.EventHandler(this._cancelButton_Click);
//
// _logBox
//
this._logBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this._logBox.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this._logBox.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(171)))), ((int)(((byte)(173)))), ((int)(((byte)(179)))));
this._logBox.CancelRequested = false;
this._logBox.ErrorEncountered = false;
this._logBox.Font = new System.Drawing.Font("Segoe UI", 9F);
this._logBox.GetDiagnosticsMethod = null;
this.l10NSharpExtender1.SetLocalizableToolTip(this._logBox, null);
this.l10NSharpExtender1.SetLocalizationComment(this._logBox, null);
this.l10NSharpExtender1.SetLocalizationPriority(this._logBox, L10NSharp.LocalizationPriority.NotLocalizable);
this.l10NSharpExtender1.SetLocalizingId(this._logBox, "PublishDialog.LogBox");
this._logBox.Location = new System.Drawing.Point(30, 328);
this._logBox.MaxLength = 715827882;
this._logBox.MaxLengthErrorMessage = "Maximum length exceeded!";
this._logBox.Name = "_logBox";
this._logBox.ProgressIndicator = null;
this._logBox.ShowCopyToClipboardMenuItem = false;
this._logBox.ShowDetailsMenuItem = false;
this._logBox.ShowDiagnosticsMenuItem = false;
this._logBox.ShowFontMenuItem = false;
this._logBox.ShowMenu = true;
this._logBox.Size = new System.Drawing.Size(610, 161);
this._logBox.TabIndex = 11;
//
// _changeDestinationLink
//
this._changeDestinationLink.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this._changeDestinationLink.AutoSize = true;
this.l10NSharpExtender1.SetLocalizableToolTip(this._changeDestinationLink, null);
this.l10NSharpExtender1.SetLocalizationComment(this._changeDestinationLink, null);
this.l10NSharpExtender1.SetLocalizingId(this._changeDestinationLink, "PublishDialog._changeDestinationLink");
this._changeDestinationLink.Location = new System.Drawing.Point(476, 252);
this._changeDestinationLink.Name = "_changeDestinationLink";
this._changeDestinationLink.Size = new System.Drawing.Size(109, 13);
this._changeDestinationLink.TabIndex = 7;
this._changeDestinationLink.TabStop = true;
this._changeDestinationLink.Text = "Change Destination...";
this._changeDestinationLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this._changeDestinationLink_LinkClicked);
//
// l10NSharpExtender1
//
this.l10NSharpExtender1.LocalizationManagerId = "HearThis";
this.l10NSharpExtender1.PrefixForNewItems = "PublishDialog";
//
// label1
//
this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.l10NSharpExtender1.SetLocalizableToolTip(this.label1, null);
this.l10NSharpExtender1.SetLocalizationComment(this.label1, null);
this.l10NSharpExtender1.SetLocalizingId(this.label1, "PublishDialog.VerseIndexFormat");
this.label1.Location = new System.Drawing.Point(18, 0);
this.label1.Name = "label1";
this.label1.Padding = new System.Windows.Forms.Padding(0, 0, 0, 3);
this.label1.Size = new System.Drawing.Size(232, 20);
this.label1.TabIndex = 17;
this.label1.Text = "Verse Index Format";
//
// _cueSheet
//
this._cueSheet.AutoSize = true;
this._cueSheet.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.l10NSharpExtender1.SetLocalizableToolTip(this._cueSheet, null);
this.l10NSharpExtender1.SetLocalizationComment(this._cueSheet, "");
this.l10NSharpExtender1.SetLocalizationPriority(this._cueSheet, L10NSharp.LocalizationPriority.NotLocalizable);
this.l10NSharpExtender1.SetLocalizingId(this._cueSheet, "PublishDialog._cueSheet");
this._cueSheet.Location = new System.Drawing.Point(18, 104);
this._cueSheet.Name = "_cueSheet";
this._cueSheet.Size = new System.Drawing.Size(84, 21);
this._cueSheet.TabIndex = 2;
this._cueSheet.Text = "Cue Sheet";
this._cueSheet.UseVisualStyleBackColor = true;
this._cueSheet.Visible = false;
//
// _audacityLabelFile
//
this._audacityLabelFile.AutoSize = true;
this._audacityLabelFile.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.l10NSharpExtender1.SetLocalizableToolTip(this._audacityLabelFile, null);
this.l10NSharpExtender1.SetLocalizationComment(this._audacityLabelFile, "Param 0: \"Scripture App Builder\" (product name); Param 1: \"Audacity\" (product nam" +
"e)");
this.l10NSharpExtender1.SetLocalizingId(this._audacityLabelFile, "PublishDialog._audacityLabelFile");
this._audacityLabelFile.Location = new System.Drawing.Point(18, 50);
this._audacityLabelFile.Name = "_audacityLabelFile";
this._audacityLabelFile.Size = new System.Drawing.Size(126, 21);
this._audacityLabelFile.TabIndex = 3;
this._audacityLabelFile.Text = "{1} Label File ({0})";
this.toolTip1.SetToolTip(this._audacityLabelFile, "https://manual.audacityteam.org/man/label_tracks.html");
this._audacityLabelFile.UseVisualStyleBackColor = true;
this._audacityLabelFile.CheckedChanged += new System.EventHandler(this._audacityLabelFile_CheckedChanged);
//
// _lblBooksToPublish
//
this._lblBooksToPublish.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this._lblBooksToPublish.AutoSize = true;
this._lblBooksToPublish.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.l10NSharpExtender1.SetLocalizableToolTip(this._lblBooksToPublish, null);
this.l10NSharpExtender1.SetLocalizationComment(this._lblBooksToPublish, null);
this.l10NSharpExtender1.SetLocalizingId(this._lblBooksToPublish, "PublishDialog._lblBooksToPublish");
this._lblBooksToPublish.Location = new System.Drawing.Point(18, 0);
this._lblBooksToPublish.Name = "_lblBooksToPublish";
this._lblBooksToPublish.Padding = new System.Windows.Forms.Padding(0, 10, 0, 3);
this._lblBooksToPublish.Size = new System.Drawing.Size(232, 30);
this._lblBooksToPublish.TabIndex = 19;
this._lblBooksToPublish.Text = "Books to Export";
//
// _rdoAllBooks
//
this._rdoAllBooks.AutoSize = true;
this._rdoAllBooks.Checked = true;
this._rdoAllBooks.Font = new System.Drawing.Font("Segoe UI", 9.75F);
this.l10NSharpExtender1.SetLocalizableToolTip(this._rdoAllBooks, null);
this.l10NSharpExtender1.SetLocalizationComment(this._rdoAllBooks, null);
this.l10NSharpExtender1.SetLocalizingId(this._rdoAllBooks, "PublishDialog._rdoAllBooks");
this._rdoAllBooks.Location = new System.Drawing.Point(18, 33);
this._rdoAllBooks.Name = "_rdoAllBooks";
this._rdoAllBooks.Size = new System.Drawing.Size(139, 21);
this._rdoAllBooks.TabIndex = 20;
this._rdoAllBooks.TabStop = true;
this._rdoAllBooks.Text = "All books in project";
this._rdoAllBooks.UseVisualStyleBackColor = true;
//
// _rdoCurrentBook
//
this._rdoCurrentBook.AutoSize = true;
this._rdoCurrentBook.Font = new System.Drawing.Font("Segoe UI", 9.75F);
this.l10NSharpExtender1.SetLocalizableToolTip(this._rdoCurrentBook, null);
this.l10NSharpExtender1.SetLocalizationComment(this._rdoCurrentBook, null);
this.l10NSharpExtender1.SetLocalizingId(this._rdoCurrentBook, "PublishDialog._rdoCurrentBook");
this._rdoCurrentBook.Location = new System.Drawing.Point(18, 60);
this._rdoCurrentBook.Name = "_rdoCurrentBook";
this._rdoCurrentBook.Size = new System.Drawing.Size(124, 21);
this._rdoCurrentBook.TabIndex = 21;
this._rdoCurrentBook.TabStop = true;
this._rdoCurrentBook.Text = "Current Book: {0}";
this._rdoCurrentBook.UseVisualStyleBackColor = true;
//
// _scrAppBuilderRadio
//
this._scrAppBuilderRadio.AutoSize = true;
this._scrAppBuilderRadio.Font = new System.Drawing.Font("Segoe UI", 9.75F);
this.l10NSharpExtender1.SetLocalizableToolTip(this._scrAppBuilderRadio, null);
this.l10NSharpExtender1.SetLocalizationComment(this._scrAppBuilderRadio, "Product name");
this.l10NSharpExtender1.SetLocalizationPriority(this._scrAppBuilderRadio, L10NSharp.LocalizationPriority.NotLocalizable);
this.l10NSharpExtender1.SetLocalizingId(this._scrAppBuilderRadio, "PublishDialog._scrAppBuilderRadio");
this._scrAppBuilderRadio.Location = new System.Drawing.Point(3, 104);
this._scrAppBuilderRadio.Name = "_scrAppBuilderRadio";
this._scrAppBuilderRadio.Size = new System.Drawing.Size(150, 21);
this._scrAppBuilderRadio.TabIndex = 16;
this._scrAppBuilderRadio.TabStop = true;
this._scrAppBuilderRadio.Text = "Scripture App Builder";
this.toolTip1.SetToolTip(this._scrAppBuilderRadio, "https://software.sil.org/scriptureappbuilder/");
this._scrAppBuilderRadio.UseVisualStyleBackColor = true;
this._scrAppBuilderRadio.CheckedChanged += new System.EventHandler(this._scrAppBuilderRadio_CheckedChanged);
//
// _includePhraseLevelLabels
//
this._includePhraseLevelLabels.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this._includePhraseLevelLabels.AutoSize = true;
this._includePhraseLevelLabels.Enabled = false;
this._includePhraseLevelLabels.Font = new System.Drawing.Font("Segoe UI", 9.75F);
this.l10NSharpExtender1.SetLocalizableToolTip(this._includePhraseLevelLabels, null);
this.l10NSharpExtender1.SetLocalizationComment(this._includePhraseLevelLabels, null);
this.l10NSharpExtender1.SetLocalizingId(this._includePhraseLevelLabels, "PublishDialog._chkPhraseLevelLabels");
this._includePhraseLevelLabels.Location = new System.Drawing.Point(18, 77);
this._includePhraseLevelLabels.Name = "_includePhraseLevelLabels";
this._includePhraseLevelLabels.Size = new System.Drawing.Size(232, 21);
this._includePhraseLevelLabels.TabIndex = 18;
this._includePhraseLevelLabels.Text = "Include labels for phrase-level clips";
this._includePhraseLevelLabels.UseVisualStyleBackColor = true;
this._includePhraseLevelLabels.CheckedChanged += new System.EventHandler(this._includePhraseLevelLabels_CheckedChanged);
//
// tableLayoutPanelMain
//
this.tableLayoutPanelMain.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tableLayoutPanelMain.ColumnCount = 3;
this.tableLayoutPanelMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanelMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanelMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanelMain.Controls.Add(this.tableLayoutPanelAudioFormat, 0, 0);
this.tableLayoutPanelMain.Controls.Add(this._tableLayoutRight, 2, 0);
this.tableLayoutPanelMain.Location = new System.Drawing.Point(30, 12);
this.tableLayoutPanelMain.Name = "tableLayoutPanelMain";
this.tableLayoutPanelMain.RowCount = 1;
this.tableLayoutPanelMain.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanelMain.Size = new System.Drawing.Size(610, 215);
this.tableLayoutPanelMain.TabIndex = 16;
//
// tableLayoutPanelAudioFormat
//
this.tableLayoutPanelAudioFormat.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tableLayoutPanelAudioFormat.AutoSize = true;
this.tableLayoutPanelAudioFormat.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.tableLayoutPanelAudioFormat.ColumnCount = 1;
this.tableLayoutPanelAudioFormat.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanelAudioFormat.Controls.Add(this.label3, 0, 0);
this.tableLayoutPanelAudioFormat.Controls.Add(this._audiBibleRadio, 0, 1);
this.tableLayoutPanelAudioFormat.Controls.Add(this._megaVoiceRadio, 0, 2);
this.tableLayoutPanelAudioFormat.Controls.Add(this._saberRadio, 0, 3);
this.tableLayoutPanelAudioFormat.Controls.Add(this._mp3Radio, 0, 5);
this.tableLayoutPanelAudioFormat.Controls.Add(this._oggRadio, 0, 6);
this.tableLayoutPanelAudioFormat.Controls.Add(this._flacRadio, 0, 7);
this.tableLayoutPanelAudioFormat.Controls.Add(this._scrAppBuilderRadio, 0, 4);
this.tableLayoutPanelAudioFormat.Location = new System.Drawing.Point(3, 3);
this.tableLayoutPanelAudioFormat.Name = "tableLayoutPanelAudioFormat";
this.tableLayoutPanelAudioFormat.RowCount = 8;
this.tableLayoutPanelAudioFormat.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanelAudioFormat.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanelAudioFormat.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanelAudioFormat.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanelAudioFormat.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanelAudioFormat.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanelAudioFormat.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanelAudioFormat.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanelAudioFormat.Size = new System.Drawing.Size(156, 209);
this.tableLayoutPanelAudioFormat.TabIndex = 0;
//
// _tableLayoutRight
//
this._tableLayoutRight.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this._tableLayoutRight.AutoSize = true;
this._tableLayoutRight.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this._tableLayoutRight.ColumnCount = 1;
this._tableLayoutRight.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this._tableLayoutRight.Controls.Add(this.tableLayoutPanelVerseIndexFormat, 0, 0);
this._tableLayoutRight.Controls.Add(this._tableLayoutPanelBooksToPublish, 0, 2);
this._tableLayoutRight.Location = new System.Drawing.Point(348, 3);
this._tableLayoutRight.Margin = new System.Windows.Forms.Padding(3, 3, 3, 0);
this._tableLayoutRight.Name = "_tableLayoutRight";
this._tableLayoutRight.RowCount = 3;
this._tableLayoutRight.RowStyles.Add(new System.Windows.Forms.RowStyle());
this._tableLayoutRight.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this._tableLayoutRight.RowStyles.Add(new System.Windows.Forms.RowStyle());
this._tableLayoutRight.Size = new System.Drawing.Size(259, 212);
this._tableLayoutRight.TabIndex = 2;
//
// tableLayoutPanelVerseIndexFormat
//
this.tableLayoutPanelVerseIndexFormat.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tableLayoutPanelVerseIndexFormat.AutoSize = true;
this.tableLayoutPanelVerseIndexFormat.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.tableLayoutPanelVerseIndexFormat.ColumnCount = 1;
this.tableLayoutPanelVerseIndexFormat.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanelVerseIndexFormat.Controls.Add(this._none, 0, 1);
this.tableLayoutPanelVerseIndexFormat.Controls.Add(this.label1, 0, 0);
this.tableLayoutPanelVerseIndexFormat.Controls.Add(this._audacityLabelFile, 0, 2);
this.tableLayoutPanelVerseIndexFormat.Controls.Add(this._cueSheet, 0, 4);
this.tableLayoutPanelVerseIndexFormat.Controls.Add(this._includePhraseLevelLabels, 0, 3);
this.tableLayoutPanelVerseIndexFormat.Location = new System.Drawing.Point(3, 3);
this.tableLayoutPanelVerseIndexFormat.Name = "tableLayoutPanelVerseIndexFormat";
this.tableLayoutPanelVerseIndexFormat.Padding = new System.Windows.Forms.Padding(15, 0, 0, 0);
this.tableLayoutPanelVerseIndexFormat.RowCount = 5;
this.tableLayoutPanelVerseIndexFormat.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanelVerseIndexFormat.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanelVerseIndexFormat.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanelVerseIndexFormat.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanelVerseIndexFormat.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanelVerseIndexFormat.Size = new System.Drawing.Size(253, 128);
this.tableLayoutPanelVerseIndexFormat.TabIndex = 1;
//
// _tableLayoutPanelBooksToPublish
//
this._tableLayoutPanelBooksToPublish.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this._tableLayoutPanelBooksToPublish.AutoSize = true;
this._tableLayoutPanelBooksToPublish.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this._tableLayoutPanelBooksToPublish.ColumnCount = 1;
this._tableLayoutPanelBooksToPublish.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this._tableLayoutPanelBooksToPublish.Controls.Add(this._rdoCurrentBook, 0, 2);
this._tableLayoutPanelBooksToPublish.Controls.Add(this._lblBooksToPublish, 0, 0);
this._tableLayoutPanelBooksToPublish.Controls.Add(this._rdoAllBooks, 0, 1);
this._tableLayoutPanelBooksToPublish.Location = new System.Drawing.Point(3, 125);
this._tableLayoutPanelBooksToPublish.Name = "_tableLayoutPanelBooksToPublish";
this._tableLayoutPanelBooksToPublish.Padding = new System.Windows.Forms.Padding(15, 0, 0, 0);
this._tableLayoutPanelBooksToPublish.RowCount = 3;
this._tableLayoutPanelBooksToPublish.RowStyles.Add(new System.Windows.Forms.RowStyle());
this._tableLayoutPanelBooksToPublish.RowStyles.Add(new System.Windows.Forms.RowStyle());
this._tableLayoutPanelBooksToPublish.RowStyles.Add(new System.Windows.Forms.RowStyle());
this._tableLayoutPanelBooksToPublish.Size = new System.Drawing.Size(253, 84);
this._tableLayoutPanelBooksToPublish.TabIndex = 2;
//
// PublishDialog
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this._cancelButton;
this.ClientSize = new System.Drawing.Size(670, 510);
this.Controls.Add(label4);
this.Controls.Add(this.tableLayoutPanelMain);
this.Controls.Add(this._changeDestinationLink);
this.Controls.Add(this._cancelButton);
this.Controls.Add(this._openFolderLink);
this.Controls.Add(this._logBox);
this.Controls.Add(this.label2);
this.Controls.Add(this._destinationLabel);
this.Controls.Add(this._publishButton);
this.l10NSharpExtender1.SetLocalizableToolTip(this, null);
this.l10NSharpExtender1.SetLocalizationComment(this, null);
this.l10NSharpExtender1.SetLocalizingId(this, "PublishDialog.WindowTitle");
this.MaximizeBox = false;
this.MinimizeBox = false;
this.MinimumSize = new System.Drawing.Size(550, 500);
this.Name = "PublishDialog";
this.ShowIcon = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.Text = "Export Sound Files";
((System.ComponentModel.ISupportInitialize)(this.l10NSharpExtender1)).EndInit();
this.tableLayoutPanelMain.ResumeLayout(false);
this.tableLayoutPanelMain.PerformLayout();
this.tableLayoutPanelAudioFormat.ResumeLayout(false);
this.tableLayoutPanelAudioFormat.PerformLayout();
this._tableLayoutRight.ResumeLayout(false);
this._tableLayoutRight.PerformLayout();
this.tableLayoutPanelVerseIndexFormat.ResumeLayout(false);
this.tableLayoutPanelVerseIndexFormat.PerformLayout();
this._tableLayoutPanelBooksToPublish.ResumeLayout(false);
this._tableLayoutPanelBooksToPublish.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.RadioButton _saberRadio;
private System.Windows.Forms.RadioButton _megaVoiceRadio;
private System.Windows.Forms.RadioButton _mp3Radio;
private System.Windows.Forms.RadioButton _oggRadio;
private System.Windows.Forms.Button _publishButton;
private System.Windows.Forms.Label _destinationLabel;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private SIL.Windows.Forms.Progress.LogBox _logBox;
private System.Windows.Forms.LinkLabel _openFolderLink;
private System.Windows.Forms.ToolTip toolTip1;
private System.Windows.Forms.RadioButton _flacRadio;
private System.Windows.Forms.Button _cancelButton;
private System.Windows.Forms.LinkLabel _changeDestinationLink;
private L10NSharp.UI.L10NSharpExtender l10NSharpExtender1;
private System.Windows.Forms.RadioButton _audiBibleRadio;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanelMain;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanelAudioFormat;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanelVerseIndexFormat;
private System.Windows.Forms.RadioButton _none;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.RadioButton _audacityLabelFile;
private System.Windows.Forms.RadioButton _cueSheet;
private System.Windows.Forms.TableLayoutPanel _tableLayoutRight;
private System.Windows.Forms.TableLayoutPanel _tableLayoutPanelBooksToPublish;
private System.Windows.Forms.RadioButton _rdoCurrentBook;
private System.Windows.Forms.Label _lblBooksToPublish;
private System.Windows.Forms.RadioButton _rdoAllBooks;
private System.Windows.Forms.RadioButton _scrAppBuilderRadio;
private System.Windows.Forms.CheckBox _includePhraseLevelLabels;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Batch.Protocol
{
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// FileOperations operations.
/// </summary>
public partial interface IFileOperations
{
/// <summary>
/// Deletes the specified task file from the compute node where the
/// task ran.
/// </summary>
/// <param name='jobId'>
/// The ID of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The ID of the task whose file you want to delete.
/// </param>
/// <param name='filePath'>
/// The path to the task file that you want to delete.
/// </param>
/// <param name='recursive'>
/// Whether to delete children of a directory. If the filePath
/// parameter represents a directory instead of a file, you can set
/// recursive to true to delete the directory and all of the files and
/// subdirectories in it. If recursive is false then the directory must
/// be empty or deletion will fail.
/// </param>
/// <param name='fileDeleteFromTaskOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<FileDeleteFromTaskHeaders>> DeleteFromTaskWithHttpMessagesAsync(string jobId, string taskId, string filePath, bool? recursive = default(bool?), FileDeleteFromTaskOptions fileDeleteFromTaskOptions = default(FileDeleteFromTaskOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Returns the content of the specified task file.
/// </summary>
/// <param name='jobId'>
/// The ID of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The ID of the task whose file you want to retrieve.
/// </param>
/// <param name='filePath'>
/// The path to the task file that you want to get the content of.
/// </param>
/// <param name='fileGetFromTaskOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.IO.Stream,FileGetFromTaskHeaders>> GetFromTaskWithHttpMessagesAsync(string jobId, string taskId, string filePath, FileGetFromTaskOptions fileGetFromTaskOptions = default(FileGetFromTaskOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets the properties of the specified task file.
/// </summary>
/// <param name='jobId'>
/// The ID of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The ID of the task whose file you want to get the properties of.
/// </param>
/// <param name='filePath'>
/// The path to the task file that you want to get the properties of.
/// </param>
/// <param name='fileGetPropertiesFromTaskOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<FileGetPropertiesFromTaskHeaders>> GetPropertiesFromTaskWithHttpMessagesAsync(string jobId, string taskId, string filePath, FileGetPropertiesFromTaskOptions fileGetPropertiesFromTaskOptions = default(FileGetPropertiesFromTaskOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Deletes the specified file from the compute node.
/// </summary>
/// <param name='poolId'>
/// The ID of the pool that contains the compute node.
/// </param>
/// <param name='nodeId'>
/// The ID of the compute node from which you want to delete the file.
/// </param>
/// <param name='filePath'>
/// The path to the file that you want to delete.
/// </param>
/// <param name='recursive'>
/// Whether to delete children of a directory. If the filePath
/// parameter represents a directory instead of a file, you can set
/// recursive to true to delete the directory and all of the files and
/// subdirectories in it. If recursive is false then the directory must
/// be empty or deletion will fail.
/// </param>
/// <param name='fileDeleteFromComputeNodeOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<FileDeleteFromComputeNodeHeaders>> DeleteFromComputeNodeWithHttpMessagesAsync(string poolId, string nodeId, string filePath, bool? recursive = default(bool?), FileDeleteFromComputeNodeOptions fileDeleteFromComputeNodeOptions = default(FileDeleteFromComputeNodeOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Returns the content of the specified compute node file.
/// </summary>
/// <param name='poolId'>
/// The ID of the pool that contains the compute node.
/// </param>
/// <param name='nodeId'>
/// The ID of the compute node that contains the file.
/// </param>
/// <param name='filePath'>
/// The path to the compute node file that you want to get the content
/// of.
/// </param>
/// <param name='fileGetFromComputeNodeOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.IO.Stream,FileGetFromComputeNodeHeaders>> GetFromComputeNodeWithHttpMessagesAsync(string poolId, string nodeId, string filePath, FileGetFromComputeNodeOptions fileGetFromComputeNodeOptions = default(FileGetFromComputeNodeOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets the properties of the specified compute node file.
/// </summary>
/// <param name='poolId'>
/// The ID of the pool that contains the compute node.
/// </param>
/// <param name='nodeId'>
/// The ID of the compute node that contains the file.
/// </param>
/// <param name='filePath'>
/// The path to the compute node file that you want to get the
/// properties of.
/// </param>
/// <param name='fileGetPropertiesFromComputeNodeOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<FileGetPropertiesFromComputeNodeHeaders>> GetPropertiesFromComputeNodeWithHttpMessagesAsync(string poolId, string nodeId, string filePath, FileGetPropertiesFromComputeNodeOptions fileGetPropertiesFromComputeNodeOptions = default(FileGetPropertiesFromComputeNodeOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists the files in a task's directory on its compute node.
/// </summary>
/// <param name='jobId'>
/// The ID of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The ID of the task whose files you want to list.
/// </param>
/// <param name='recursive'>
/// Whether to list children of a directory. This parameter can be used
/// in combination with the filter parameter to list specific type of
/// files.
/// </param>
/// <param name='fileListFromTaskOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NodeFile>,FileListFromTaskHeaders>> ListFromTaskWithHttpMessagesAsync(string jobId, string taskId, bool? recursive = default(bool?), FileListFromTaskOptions fileListFromTaskOptions = default(FileListFromTaskOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists all of the files in task directories on the specified compute
/// node.
/// </summary>
/// <param name='poolId'>
/// The ID of the pool that contains the compute node.
/// </param>
/// <param name='nodeId'>
/// The ID of the compute node whose files you want to list.
/// </param>
/// <param name='recursive'>
/// Whether to list children of a directory.
/// </param>
/// <param name='fileListFromComputeNodeOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NodeFile>,FileListFromComputeNodeHeaders>> ListFromComputeNodeWithHttpMessagesAsync(string poolId, string nodeId, bool? recursive = default(bool?), FileListFromComputeNodeOptions fileListFromComputeNodeOptions = default(FileListFromComputeNodeOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists the files in a task's directory on its compute node.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='fileListFromTaskNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NodeFile>,FileListFromTaskHeaders>> ListFromTaskNextWithHttpMessagesAsync(string nextPageLink, FileListFromTaskNextOptions fileListFromTaskNextOptions = default(FileListFromTaskNextOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists all of the files in task directories on the specified compute
/// node.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='fileListFromComputeNodeNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NodeFile>,FileListFromComputeNodeHeaders>> ListFromComputeNodeNextWithHttpMessagesAsync(string nextPageLink, FileListFromComputeNodeNextOptions fileListFromComputeNodeNextOptions = default(FileListFromComputeNodeNextOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
}
}
| |
//
// PrivateKey.cs - Private Key (PVK) Format Implementation
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Globalization;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using Mono.Security.Cryptography;
namespace Mono.Security.Authenticode {
// References:
// a. http://www.drh-consultancy.demon.co.uk/pvk.html
#if INSIDE_SYSTEM
internal
#else
public
#endif
class PrivateKey {
private const uint magic = 0xb0b5f11e;
private bool encrypted;
private RSA rsa;
private bool weak;
private int keyType;
public PrivateKey ()
{
keyType = 2; // required for MS makecert !!!
}
public PrivateKey (byte[] data, string password)
{
if (data == null)
throw new ArgumentNullException ("data");
if (!Decode (data, password)) {
throw new CryptographicException (
("Invalid data and/or password"));
}
}
public bool Encrypted {
get { return encrypted; }
}
public int KeyType {
get { return keyType; }
set { keyType = value; }
}
public RSA RSA {
get { return rsa; }
set { rsa = value; }
}
public bool Weak {
get { return ((encrypted) ? weak : true); }
set { weak = value; }
}
private byte[] DeriveKey (byte[] salt, string password)
{
byte[] pwd = Encoding.ASCII.GetBytes (password);
SHA1 sha1 = (SHA1)SHA1.Create ();
sha1.TransformBlock (salt, 0, salt.Length, salt, 0);
sha1.TransformFinalBlock (pwd, 0, pwd.Length);
byte[] key = new byte [16];
Buffer.BlockCopy (sha1.Hash, 0, key, 0, 16);
sha1.Clear ();
Array.Clear (pwd, 0, pwd.Length);
return key;
}
private bool Decode (byte[] pvk, string password)
{
// DWORD magic
if (BitConverterLE.ToUInt32 (pvk, 0) != magic)
return false;
// DWORD reserved
if (BitConverterLE.ToUInt32 (pvk, 4) != 0x0)
return false;
// DWORD keytype
keyType = BitConverterLE.ToInt32 (pvk, 8);
// DWORD encrypted
encrypted = (BitConverterLE.ToUInt32 (pvk, 12) == 1);
// DWORD saltlen
int saltlen = BitConverterLE.ToInt32 (pvk, 16);
// DWORD keylen
int keylen = BitConverterLE.ToInt32 (pvk, 20);
byte[] keypair = new byte [keylen];
Buffer.BlockCopy (pvk, 24 + saltlen, keypair, 0, keylen);
// read salt (if present)
if (saltlen > 0) {
if (password == null)
return false;
byte[] salt = new byte [saltlen];
Buffer.BlockCopy (pvk, 24, salt, 0, saltlen);
// first try with full (128) bits
byte[] key = DeriveKey (salt, password);
// decrypt in place and try this
RC4 rc4 = RC4.Create ();
ICryptoTransform dec = rc4.CreateDecryptor (key, null);
dec.TransformBlock (keypair, 8, keypair.Length - 8, keypair, 8);
try {
rsa = CryptoConvert.FromCapiPrivateKeyBlob (keypair);
weak = false;
}
catch (CryptographicException) {
weak = true;
// second chance using weak crypto
Buffer.BlockCopy (pvk, 24 + saltlen, keypair, 0, keylen);
// truncate the key to 40 bits
Array.Clear (key, 5, 11);
// decrypt
RC4 rc4b = RC4.Create ();
dec = rc4b.CreateDecryptor (key, null);
dec.TransformBlock (keypair, 8, keypair.Length - 8, keypair, 8);
rsa = CryptoConvert.FromCapiPrivateKeyBlob (keypair);
}
Array.Clear (key, 0, key.Length);
}
else {
weak = true;
// read unencrypted keypair
rsa = CryptoConvert.FromCapiPrivateKeyBlob (keypair);
Array.Clear (keypair, 0, keypair.Length);
}
// zeroize pvk (which could contain the unencrypted private key)
Array.Clear (pvk, 0, pvk.Length);
return (rsa != null);
}
public void Save (string filename)
{
Save (filename, null);
}
public void Save (string filename, string password)
{
if (filename == null)
throw new ArgumentNullException ("filename");
byte[] blob = null;
FileStream fs = File.Open (filename, FileMode.Create, FileAccess.Write);
try {
// header
byte[] empty = new byte [4];
byte[] data = BitConverterLE.GetBytes (magic);
fs.Write (data, 0, 4); // magic
fs.Write (empty, 0, 4); // reserved
data = BitConverterLE.GetBytes (keyType);
fs.Write (data, 0, 4); // key type
encrypted = (password != null);
blob = CryptoConvert.ToCapiPrivateKeyBlob (rsa);
if (encrypted) {
data = BitConverterLE.GetBytes (1);
fs.Write (data, 0, 4); // encrypted
data = BitConverterLE.GetBytes (16);
fs.Write (data, 0, 4); // saltlen
data = BitConverterLE.GetBytes (blob.Length);
fs.Write (data, 0, 4); // keylen
byte[] salt = new byte [16];
RC4 rc4 = RC4.Create ();
byte[] key = null;
try {
// generate new salt (16 bytes)
RandomNumberGenerator rng = RandomNumberGenerator.Create ();
rng.GetBytes (salt);
fs.Write (salt, 0, salt.Length);
key = DeriveKey (salt, password);
if (Weak)
Array.Clear (key, 5, 11);
ICryptoTransform enc = rc4.CreateEncryptor (key, null);
// we don't encrypt the header part of the BLOB
enc.TransformBlock (blob, 8, blob.Length - 8, blob, 8);
}
finally {
Array.Clear (salt, 0, salt.Length);
Array.Clear (key, 0, key.Length);
rc4.Clear ();
}
}
else {
fs.Write (empty, 0, 4); // encrypted
fs.Write (empty, 0, 4); // saltlen
data = BitConverterLE.GetBytes (blob.Length);
fs.Write (data, 0, 4); // keylen
}
fs.Write (blob, 0, blob.Length);
}
finally {
// BLOB may include an uncrypted keypair
Array.Clear (blob, 0, blob.Length);
fs.Close ();
}
}
static public PrivateKey CreateFromFile (string filename)
{
return CreateFromFile (filename, null);
}
static public PrivateKey CreateFromFile (string filename, string password)
{
if (filename == null)
throw new ArgumentNullException ("filename");
byte[] pvk = null;
using (FileStream fs = File.Open (filename, FileMode.Open, FileAccess.Read, FileShare.Read)) {
pvk = new byte [fs.Length];
fs.Read (pvk, 0, pvk.Length);
fs.Close ();
}
return new PrivateKey (pvk, password);
}
}
}
| |
using NServiceKit.DesignPatterns.Model;
using ProtoBuf;
using System;
using System.Runtime.Serialization;
namespace Northwind.Common.ServiceModel
{
[ProtoContract(ImplicitFields = ImplicitFields.AllPublic, InferTagFromName = true)]
[DataContract]
[Serializable]
public class EmployeeDto
: IHasIntId
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string LastName { get; set; }
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string Title { get; set; }
[DataMember]
public string TitleOfCourtesy { get; set; }
[DataMember]
public DateTime? BirthDate { get; set; }
[DataMember]
public DateTime? HireDate { get; set; }
[DataMember]
public string Address { get; set; }
[DataMember]
public string City { get; set; }
[DataMember]
public string Region { get; set; }
[DataMember]
public string PostalCode { get; set; }
[DataMember]
public string Country { get; set; }
[DataMember]
public string HomePhone { get; set; }
[DataMember]
public string Extension { get; set; }
//Some serializers can't handle bytes so disabling for all
//
//[DataMember]
public byte[] Photo { get; set; }
[DataMember]
public string Notes { get; set; }
[DataMember]
public int? ReportsTo { get; set; }
[DataMember]
public string PhotoPath { get; set; }
}
[ProtoContract(ImplicitFields = ImplicitFields.AllPublic, InferTagFromName = true)]
[DataContract]
[Serializable]
public class CategoryDto : IHasIntId
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string CategoryName { get; set; }
[DataMember]
public string Description { get; set; }
//[DataMember]
public byte[] Picture { get; set; }
}
[ProtoContract(ImplicitFields = ImplicitFields.AllPublic, InferTagFromName = true)]
[DataContract]
[Serializable]
public class CustomerDto
: IHasStringId
{
[DataMember]
public string Id { get; set; }
[DataMember]
public string CompanyName { get; set; }
[DataMember]
public string ContactName { get; set; }
[DataMember]
public string ContactTitle { get; set; }
[DataMember]
public string Address { get; set; }
[DataMember]
public string City { get; set; }
[DataMember]
public string Region { get; set; }
[DataMember]
public string PostalCode { get; set; }
[DataMember]
public string Country { get; set; }
[DataMember]
public string Phone { get; set; }
[DataMember]
public string Fax { get; set; }
//[DataMember]
public byte[] Picture { get; set; }
public override bool Equals(object obj)
{
var other = obj as CustomerDto;
if (other == null) return false;
return this.Address == other.Address
&& this.City == other.City
&& this.CompanyName == other.CompanyName
&& this.ContactName == other.ContactName
&& this.ContactTitle == other.ContactTitle
&& this.Country == other.Country
&& this.Fax == other.Fax
&& this.Id == other.Id
&& this.Phone == other.Phone
&& this.Picture == other.Picture
&& this.PostalCode == other.PostalCode
&& this.Region == other.Region;
}
}
[ProtoContract(ImplicitFields = ImplicitFields.AllPublic, InferTagFromName = true)]
[DataContract]
[Serializable]
public class ShipperDto : IHasIntId
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string CompanyName { get; set; }
[DataMember]
public string Phone { get; set; }
}
[ProtoContract(ImplicitFields = ImplicitFields.AllPublic, InferTagFromName = true)]
[DataContract]
[Serializable]
public class SupplierDto : IHasIntId
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string CompanyName { get; set; }
[DataMember]
public string ContactName { get; set; }
[DataMember]
public string ContactTitle { get; set; }
[DataMember]
public string Address { get; set; }
[DataMember]
public string City { get; set; }
[DataMember]
public string Region { get; set; }
[DataMember]
public string PostalCode { get; set; }
[DataMember]
public string Country { get; set; }
[DataMember]
public string Phone { get; set; }
[DataMember]
public string Fax { get; set; }
[DataMember]
public string HomePage { get; set; }
public override bool Equals(object obj)
{
var other = obj as SupplierDto;
if (other == null) return false;
return this.Id == other.Id
&& this.CompanyName == other.CompanyName
&& this.ContactName == other.ContactName
&& this.ContactTitle == other.ContactTitle
&& this.Address == other.Address
&& this.City == other.City
&& this.Region == other.Region
&& this.PostalCode == other.PostalCode
&& this.Country == other.Country
&& this.Phone == other.Phone
&& this.Fax == other.Fax
&& this.HomePage == other.HomePage;
}
}
[ProtoContract(ImplicitFields = ImplicitFields.AllPublic, InferTagFromName = true)]
[DataContract]
[Serializable]
public class OrderDto
: IHasIntId
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string CustomerId { get; set; }
[DataMember]
public int EmployeeId { get; set; }
[DataMember]
public DateTime? OrderDate { get; set; }
[DataMember]
public DateTime? RequiredDate { get; set; }
[DataMember]
public DateTime? ShippedDate { get; set; }
[DataMember]
public int? ShipVia { get; set; }
[DataMember]
public decimal Freight { get; set; }
[DataMember]
public string ShipName { get; set; }
[DataMember]
public string ShipAddress { get; set; }
[DataMember]
public string ShipCity { get; set; }
[DataMember]
public string ShipRegion { get; set; }
[DataMember]
public string ShipPostalCode { get; set; }
[DataMember]
public string ShipCountry { get; set; }
public override bool Equals(object obj)
{
var other = obj as OrderDto;
if (other == null) return false;
return this.Id == other.Id
&& this.CustomerId == other.CustomerId
&& this.EmployeeId == other.EmployeeId
&& this.OrderDate == other.OrderDate
&& this.RequiredDate == other.RequiredDate
&& this.ShippedDate == other.ShippedDate
&& this.ShipVia == other.ShipVia
&& this.Freight == other.Freight
&& this.ShipName == other.ShipName
&& this.ShipAddress == other.ShipAddress
&& this.ShipCity == other.ShipCity
&& this.ShipRegion == other.ShipRegion
&& this.ShipPostalCode == other.ShipPostalCode
&& this.ShipCountry == other.ShipCountry;
}
}
[ProtoContract(ImplicitFields = ImplicitFields.AllPublic, InferTagFromName = true)]
[DataContract]
[Serializable]
public class ProductDto : IHasIntId
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string ProductName { get; set; }
[DataMember]
public int SupplierId { get; set; }
[DataMember]
public int CategoryId { get; set; }
[DataMember]
public string QuantityPerUnit { get; set; }
[DataMember]
public decimal UnitPrice { get; set; }
[DataMember]
public short UnitsInStock { get; set; }
[DataMember]
public short UnitsOnOrder { get; set; }
[DataMember]
public short ReorderLevel { get; set; }
[DataMember]
public bool Discontinued { get; set; }
}
[ProtoContract(ImplicitFields = ImplicitFields.AllPublic, InferTagFromName = true)]
[DataContract]
[Serializable]
public class OrderDetailDto
: IHasStringId
{
[DataMember]
public string Id { get; set; }
//public string Id { get { return this.OrderId + "/" + this.ProductId; } } //Protobuf no like
[DataMember]
public int OrderId { get; set; }
[DataMember]
public int ProductId { get; set; }
[DataMember]
public decimal UnitPrice { get; set; }
[DataMember]
public short Quantity { get; set; }
[DataMember]
public double Discount { get; set; }
public override bool Equals(object obj)
{
var other = obj as OrderDetailDto;
if (other == null) return false;
return this.Id == other.Id
&& this.OrderId == other.OrderId
&& this.ProductId == other.ProductId
&& this.UnitPrice == other.UnitPrice
&& this.Quantity == other.Quantity
&& this.Discount == other.Discount;
}
}
[ProtoContract(ImplicitFields = ImplicitFields.AllPublic, InferTagFromName = true)]
[DataContract]
[Serializable]
public class CustomerCustomerDemoDto : IHasStringId
{
[DataMember]
public string Id { get; set; }
[DataMember]
public string CustomerTypeId { get; set; }
}
[ProtoContract(ImplicitFields = ImplicitFields.AllPublic, InferTagFromName = true)]
[DataContract]
[Serializable]
public class CustomerDemographicDto : IHasStringId
{
[DataMember]
public string Id { get; set; }
[DataMember]
public string CustomerDesc { get; set; }
}
[ProtoContract(ImplicitFields = ImplicitFields.AllPublic, InferTagFromName = true)]
[DataContract]
[Serializable]
public class RegionDto : IHasIntId
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string RegionDescription { get; set; }
}
[ProtoContract(ImplicitFields = ImplicitFields.AllPublic, InferTagFromName = true)]
[DataContract]
[Serializable]
public class TerritoryDto : IHasStringId
{
[DataMember]
public string Id { get; set; }
[DataMember]
public string TerritoryDescription { get; set; }
[DataMember]
public int RegionId { get; set; }
}
[ProtoContract(ImplicitFields = ImplicitFields.AllPublic, InferTagFromName = true)]
[DataContract]
[Serializable]
public class EmployeeTerritoryDto : IHasStringId
{
[DataMember]
public string Id { get; set; }
//public string Id { get { return this.EmployeeId + "/" + this.TerritoryId; } } //Protobuf no like
[DataMember]
public int EmployeeId { get; set; }
[DataMember]
public string TerritoryId { get; set; }
}
}
| |
using DevExpress.Mvvm.UI.Interactivity;
using DevExpress.Mvvm.UI.Interactivity.Internal;
using NUnit.Framework;
using System.Windows;
using DevExpress.Mvvm.Native;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
namespace DevExpress.Mvvm.UI.Tests {
public class FakeTrigger : TriggerBase<DependencyObject> {
}
public class FakeBehavior : Behavior<FrameworkElement> {
}
public class TestBehavior : Behavior<Button> {
internal int attachedFireCount;
internal int detachingFireCount;
protected override void OnAttached() {
base.OnAttached();
attachedFireCount++;
}
protected override void OnDetaching() {
base.OnDetaching();
detachingFireCount++;
}
}
public class TestBehaviorWithBindableProperty : TestBehavior {
public object MyProperty {
get { return (object)GetValue(MyPropertyProperty); }
set { SetValue(MyPropertyProperty, value); }
}
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register("MyProperty", typeof(object), typeof(TestBehaviorWithBindableProperty), new PropertyMetadata(null));
}
[TestFixture]
public class AttachedBehaviorTests : BaseWpfFixture {
TestBehavior behavior;
Button button;
protected override void SetUpCore() {
base.SetUpCore();
behavior = new TestBehavior();
button = new Button();
}
protected override void TearDownCore() {
base.TearDownCore();
behavior = null;
button = null;
}
[Test, Asynchronous]
public void Q458047_BindAttachedBehaviorInPopup() {
Popup popup = new Popup();
var behavior = new TestBehaviorWithBindableProperty();
BindingOperations.SetBinding(behavior, TestBehaviorWithBindableProperty.MyPropertyProperty, new Binding());
Interaction.GetBehaviors(button).Add(behavior);
popup.Child = button;
button.DataContext = "test";
EnqueueShowWindow();
EnqueueCallback(() => {
popup.IsOpen = true;
});
EnqueueWindowUpdateLayout();
EnqueueCallback(() => {
Assert.AreEqual("test", behavior.MyProperty);
popup.IsOpen = false;
});
EnqueueTestComplete();
}
[Test, Asynchronous]
public void InheritDataContextWhenElementInTree() {
button.DataContext = "test";
Window.Content = button;
EnqueueShowWindow();
EnqueueCallback(() => {
Assert.AreEqual(0, behavior.attachedFireCount);
Interaction.GetBehaviors(button).Add(behavior);
Assert.AreEqual(1, behavior.attachedFireCount);
Assert.AreEqual(1, behavior.attachedFireCount);
Assert.AreEqual(0, behavior.detachingFireCount);
});
EnqueueTestComplete();
}
[Test, Asynchronous]
public void InheritDataContextWhenElementInTree2() {
Border border = new Border() { DataContext = "test", Child = button };
Window.Content = border;
EnqueueShowWindow();
EnqueueCallback(() => {
Assert.AreEqual(0, behavior.attachedFireCount);
Interaction.GetBehaviors(button).Add(behavior);
Assert.AreEqual(1, behavior.attachedFireCount);
Assert.AreEqual(1, behavior.attachedFireCount);
Assert.AreEqual(0, behavior.detachingFireCount);
});
EnqueueTestComplete();
}
[Test]
public void InheritDataContextWhenElementNotInTree() {
Interaction.GetBehaviors(button).Add(behavior);
button.DataContext = "test";
Assert.AreEqual(1, behavior.attachedFireCount);
Assert.AreEqual(0, behavior.detachingFireCount);
}
[Test]
public void InheritDataContextWhenElementNotInTree3() {
Interaction.GetBehaviors(button).Add(behavior);
Assert.AreEqual(1, behavior.attachedFireCount);
Assert.AreEqual(0, behavior.detachingFireCount);
Border border = new Border() { DataContext = "test", Child = button };
Interaction.GetBehaviors(button).Remove(behavior);
Assert.AreEqual(1, behavior.attachedFireCount);
Assert.AreEqual(1, behavior.detachingFireCount);
}
[Test]
public void BehaviorShouldNotBeFrozen_Test00_T196013() {
var behavior = new FakeBehavior();
Assert.IsFalse(behavior.IsFrozen);
Assert.IsFalse(behavior.CanFreeze);
}
[Test]
public void BehaviorShouldNotBeFrozen_Test01_T196013() {
var content = new FrameworkElementFactory(typeof(ContentControl));
content.SetValue(ContentControl.ContentProperty, new FakeBehavior());
var template = new DataTemplate() { VisualTree = content };
template.Seal();
var behavior = ((ContentControl)template.LoadContent()).Content as Behavior;
Assert.IsFalse(behavior.IsFrozen);
Assert.IsFalse(behavior.CanFreeze);
}
}
[TestFixture]
public class AttachedBehaviorDesignModeTests : BaseWpfFixture {
public class TestBehaviorRegular : Behavior<FrameworkElement> { }
public class TestBehaviorAllowAttachInDesignMode : Behavior<FrameworkElement> {
protected override bool AllowAttachInDesignMode {
get { return true; }
}
}
public class TestBehaviorNotAllowAttachInDesignMode : Behavior<FrameworkElement> {
protected override bool AllowAttachInDesignMode {
get { return false; }
}
}
protected override void TearDownCore() {
base.TearDownCore();
ViewModelDesignHelper.IsInDesignModeOverride = false;
}
#region RunTime
[Test]
public void TestBehaviorRegular_AttachInRunTime() {
CheckAttach(new TestBehaviorRegular());
}
[Test]
public void TestBehaviorAllowAttachInDesignTime_AttachInRunTime() {
CheckAttach(new TestBehaviorAllowAttachInDesignMode());
}
[Test]
public void TestBehaviorNotAllowAttachInDesignMode_AttachInRunTime() {
CheckAttach(new TestBehaviorNotAllowAttachInDesignMode());
}
[Test]
public void TestBehaviorRegular_AttachInRunTime_InteractionHelperOnBehavior() {
var b = new TestBehaviorRegular();
InteractionHelper.SetBehaviorInDesignMode(b, InteractionBehaviorInDesignMode.AsWellAsNotInDesignMode);
CheckAttach(b);
}
[Test]
public void TestBehaviorAllowAttachInDesignMode_AttachInRunTime_InteractionHelperOnBehavior() {
var b = new TestBehaviorAllowAttachInDesignMode();
InteractionHelper.SetBehaviorInDesignMode(b, InteractionBehaviorInDesignMode.AsWellAsNotInDesignMode);
CheckAttach(b);
}
[Test]
public void TestBehaviorNotAllowAttachInDesignMode_AttachInRunTime_InteractionHelperOnBehavior() {
var b = new TestBehaviorNotAllowAttachInDesignMode();
InteractionHelper.SetBehaviorInDesignMode(b, InteractionBehaviorInDesignMode.AsWellAsNotInDesignMode);
CheckAttach(b);
}
[Test]
public void TestBehaviorRegular_AttachInRunTime_InteractionHelperOnAssociatedObject() {
Grid element = new Grid();
InteractionHelper.SetBehaviorInDesignMode(element, InteractionBehaviorInDesignMode.AsWellAsNotInDesignMode);
CheckAttach(new TestBehaviorRegular(), element);
}
[Test]
public void TestBehaviorAllowAttachInDesignMode_AttachInRunTime_InteractionHelperOnAssociatedObject() {
Grid element = new Grid();
InteractionHelper.SetBehaviorInDesignMode(element, InteractionBehaviorInDesignMode.AsWellAsNotInDesignMode);
CheckAttach(new TestBehaviorAllowAttachInDesignMode(), element);
}
[Test]
public void TestBehaviorNotAllowAttachInDesignMode_AttachInRunTime_InteractionHelperOnAssociatedObject() {
Grid element = new Grid();
InteractionHelper.SetBehaviorInDesignMode(element, InteractionBehaviorInDesignMode.AsWellAsNotInDesignMode);
CheckAttach(new TestBehaviorNotAllowAttachInDesignMode(), element);
}
[Test]
public void TestEnableBehaviorsInDesignTime() {
ViewModelDesignHelper.IsInDesignModeOverride = true;
var b = new TestBehaviorNotAllowAttachInDesignMode();
var border = new Border();
InteractionHelper.SetEnableBehaviorsInDesignTime(border, true);
var button = new Button();
border.Child = button;
CheckAttach(b, button);
}
[Test]
public void TestEnableBehaviorsInDesignTimeForEventTriggers() {
ViewModelDesignHelper.IsInDesignModeOverride = true;
var trigger = new FakeTrigger();
var border = new Border();
var button = new Button();
border.Child = button;
InteractionHelper.SetEnableBehaviorsInDesignTime(border, true);
CheckAttach(trigger, button);
}
[Test]
public void TestAssociatedObjectImplementsINotifyPropertyChanged() {
Grid element = new Grid();
var testBehavior = new FakeBehavior();
element.SetBinding(Grid.TagProperty, new Binding() { Path = new PropertyPath("AssociatedObject"), Source = testBehavior, Mode = BindingMode.OneWay });
Interaction.GetBehaviors(element).Add(testBehavior);
Assert.AreSame(element, element.Tag);
}
[Test]
public void TestAssociatedObjectImplementsINotifyPropertyChanged2() {
Grid element = new Grid();
var testBehavior = new EventToCommand();
BindingOperations.SetBinding(testBehavior, EventToCommand.CommandParameterProperty, new Binding() { Path = new PropertyPath("AssociatedObject"),
RelativeSource = RelativeSource.Self
});
Interaction.GetBehaviors(element).Add(testBehavior);
Assert.AreSame(element, testBehavior.CommandParameter);
Interaction.GetBehaviors(element).Remove(testBehavior);
Assert.IsNull(testBehavior.CommandParameter);
}
#endregion
#region DesignTime
[Test]
public void TestBehaviorRegular_NotAttachInDesignTime() {
ViewModelDesignHelper.IsInDesignModeOverride = true;
CheckNotAttach(new TestBehaviorRegular());
}
[Test]
public void TestBehaviorAllowAttachInDesignTime_AttachInDesignTime() {
ViewModelDesignHelper.IsInDesignModeOverride = true;
CheckAttach(new TestBehaviorAllowAttachInDesignMode());
}
[Test]
public void TestBehaviorNotAllowAttachInDesignMode_AttachInDesignTime() {
ViewModelDesignHelper.IsInDesignModeOverride = true;
CheckNotAttach(new TestBehaviorNotAllowAttachInDesignMode());
}
[Test]
public void TestBehaviorRegular_AttachInDesignTime_InteractionHelperOnBehavior() {
ViewModelDesignHelper.IsInDesignModeOverride = true;
var b = new TestBehaviorRegular();
InteractionHelper.SetBehaviorInDesignMode(b, InteractionBehaviorInDesignMode.AsWellAsNotInDesignMode);
CheckAttach(b);
}
[Test]
public void TestBehaviorAllowAttachInDesignMode_AttachInDesignTime_InteractionHelperOnBehavior() {
ViewModelDesignHelper.IsInDesignModeOverride = true;
var b = new TestBehaviorAllowAttachInDesignMode();
InteractionHelper.SetBehaviorInDesignMode(b, InteractionBehaviorInDesignMode.AsWellAsNotInDesignMode);
CheckAttach(b);
}
[Test]
public void TestBehaviorNotAllowAttachInDesignMode_AttachInDesignTime_InteractionHelperOnBehavior() {
ViewModelDesignHelper.IsInDesignModeOverride = true;
var b = new TestBehaviorNotAllowAttachInDesignMode();
InteractionHelper.SetBehaviorInDesignMode(b, InteractionBehaviorInDesignMode.AsWellAsNotInDesignMode);
CheckNotAttach(b);
}
[Test]
public void TestBehaviorRegular_AttachInDesignTime_InteractionHelperOnAssociatedObject() {
ViewModelDesignHelper.IsInDesignModeOverride = true;
Grid element = new Grid();
InteractionHelper.SetBehaviorInDesignMode(element, InteractionBehaviorInDesignMode.AsWellAsNotInDesignMode);
CheckAttach(new TestBehaviorRegular(), element);
}
[Test]
public void TestBehaviorAllowAttachInDesignMode_AttachInDesignTime_InteractionHelperOnAssociatedObject() {
ViewModelDesignHelper.IsInDesignModeOverride = true;
Grid element = new Grid();
InteractionHelper.SetBehaviorInDesignMode(element, InteractionBehaviorInDesignMode.AsWellAsNotInDesignMode);
CheckAttach(new TestBehaviorAllowAttachInDesignMode(), element);
}
[Test]
public void TestBehaviorNotAllowAttachInDesignMode_AttachInDesignTime_InteractionHelperOnAssociatedObject() {
ViewModelDesignHelper.IsInDesignModeOverride = true;
Grid element = new Grid();
InteractionHelper.SetBehaviorInDesignMode(element, InteractionBehaviorInDesignMode.AsWellAsNotInDesignMode);
CheckAttach(new TestBehaviorAllowAttachInDesignMode(), element);
}
#endregion
void CheckAttach(Behavior behavior, FrameworkElement container = null) {
FrameworkElement element = container ?? new Grid();
Interaction.GetBehaviors(element).Add(behavior);
Assert.IsTrue(behavior.IsAttached);
Assert.AreSame(element, behavior.AssociatedObject);
}
void CheckNotAttach(Behavior behavior, FrameworkElement container = null) {
FrameworkElement element = container ?? new Grid();
Interaction.GetBehaviors(element).Add(behavior);
Assert.IsFalse(behavior.IsAttached);
Assert.IsNull(behavior.AssociatedObject);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ResourceManager
{
using System.Threading.Tasks;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for FeaturesOperations.
/// </summary>
public static partial class FeaturesOperationsExtensions
{
/// <summary>
/// Gets a list of previewed features for all the providers in the current
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Microsoft.Rest.Azure.IPage<FeatureResult> ListAll(this IFeaturesOperations operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IFeaturesOperations)s).ListAllAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of previewed features for all the providers in the current
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<FeatureResult>> ListAllAsync(this IFeaturesOperations operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a list of previewed features of a resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceProviderNamespace'>
/// The namespace of the resource provider.
/// </param>
public static Microsoft.Rest.Azure.IPage<FeatureResult> List(this IFeaturesOperations operations, string resourceProviderNamespace)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IFeaturesOperations)s).ListAsync(resourceProviderNamespace), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of previewed features of a resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceProviderNamespace'>
/// The namespace of the resource provider.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<FeatureResult>> ListAsync(this IFeaturesOperations operations, string resourceProviderNamespace, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceProviderNamespace, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get all features under the subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Namespace of the resource provider.
/// </param>
/// <param name='featureName'>
/// Previewed feature name in the resource provider.
/// </param>
public static FeatureResult Get(this IFeaturesOperations operations, string resourceProviderNamespace, string featureName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IFeaturesOperations)s).GetAsync(resourceProviderNamespace, featureName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get all features under the subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Namespace of the resource provider.
/// </param>
/// <param name='featureName'>
/// Previewed feature name in the resource provider.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<FeatureResult> GetAsync(this IFeaturesOperations operations, string resourceProviderNamespace, string featureName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceProviderNamespace, featureName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Registers for a previewed feature of a resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Namespace of the resource provider.
/// </param>
/// <param name='featureName'>
/// Previewed feature name in the resource provider.
/// </param>
public static FeatureResult Register(this IFeaturesOperations operations, string resourceProviderNamespace, string featureName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IFeaturesOperations)s).RegisterAsync(resourceProviderNamespace, featureName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Registers for a previewed feature of a resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Namespace of the resource provider.
/// </param>
/// <param name='featureName'>
/// Previewed feature name in the resource provider.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<FeatureResult> RegisterAsync(this IFeaturesOperations operations, string resourceProviderNamespace, string featureName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.RegisterWithHttpMessagesAsync(resourceProviderNamespace, featureName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a list of previewed features for all the providers in the current
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<FeatureResult> ListAllNext(this IFeaturesOperations operations, string nextPageLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IFeaturesOperations)s).ListAllNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of previewed features for all the providers in the current
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<FeatureResult>> ListAllNextAsync(this IFeaturesOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a list of previewed features of a resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<FeatureResult> ListNext(this IFeaturesOperations operations, string nextPageLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IFeaturesOperations)s).ListNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of previewed features of a resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<FeatureResult>> ListNextAsync(this IFeaturesOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// Summary: Test suite for the below scenario:
// An array of tasks that can have different workloads
// WaitAny and WaitAll
// - with/without timeout is performed on them
// - the allowed delta for cases with timeout:10 ms
// Scheduler used : current ( ThreadPool)
//
// Observations:
// 1. The input data for tasks does not contain any Exceptional or Cancelled tasks.
// 2. WaitAll on array with cancelled tasks can be found at: Functional\TPL\YetiTests\TaskWithYeti\TaskWithYeti.cs
// 3. WaitAny/WaitAll with token tests can be found at:Functional\TPL\YetiTests\TaskCancellation\TaskCancellation.cs
using Xunit;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace System.Threading.Tasks.Tests.WaitAllAny
{
#region Helper Classes / Methods
/// <summary>
/// the waiting type
/// </summary>
public enum API
{
WaitAll,
WaitAny,
}
/// <summary>
/// Waiting type
/// </summary>
public enum WaitBy
{
None,
TimeSpan,
Millisecond,
}
/// <summary>
/// Every task has an workload associated
/// These are the workload types used in the task tree
/// The workload is not common for the whole tree - Every node can have its own workload
/// </summary>
public enum WorkloadType
{
Exceptional = -2,
Cancelled = -1,
VeryLight = 1000, // the number is the N input to the ZetaSequence workload
Light = 10000,
Medium = 1000000,
Heavy = 100000000,
VeryHeavy = 1000000000,
}
public class TestParameters_WaitAllAny
{
public readonly TaskInfo[] AllTaskInfos;
public readonly API Api;
public readonly WaitBy WaitBy;
public readonly int WaitTime;
public TestParameters_WaitAllAny(API api, int waitTime, WaitBy waitBy, TaskInfo[] allTasks)
{
Api = api;
WaitBy = waitBy;
WaitTime = waitTime;
AllTaskInfos = allTasks;
}
}
/// <summary>
/// The Tree node Data type
///
/// While the tree is not restricted to this data type
/// the implemented tests are using the TaskInfo_WaitAllAny data type for their scenarios
/// </summary>
public class TaskInfo
{
private static double s_UNINITIALED_RESULT = -1;
public TaskInfo(WorkloadType workType)
{
CancellationTokenSource = new CancellationTokenSource();
CancellationToken = CancellationTokenSource.Token;
Result = s_UNINITIALED_RESULT;
WorkType = workType;
}
#region Properties
/// <summary>
/// The task associated with the current node
/// </summary>
public Task Task { get; set; }
/// <summary>
/// The token associated with the current node's task
/// </summary>
public CancellationToken CancellationToken { get; set; }
/// <summary>
/// Every node has a cancellation source - its token participate in the task creation
/// </summary>
public CancellationTokenSource CancellationTokenSource { get; set; }
/// <summary>
/// While a tasks is correct execute a result is produced
/// this is the result
/// </summary>
public double Result { get; private set; }
public WorkloadType WorkType { get; private set; }
#endregion
#region Helper Methods
/// <summary>
/// The Task workload execution
/// </summary>
public void RunWorkload()
{
//Thread = Thread.CurrentThread;
if (WorkType == WorkloadType.Exceptional)
{
ThrowException();
}
else if (WorkType == WorkloadType.Cancelled)
{
CancelSelf(CancellationTokenSource, CancellationToken);
}
else
{
// run the workload
if (Result == s_UNINITIALED_RESULT)
{
Result = ZetaSequence((int)WorkType, CancellationToken);
}
else // task re-entry, mark it failed
{
Result = s_UNINITIALED_RESULT;
}
}
}
public static double ZetaSequence(int n, CancellationToken token)
{
double result = 0;
for (int i = 1; i < n; i++)
{
if (token.IsCancellationRequested)
return s_UNINITIALED_RESULT;
result += 1.0 / ((double)i * (double)i);
}
return result;
}
/// <summary>
/// Cancel self workload. The CancellationToken has been wired such that the source passed to this method
/// is a source that can actually causes the Task CancellationToken to be canceled. The source could be the
/// Token's original source, or one of the sources in case of Linked Tokens
/// </summary>
/// <param name="cts"></param>
public static void CancelSelf(CancellationTokenSource cts, CancellationToken ct)
{
cts.Cancel();
throw new OperationCanceledException(ct);
}
public static void ThrowException()
{
throw new TPLTestException();
}
#endregion
}
public sealed class TaskWaitAllAnyTest
{
#region Private Fields
private const int MAX_DELAY_TIMEOUT = 10;
private readonly API _api; // the API_WaitAllAny to be tested
private readonly WaitBy _waitBy; // the format of Wait
private readonly int _waitTimeout; // the timeout in ms to be waited
private readonly TaskInfo[] _taskInfos; // task info for each task
private readonly Task[] _tasks; // _tasks to be waited
private bool _taskWaitAllReturn; // result to record the WaitAll(timeout) return value
private int _taskWaitAnyReturn; // result to record the WaitAny(timeout) return value
private AggregateException _caughtException; // exception thrown during wait
#endregion
public TaskWaitAllAnyTest(TestParameters_WaitAllAny parameters)
{
_api = parameters.Api;
_waitBy = parameters.WaitBy;
_waitTimeout = parameters.WaitTime;
_taskInfos = parameters.AllTaskInfos;
_tasks = new Task[parameters.AllTaskInfos.Length];
}
/// <summary>
/// The method that will run the scenario
/// </summary>
/// <returns></returns>
internal void RealRun()
{
//create the tasks
CreateTask();
Stopwatch sw = Stopwatch.StartNew();
//start the wait in a try/catch
try
{
switch (_api)
{
case API.WaitAll:
switch (_waitBy)
{
case WaitBy.None:
Task.WaitAll(_tasks);
_taskWaitAllReturn = true;
break;
case WaitBy.Millisecond:
_taskWaitAllReturn = Task.WaitAll(_tasks, _waitTimeout);
break;
case WaitBy.TimeSpan:
_taskWaitAllReturn = Task.WaitAll(_tasks, new TimeSpan(0, 0, 0, 0, _waitTimeout));
break;
}
break;
case API.WaitAny:
switch (_waitBy)
{
case WaitBy.None:
//save the returned task index
_taskWaitAnyReturn = Task.WaitAny(_tasks);
break;
case WaitBy.Millisecond:
//save the returned task index
_taskWaitAnyReturn = Task.WaitAny(_tasks, _waitTimeout);
break;
case WaitBy.TimeSpan:
//save the returned task index
_taskWaitAnyReturn = Task.WaitAny(_tasks, new TimeSpan(0, 0, 0, 0, _waitTimeout));
break;
}
break;
}
}
catch (AggregateException exp)
{
_caughtException = exp;
}
finally
{
sw.Stop();
}
long maxTimeout = (long)(_waitTimeout + MAX_DELAY_TIMEOUT);
if (_waitTimeout != -1 && sw.ElapsedMilliseconds > maxTimeout)
{
Debug.WriteLine("ElapsedMilliseconds way more than requested Timeout.");
Debug.WriteLine("Max Timeout: {0}ms + {1}ms, Actual Time: {2}ms",
_waitTimeout, MAX_DELAY_TIMEOUT, sw.ElapsedMilliseconds);
}
Verify();
CleanUpTasks();
}
private void CleanUpTasks()
{
foreach (TaskInfo taskInfo in _taskInfos)
{
if (taskInfo.Task.Status == TaskStatus.Running)
{
taskInfo.CancellationTokenSource.Cancel();
taskInfo.Task.Wait();
}
}
}
/// <summary>
/// create an array of tasks
/// </summary>
private void CreateTask()
{
for (int i = 0; i < _taskInfos.Length; i++)
{
int iCopy = i;
_taskInfos[i].Task = Task.Factory.StartNew(
delegate (object o)
{
_taskInfos[iCopy].RunWorkload();
}, string.Concat("Task_", iCopy), _taskInfos[iCopy].CancellationTokenSource.Token, TaskCreationOptions.AttachedToParent, TaskScheduler.Current);
_tasks[i] = _taskInfos[i].Task;
}
}
/// <summary>
/// the scenario verification
///
/// - all the tasks should be coplted in case of waitAll with -1 timeout
/// - the returned index form WaitAny should correspond to a completed task
/// - in case of Cancelled and Exception tests the right exceptions should be got for WaitAll
/// </summary>
/// <returns></returns>
private void Verify()
{
// verification for WaitAll
bool allShouldFinish = (_api == API.WaitAll && _taskWaitAllReturn);
// verification for WaitAny
Task thisShouldFinish = (_api == API.WaitAny && _taskWaitAnyReturn != -1) ? _taskInfos[_taskWaitAnyReturn].Task : null;
Dictionary<int, Task> faultyTasks = new Dictionary<int, Task>();
bool expCaught = false;
for (int i = 0; i < _taskInfos.Length; i++)
{
TaskInfo ti = _taskInfos[i];
if (allShouldFinish && !ti.Task.IsCompleted)
Assert.True(false, string.Format("WaitAll contract is broken -- Task at Index = {0} does not finish", i));
if (thisShouldFinish == ti.Task && !ti.Task.IsCompleted)
Assert.True(false, string.Format("WaitAny contract is broken -- Task at Index = {0} does not finish", i));
WorkloadType workType = ti.WorkType;
if (workType == WorkloadType.Exceptional)
{
// verify whether exception has(not) been propogated
expCaught = VerifyException((ex) =>
{
TPLTestException expectedExp = ex as TPLTestException;
return expectedExp != null && expectedExp.FromTaskId == ti.Task.Id;
});
if (_api == API.WaitAll)
{
if (!expCaught)
Assert.True(false, string.Format("excepted TPLTestException in Task at Index = {0} NOT caught", i));
}
else // must be API_WaitAllAny.WaitAny
{
//waitAny will not fail if a number of tasks were exceptional
if (expCaught)
Assert.True(false, string.Format("Unexcepted TPLTestException in Task at Index = {0} caught", i));
//need to check it eventually to prevent it from crashing the finalizer
faultyTasks.Add(i, ti.Task);
}
}
else if (workType == WorkloadType.Cancelled)
{
expCaught = VerifyException((ex) =>
{
TaskCanceledException expectedExp = ex as TaskCanceledException;
return expectedExp != null && expectedExp.Task == ti.Task;
});
if (_api == API.WaitAll)
Assert.True(expCaught, "excepted TaskCanceledException in Task at Index = " + i + " NOT caught");
else // must be API_WaitAllAny.WaitAny
{
if (expCaught) //waitAny will not fail if a number of tasks were cancelled
Assert.False(expCaught, "Unexcepted TaskCanceledException in Task at Index = " + i + " caught");
}
}
else if (ti.Task.IsCompleted && !CheckResult(ti.Result))
Assert.True(false, string.Format("Failed result verification in Task at Index = {0}", i));
else if (ti.Task.Status == TaskStatus.WaitingToRun && ti.Result != -1)
Assert.True(false, string.Format("Result must remain uninitialized for unstarted task"));
}
if (!expCaught && _caughtException != null)
Assert.True(false, string.Format("Caught unexpected exception of {0}", _caughtException));
// second pass on the faulty tasks
if (faultyTasks.Count > 0)
{
List<WaitHandle> faultyTaskHandles = new List<WaitHandle>();
foreach (var task in faultyTasks.Values)
faultyTaskHandles.Add(((IAsyncResult)task).AsyncWaitHandle);
WaitHandle.WaitAll(faultyTaskHandles.ToArray());
foreach (var tasks in faultyTasks)
{
if (!(tasks.Value.Exception.InnerException is TPLTestException))
Assert.True(false, string.Format("Unexcepted Exception in Task at Index = {0} caught", tasks.Key));
}
}
}
/// <summary>
/// verify the exception using a custom defined predicate
/// It walks the whole inner exceptions list saved in _caughtException
/// </summary>
private bool VerifyException(Predicate<Exception> isExpectedExp)
{
if (_caughtException == null)
{
return false;
}
foreach (Exception ex in _caughtException.InnerExceptions)
{
if (isExpectedExp(ex)) return true;
}
return false;
}
/// <summary>
/// Verify the result for a correct running task
/// </summary>
private bool CheckResult(double result)
{
//Function point comparison cant be done by rounding off to nearest decimal points since
//1.64 could be represented as 1.63999999 or as 1.6499999999. To perform floating point comparisons,
//a range has to be defined and check to ensure that the result obtained is within the specified range
double minLimit = 1.63;
double maxLimit = 1.65;
return result > minLimit && result < maxLimit;
}
}
#endregion
public sealed class TaskWaitAllAny
{
[Fact]
[OuterLoop]
public static void TaskWaitAllAny0()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Heavy);
TaskInfo[] allTasks = new[] { node1, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, -1, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
[OuterLoop]
public static void TaskWaitAllAny1()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, -1, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny2()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, -1, WaitBy.None, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny3()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, -1, WaitBy.None, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny4()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, -1, WaitBy.None, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
[OuterLoop]
public static void TaskWaitAllAny5()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo node3 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node4 = new TaskInfo(WorkloadType.Medium);
TaskInfo node5 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node6 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node7 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, node3, node4, node5, node6, node7, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, -1, WaitBy.None, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny6()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Light);
TaskInfo[] allTasks = new[] { node1, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, -1, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
[OuterLoop]
public static void TaskWaitAllAny7()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo node3 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node4 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node5 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node6 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node7 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, node3, node4, node5, node6, node7, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, -1, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny8()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 0, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny9()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node2 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 0, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny10()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 0, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny11()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo node3 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node4 = new TaskInfo(WorkloadType.Medium);
TaskInfo node5 = new TaskInfo(WorkloadType.Light);
TaskInfo node6 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node7 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, node3, node4, node5, node6, node7, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 0, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny12()
{
TaskInfo node1 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 197, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny13()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node3 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node4 = new TaskInfo(WorkloadType.Medium);
TaskInfo node5 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node6 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node7 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, node3, node4, node5, node6, node7, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 197, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny14()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 197, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny15()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Heavy);
TaskInfo[] allTasks = new[] { node1, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 197, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny16()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node2 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 197, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny17()
{
TaskInfo node1 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo[] allTasks = new[] { node1, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 1, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny18()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 1, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny19()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 1, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny20()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo node3 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node4 = new TaskInfo(WorkloadType.Medium);
TaskInfo node5 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node6 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node7 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, node3, node4, node5, node6, node7, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 1, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny21()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 47, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny22()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 47, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny23()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Heavy);
TaskInfo[] allTasks = new[] { node1, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 47, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny24()
{
TaskInfo node1 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node2 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 47, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny25()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo node3 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node4 = new TaskInfo(WorkloadType.Medium);
TaskInfo node5 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node6 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node7 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, node3, node4, node5, node6, node7, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 47, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny26()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 7, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny27()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Light);
TaskInfo[] allTasks = new[] { node1, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 7, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny28()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.Heavy);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 7, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny29()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo node3 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node4 = new TaskInfo(WorkloadType.Medium);
TaskInfo node5 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node6 = new TaskInfo(WorkloadType.Light);
TaskInfo node7 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, node3, node4, node5, node6, node7, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAll, 7, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny30()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, -1, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
[OuterLoop]
public static void TaskWaitAllAny31()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo node3 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node4 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node5 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node6 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node7 = new TaskInfo(WorkloadType.Medium);
TaskInfo node8 = new TaskInfo(WorkloadType.Medium);
TaskInfo node9 = new TaskInfo(WorkloadType.Light);
TaskInfo node10 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node11 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node12 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node13 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node14 = new TaskInfo(WorkloadType.Medium);
TaskInfo node15 = new TaskInfo(WorkloadType.Medium);
TaskInfo node16 = new TaskInfo(WorkloadType.Light);
TaskInfo node17 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node18 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node19 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node20 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node21 = new TaskInfo(WorkloadType.Medium);
TaskInfo node22 = new TaskInfo(WorkloadType.Medium);
TaskInfo node23 = new TaskInfo(WorkloadType.Light);
TaskInfo node24 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node25 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node26 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node27 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node28 = new TaskInfo(WorkloadType.Medium);
TaskInfo node29 = new TaskInfo(WorkloadType.Medium);
TaskInfo node30 = new TaskInfo(WorkloadType.Light);
TaskInfo node31 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node32 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node33 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node34 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node35 = new TaskInfo(WorkloadType.Medium);
TaskInfo node36 = new TaskInfo(WorkloadType.Medium);
TaskInfo node37 = new TaskInfo(WorkloadType.Light);
TaskInfo node38 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node39 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node40 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node41 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node42 = new TaskInfo(WorkloadType.Medium);
TaskInfo node43 = new TaskInfo(WorkloadType.Medium);
TaskInfo node44 = new TaskInfo(WorkloadType.Light);
TaskInfo node45 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node46 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node47 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node48 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node49 = new TaskInfo(WorkloadType.Medium);
TaskInfo node50 = new TaskInfo(WorkloadType.Medium);
TaskInfo node51 = new TaskInfo(WorkloadType.Light);
TaskInfo node52 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node53 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node54 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node55 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node56 = new TaskInfo(WorkloadType.Medium);
TaskInfo node57 = new TaskInfo(WorkloadType.Medium);
TaskInfo node58 = new TaskInfo(WorkloadType.Light);
TaskInfo node59 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node60 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node61 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node62 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node63 = new TaskInfo(WorkloadType.Medium);
TaskInfo node64 = new TaskInfo(WorkloadType.Medium);
TaskInfo node65 = new TaskInfo(WorkloadType.Light);
TaskInfo node66 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo[] allTasks = new[] { node1, node2, node3, node4, node5, node6, node7, node8, node9, node10, node11, node12, node13, node14, node15, node16, node17, node18, node19, node20, node21, node22, node23, node24, node25, node26, node27, node28, node29, node30, node31, node32, node33, node34, node35, node36, node37, node38, node39, node40, node41, node42, node43, node44, node45, node46, node47, node48, node49, node50, node51, node52, node53, node54, node55, node56, node57, node58, node59, node60, node61, node62, node63, node64, node65, node66, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, -1, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny32()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, -1, WaitBy.None, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
[OuterLoop]
public static void TaskWaitAllAny33()
{
TaskInfo node1 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo[] allTasks = new[] { node1, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, -1, WaitBy.None, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
[OuterLoop]
public static void TaskWaitAllAny34()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, -1, WaitBy.None, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny35()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, -1, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny36()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo node3 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node4 = new TaskInfo(WorkloadType.Medium);
TaskInfo node5 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node6 = new TaskInfo(WorkloadType.Light);
TaskInfo node7 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, node3, node4, node5, node6, node7, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, -1, WaitBy.None, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
[OuterLoop]
public static void TaskWaitAllAny37()
{
TaskInfo node1 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node2 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, -1, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny38()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 0, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny39()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node3 = new TaskInfo(WorkloadType.Light);
TaskInfo node4 = new TaskInfo(WorkloadType.Medium);
TaskInfo node5 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node6 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node7 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, node3, node4, node5, node6, node7, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 0, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny40()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 0, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny41()
{
TaskInfo node1 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node2 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 0, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny42()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 197, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny43()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 197, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny44()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node2 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 197, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
[OuterLoop]
public static void TaskWaitAllAny45()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo node3 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node4 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node5 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node6 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node7 = new TaskInfo(WorkloadType.Medium);
TaskInfo node8 = new TaskInfo(WorkloadType.Medium);
TaskInfo node9 = new TaskInfo(WorkloadType.Light);
TaskInfo node10 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node11 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node12 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node13 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node14 = new TaskInfo(WorkloadType.Medium);
TaskInfo node15 = new TaskInfo(WorkloadType.Medium);
TaskInfo node16 = new TaskInfo(WorkloadType.Light);
TaskInfo node17 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node18 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node19 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node20 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node21 = new TaskInfo(WorkloadType.Medium);
TaskInfo node22 = new TaskInfo(WorkloadType.Medium);
TaskInfo node23 = new TaskInfo(WorkloadType.Light);
TaskInfo node24 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node25 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node26 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node27 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node28 = new TaskInfo(WorkloadType.Medium);
TaskInfo node29 = new TaskInfo(WorkloadType.Medium);
TaskInfo node30 = new TaskInfo(WorkloadType.Light);
TaskInfo node31 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node32 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node33 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node34 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node35 = new TaskInfo(WorkloadType.Medium);
TaskInfo node36 = new TaskInfo(WorkloadType.Medium);
TaskInfo node37 = new TaskInfo(WorkloadType.Light);
TaskInfo node38 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node39 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node40 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node41 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node42 = new TaskInfo(WorkloadType.Medium);
TaskInfo node43 = new TaskInfo(WorkloadType.Medium);
TaskInfo node44 = new TaskInfo(WorkloadType.Light);
TaskInfo node45 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node46 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node47 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node48 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node49 = new TaskInfo(WorkloadType.Medium);
TaskInfo node50 = new TaskInfo(WorkloadType.Medium);
TaskInfo node51 = new TaskInfo(WorkloadType.Light);
TaskInfo node52 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node53 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node54 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node55 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node56 = new TaskInfo(WorkloadType.Medium);
TaskInfo node57 = new TaskInfo(WorkloadType.Medium);
TaskInfo node58 = new TaskInfo(WorkloadType.Light);
TaskInfo node59 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node60 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node61 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node62 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node63 = new TaskInfo(WorkloadType.Medium);
TaskInfo node64 = new TaskInfo(WorkloadType.Medium);
TaskInfo node65 = new TaskInfo(WorkloadType.Light);
TaskInfo node66 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node67 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node68 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node69 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo[] allTasks = new[] { node1, node2, node3, node4, node5, node6, node7, node8, node9, node10, node11, node12, node13, node14, node15, node16, node17, node18, node19, node20, node21, node22, node23, node24, node25, node26, node27, node28, node29, node30, node31, node32, node33, node34, node35, node36, node37, node38, node39, node40, node41, node42, node43, node44, node45, node46, node47, node48, node49, node50, node51, node52, node53, node54, node55, node56, node57, node58, node59, node60, node61, node62, node63, node64, node65, node66, node67, node68, node69, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 197, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny46()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 1, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny47()
{
TaskInfo node1 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node2 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 1, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny48()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo node3 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node4 = new TaskInfo(WorkloadType.Medium);
TaskInfo node5 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo node6 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node7 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, node3, node4, node5, node6, node7, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 1, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny49()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Heavy);
TaskInfo[] allTasks = new[] { node1, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 1, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny50()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Light);
TaskInfo[] allTasks = new[] { node1, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 47, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny51()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Light);
TaskInfo node2 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 47, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny52()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo node3 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node4 = new TaskInfo(WorkloadType.Medium);
TaskInfo node5 = new TaskInfo(WorkloadType.Medium);
TaskInfo node6 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node7 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, node3, node4, node5, node6, node7, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 47, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny53()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 47, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny54()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node2 = new TaskInfo(WorkloadType.VeryHeavy);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 47, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny55()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Light);
TaskInfo[] allTasks = new[] { node1, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 7, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny56()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo[] allTasks = new[] { node1, node2, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 7, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny57()
{
TaskInfo node1 = new TaskInfo(WorkloadType.Medium);
TaskInfo node2 = new TaskInfo(WorkloadType.Light);
TaskInfo node3 = new TaskInfo(WorkloadType.Heavy);
TaskInfo node4 = new TaskInfo(WorkloadType.Medium);
TaskInfo node5 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node6 = new TaskInfo(WorkloadType.VeryLight);
TaskInfo node7 = new TaskInfo(WorkloadType.Medium);
TaskInfo[] allTasks = new[] { node1, node2, node3, node4, node5, node6, node7, };
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 7, WaitBy.Millisecond, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskWaitAllAny58()
{
TaskInfo[] allTasks = new TaskInfo[0];
TestParameters_WaitAllAny parameters = new TestParameters_WaitAllAny(API.WaitAny, 7, WaitBy.TimeSpan, allTasks);
TaskWaitAllAnyTest test = new TaskWaitAllAnyTest(parameters);
test.RealRun();
}
}
}
| |
/*
* 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.
*/
// ReSharper disable UnusedVariable
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable UnusedAutoPropertyAccessor.Local
namespace Apache.Ignite.Core.Tests
{
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Resource;
using Apache.Ignite.Core.Tests.Process;
using NUnit.Framework;
/// <summary>
/// Tests for Apache.Ignite.exe.
/// </summary>
[Category(TestUtils.CategoryIntensive)]
public class ExecutableTest
{
/** Spring configuration path. */
private const string SpringCfgPath = "config\\compute\\compute-standalone.xml";
/** Min memory Java task. */
private const string MinMemTask = "org.apache.ignite.platform.PlatformMinMemoryTask";
/** Max memory Java task. */
private const string MaxMemTask = "org.apache.ignite.platform.PlatformMaxMemoryTask";
/** Grid. */
private IIgnite _grid;
/// <summary>
/// Set-up routine.
/// </summary>
[SetUp]
public void SetUp()
{
TestUtils.KillProcesses();
_grid = Ignition.Start(new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
BinaryConfiguration = new BinaryConfiguration
{
TypeConfigurations = new List<BinaryTypeConfiguration>
{
new BinaryTypeConfiguration(typeof(RemoteConfiguration)),
new BinaryTypeConfiguration(typeof(RemoteConfigurationClosure))
}
},
SpringConfigUrl = SpringCfgPath
});
Assert.IsTrue(_grid.WaitTopology(1));
IgniteProcess.SaveConfigurationBackup();
}
/// <summary>
/// Tear-down routine.
/// </summary>
[TearDown]
public void TearDown()
{
Ignition.StopAll(true);
TestUtils.KillProcesses();
IgniteProcess.RestoreConfigurationBackup();
}
/// <summary>
/// Test data pass through configuration file.
/// </summary>
[Test]
public void TestConfig()
{
IgniteProcess.ReplaceConfiguration("config\\Apache.Ignite.exe.config.test");
GenerateDll("test-1.dll");
GenerateDll("test-2.dll");
var proc = new IgniteProcess(
"-jvmClasspath=" + TestUtils.CreateTestClasspath()
);
Assert.IsTrue(_grid.WaitTopology(2));
var cfg = RemoteConfig();
Assert.AreEqual(SpringCfgPath, cfg.SpringConfigUrl);
Assert.IsTrue(cfg.JvmOptions.Contains("-DOPT1") && cfg.JvmOptions.Contains("-DOPT2"));
Assert.IsTrue(cfg.Assemblies.Contains("test-1.dll") && cfg.Assemblies.Contains("test-2.dll"));
Assert.AreEqual(601, cfg.JvmInitialMemoryMb);
Assert.AreEqual(702, cfg.JvmMaxMemoryMb);
}
/// <summary>
/// Test assemblies passing through command-line.
/// </summary>
[Test]
public void TestAssemblyCmd()
{
GenerateDll("test-1.dll");
GenerateDll("test-2.dll");
var proc = new IgniteProcess(
"-jvmClasspath=" + TestUtils.CreateTestClasspath(),
"-springConfigUrl=" + SpringCfgPath,
"-assembly=test-1.dll",
"-assembly=test-2.dll"
);
Assert.IsTrue(_grid.WaitTopology(2));
var cfg = RemoteConfig();
Assert.IsTrue(cfg.Assemblies.Contains("test-1.dll") && cfg.Assemblies.Contains("test-2.dll"));
}
/// <summary>
/// Test JVM options passing through command-line.
/// </summary>
[Test]
public void TestJvmOptsCmd()
{
var proc = new IgniteProcess(
"-jvmClasspath=" + TestUtils.CreateTestClasspath(),
"-springConfigUrl=" + SpringCfgPath,
"-J-DOPT1",
"-J-DOPT2"
);
Assert.IsTrue(_grid.WaitTopology(2));
var cfg = RemoteConfig();
Assert.IsTrue(cfg.JvmOptions.Contains("-DOPT1") && cfg.JvmOptions.Contains("-DOPT2"));
}
/// <summary>
/// Test JVM memory options passing through command-line: raw java options.
/// </summary>
[Test]
public void TestJvmMemoryOptsCmdRaw()
{
var proc = new IgniteProcess(
"-jvmClasspath=" + TestUtils.CreateTestClasspath(),
"-springConfigUrl=" + SpringCfgPath,
"-J-Xms506m",
"-J-Xmx607m"
);
Assert.IsTrue(_grid.WaitTopology(2));
var minMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MinMemTask, null);
Assert.AreEqual((long) 506*1024*1024, minMem);
var maxMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MaxMemTask, null);
AssertJvmMaxMemory((long) 607*1024*1024, maxMem);
}
/// <summary>
/// Test JVM memory options passing through command-line: custom options.
/// </summary>
[Test]
public void TestJvmMemoryOptsCmdCustom()
{
var proc = new IgniteProcess(
"-jvmClasspath=" + TestUtils.CreateTestClasspath(),
"-springConfigUrl=" + SpringCfgPath,
"-JvmInitialMemoryMB=615",
"-JvmMaxMemoryMB=863"
);
Assert.IsTrue(_grid.WaitTopology(2));
var minMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MinMemTask, null);
Assert.AreEqual((long) 615*1024*1024, minMem);
var maxMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MaxMemTask, null);
AssertJvmMaxMemory((long) 863*1024*1024, maxMem);
}
/// <summary>
/// Test JVM memory options passing from application configuration.
/// </summary>
[Test]
public void TestJvmMemoryOptsAppConfig(
[Values("config\\Apache.Ignite.exe.config.test", "config\\Apache.Ignite.exe.config.test2")] string config)
{
IgniteProcess.ReplaceConfiguration(config);
GenerateDll("test-1.dll");
GenerateDll("test-2.dll");
var proc = new IgniteProcess("-jvmClasspath=" + TestUtils.CreateTestClasspath());
Assert.IsTrue(_grid.WaitTopology(2));
var minMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MinMemTask, null);
Assert.AreEqual((long) 601*1024*1024, minMem);
var maxMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MaxMemTask, null);
AssertJvmMaxMemory((long) 702*1024*1024, maxMem);
proc.Kill();
Assert.IsTrue(_grid.WaitTopology(1));
// Command line options overwrite config file options
// ReSharper disable once RedundantAssignment
proc = new IgniteProcess("-jvmClasspath=" + TestUtils.CreateTestClasspath(),
"-J-Xms605m", "-J-Xmx706m");
Assert.IsTrue(_grid.WaitTopology(2));
minMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MinMemTask, null);
Assert.AreEqual((long) 605*1024*1024, minMem);
maxMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MaxMemTask, null);
AssertJvmMaxMemory((long) 706*1024*1024, maxMem);
}
/// <summary>
/// Test JVM memory options passing through command-line: custom options + raw options.
/// </summary>
[Test]
public void TestJvmMemoryOptsCmdCombined()
{
var proc = new IgniteProcess(
"-jvmClasspath=" + TestUtils.CreateTestClasspath(),
"-springConfigUrl=" + SpringCfgPath,
"-J-Xms555m",
"-J-Xmx666m",
"-JvmInitialMemoryMB=128",
"-JvmMaxMemoryMB=256"
);
Assert.IsTrue(_grid.WaitTopology(2));
// Raw JVM options (Xms/Xmx) should override custom options
var minMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MinMemTask, null);
Assert.AreEqual((long) 555*1024*1024, minMem);
var maxMem = _grid.GetCluster().ForRemotes().GetCompute().ExecuteJavaTask<long>(MaxMemTask, null);
AssertJvmMaxMemory((long) 666*1024*1024, maxMem);
}
/// <summary>
/// Tests the .NET XML configuration specified in app.config.
/// </summary>
[Test]
public void TestXmlConfigurationAppConfig()
{
IgniteProcess.ReplaceConfiguration("config\\Apache.Ignite.exe.config.test3");
var proc = new IgniteProcess("-jvmClasspath=" + TestUtils.CreateTestClasspath());
Assert.IsTrue(_grid.WaitTopology(2));
var remoteCfg = RemoteConfig();
Assert.IsTrue(remoteCfg.JvmOptions.Contains("-DOPT25"));
proc.Kill();
Assert.IsTrue(_grid.WaitTopology(1));
}
/// <summary>
/// Tests the .NET XML configuration specified in command line.
/// </summary>
[Test]
public void TestXmlConfigurationCmd()
{
var proc = new IgniteProcess("-jvmClasspath=" + TestUtils.CreateTestClasspath(),
"-configFileName=config\\ignite-dotnet-cfg.xml");
Assert.IsTrue(_grid.WaitTopology(2));
var remoteCfg = RemoteConfig();
Assert.IsTrue(remoteCfg.JvmOptions.Contains("-DOPT25"));
proc.Kill();
Assert.IsTrue(_grid.WaitTopology(1));
}
/// <summary>
/// Tests invalid command arguments.
/// </summary>
[Test]
public void TestInvalidCmdArgs()
{
Action<string, string> checkError = (args, err) =>
{
var reader = new ListDataReader();
var proc = new IgniteProcess(reader, args);
int exitCode;
Assert.IsTrue(proc.Join(30000, out exitCode));
Assert.AreEqual(-1, exitCode);
lock (reader.List)
{
Assert.AreEqual(err, reader.List.FirstOrDefault(x => !string.IsNullOrWhiteSpace(x)));
}
};
checkError("blabla", "ERROR: Apache.Ignite.Core.Common.IgniteException: Missing argument value: " +
"'blabla'. See 'Apache.Ignite.exe /help'");
checkError("blabla=foo", "ERROR: Apache.Ignite.Core.Common.IgniteException: " +
"Unknown argument: 'blabla'. See 'Apache.Ignite.exe /help'");
checkError("assembly=", "ERROR: Apache.Ignite.Core.Common.IgniteException: Missing argument value: " +
"'assembly'. See 'Apache.Ignite.exe /help'");
checkError("assembly=x.dll", "ERROR: Apache.Ignite.Core.Common.IgniteException: Failed to start " +
"Ignite.NET, check inner exception for details ---> Apache.Ignite.Core." +
"Common.IgniteException: Failed to load assembly: x.dll");
checkError("configFileName=wrong.config", "ERROR: System.Configuration.ConfigurationErrorsException: " +
"Specified config file does not exist: wrong.config");
checkError("configSectionName=wrongSection", "ERROR: System.Configuration.ConfigurationErrorsException: " +
"Could not find IgniteConfigurationSection " +
"in current application configuration");
checkError("JvmInitialMemoryMB=A_LOT", "ERROR: System.InvalidOperationException: Failed to configure " +
"Ignite: property 'JvmInitialMemoryMB' has value 'A_LOT', " +
"which is not an integer.");
checkError("JvmMaxMemoryMB=ALL_OF_IT", "ERROR: System.InvalidOperationException: Failed to configure " +
"Ignite: property 'JvmMaxMemoryMB' has value 'ALL_OF_IT', " +
"which is not an integer.");
}
/// <summary>
/// Get remote node configuration.
/// </summary>
/// <returns>Configuration.</returns>
private RemoteConfiguration RemoteConfig()
{
return _grid.GetCluster().ForRemotes().GetCompute().Call(new RemoteConfigurationClosure());
}
/// <summary>
///
/// </summary>
/// <param name="outputPath"></param>
private static void GenerateDll(string outputPath)
{
var parameters = new CompilerParameters
{
GenerateExecutable = false,
OutputAssembly = outputPath
};
var src = "namespace Apache.Ignite.Client.Test { public class Foo {}}";
var results = CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromSource(parameters, src);
Assert.False(results.Errors.HasErrors);
}
/// <summary>
/// Asserts that JVM maximum memory corresponds to Xmx parameter value.
/// </summary>
private static void AssertJvmMaxMemory(long expected, long actual)
{
// allow 20% tolerance because max memory in Java is not exactly equal to Xmx parameter value
Assert.LessOrEqual(actual, expected);
Assert.Greater(actual, expected/5*4);
}
/// <summary>
/// Closure which extracts configuration and passes it back.
/// </summary>
private class RemoteConfigurationClosure : IComputeFunc<RemoteConfiguration>
{
#pragma warning disable 0649
/** Grid. */
[InstanceResource] private IIgnite _grid;
#pragma warning restore 0649
/** <inheritDoc /> */
public RemoteConfiguration Invoke()
{
var grid0 = (Ignite) _grid;
var cfg = grid0.Configuration;
var res = new RemoteConfiguration
{
IgniteHome = cfg.IgniteHome,
SpringConfigUrl = cfg.SpringConfigUrl,
JvmDll = cfg.JvmDllPath,
JvmClasspath = cfg.JvmClasspath,
JvmOptions = cfg.JvmOptions,
Assemblies = cfg.Assemblies,
JvmInitialMemoryMb = cfg.JvmInitialMemoryMb,
JvmMaxMemoryMb = cfg.JvmMaxMemoryMb
};
Console.WriteLine("RETURNING CFG: " + cfg);
return res;
}
}
/// <summary>
/// Configuration.
/// </summary>
private class RemoteConfiguration
{
/// <summary>
/// GG home.
/// </summary>
public string IgniteHome { get; set; }
/// <summary>
/// Spring config URL.
/// </summary>
public string SpringConfigUrl { get; set; }
/// <summary>
/// JVM DLL.
/// </summary>
public string JvmDll { get; set; }
/// <summary>
/// JVM classpath.
/// </summary>
public string JvmClasspath { get; set; }
/// <summary>
/// JVM options.
/// </summary>
public ICollection<string> JvmOptions { get; set; }
/// <summary>
/// Assemblies.
/// </summary>
public ICollection<string> Assemblies { get; set; }
/// <summary>
/// Minimum JVM memory (Xms).
/// </summary>
public int JvmInitialMemoryMb { get; set; }
/// <summary>
/// Maximum JVM memory (Xms).
/// </summary>
public int JvmMaxMemoryMb { get; set; }
}
private class ListDataReader : IIgniteProcessOutputReader
{
public readonly List<string> List = new List<string>();
public void OnOutput(System.Diagnostics.Process proc, string data, bool err)
{
lock (List)
{
List.Add(data);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Build.Locator;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using R4Mvc.Tools.CodeGen;
using R4Mvc.Tools.Commands.Core;
using R4Mvc.Tools.Extensions;
using R4Mvc.Tools.Locators;
using R4Mvc.Tools.Services;
namespace R4Mvc.Tools.Commands
{
public class GenerateCommand : ICommand
{
public bool IsGlobal => false;
public byte Order => 1;
public string Key => "generate";
public string Summary => "Run the R4Mvc generator against the selected project";
public string Description => Summary + @"
Usage: generate [options] [-p project-path]
project-path:
Path to the project's .cshtml file";
public Type GetCommandType() => typeof(Runner);
public class Runner : ICommandRunner
{
private readonly IControllerRewriterService _controllerRewriter;
private readonly IPageRewriterService _pageRewriter;
private readonly IEnumerable<IViewLocator> _viewLocators;
private readonly IEnumerable<IPageViewLocator> _pageViewLocators;
private readonly R4MvcGeneratorService _generatorService;
private readonly Settings _settings;
private readonly IGeneratedFileTesterService _generatedFileTesterService;
private readonly IFilePersistService _filePersistService;
public Runner(IControllerRewriterService controllerRewriter, IPageRewriterService pageRewriter, IEnumerable<IViewLocator> viewLocators,
IEnumerable<IPageViewLocator> pageViewLocators, R4MvcGeneratorService generatorService, Settings settings,
IGeneratedFileTesterService generatedFileTesterService, IFilePersistService filePersistService)
{
_controllerRewriter = controllerRewriter;
_pageRewriter = pageRewriter;
_viewLocators = viewLocators;
_pageViewLocators = pageViewLocators;
_generatorService = generatorService;
_settings = settings;
_generatedFileTesterService = generatedFileTesterService;
_filePersistService = filePersistService;
}
public async Task Run(string projectPath, IConfiguration configuration, string[] args)
{
var sw = Stopwatch.StartNew();
var vsInstance = InitialiseMSBuild(configuration);
Console.WriteLine($"Using: {vsInstance.Name} - {vsInstance.Version}");
Console.WriteLine("Project: " + projectPath);
Console.WriteLine();
// Load the project and check for compilation errors
Console.WriteLine("Creating Workspace ...");
var workspace = MSBuildWorkspace.Create(new Dictionary<string, string> { ["IsR4MvcBuild"] = "true" });
Console.WriteLine("Loading project ...");
var projectRoot = Path.GetDirectoryName(projectPath);
var project = await workspace.OpenProjectAsync(projectPath);
if (workspace.Diagnostics.Count > 0)
{
var foundErrors = false;
foreach (var diag in workspace.Diagnostics)
{
if (diag.Kind == WorkspaceDiagnosticKind.Failure)
{
Console.Error.WriteLine($" {diag.Kind}: {diag.Message}");
foundErrors = true;
}
else
{
Console.WriteLine($" {diag.Kind}: {diag.Message}");
}
}
if (foundErrors)
{
Console.Error.WriteLine("Found errors during project analysis. Aborting");
return;
}
}
// Prep the project Compilation object, and process the Controller public methods list
Console.WriteLine("Compiling project ...");
var compilation = await project.GetCompilationAsync() as CSharpCompilation;
SyntaxNodeHelpers.PopulateControllerClassMethodNames(compilation);
// Get MVC version
var mvcAssembly = compilation.ReferencedAssemblyNames
.Where(a => a.Name == "Microsoft.AspNetCore.Mvc")
.FirstOrDefault();
if (mvcAssembly != null)
Console.WriteLine($"Detected MVC version: {mvcAssembly.Version}");
else
Console.WriteLine("Error? Failed to find MVC");
Console.WriteLine();
// Analyse the controllers in the project (updating them to be partial), as well as locate all the view files
var controllers = _controllerRewriter.RewriteControllers(compilation);
var allViewFiles = _viewLocators.SelectMany(x => x.Find(projectRoot));
// Assign view files to controllers
foreach (var views in allViewFiles.GroupBy(v => new { v.AreaName, v.ControllerName }))
{
var controller = controllers
.Where(c => string.Equals(c.Name, views.Key.ControllerName, StringComparison.OrdinalIgnoreCase))
.Where(c => string.Equals(c.Area, views.Key.AreaName, StringComparison.OrdinalIgnoreCase))
.FirstOrDefault();
if (controller == null)
controllers.Add(controller = new ControllerDefinition
{
Area = views.Key.AreaName,
Name = views.Key.ControllerName,
});
foreach (var view in views)
controller.Views.Add(view);
}
// Generate mappings for area names, to avoid clashes with controller names
var areaMap = GenerateAreaMap(controllers);
foreach (var controller in controllers.Where(a => !string.IsNullOrEmpty(a.Area)))
controller.AreaKey = areaMap[controller.Area];
// Analyse the razor pages in the project (updating them to be partial), as well as locate all the view files
var hasPagesSupport = mvcAssembly?.Version >= new Version(2, 0, 0, 0);
IList<PageView> pages;
if (hasPagesSupport)
{
var definitions = _pageRewriter.RewritePages(compilation);
pages = _pageViewLocators.SelectMany(x => x.Find(projectRoot)).Where(p => p.IsPage).ToList();
foreach (var page in pages)
{
page.Definition = definitions.FirstOrDefault(d => d.GetFilePath() == (page.FilePath + ".cs"));
}
}
else
{
pages = new List<PageView>();
}
Console.WriteLine();
// Generate the R4Mvc.generated.cs file
_generatorService.Generate(projectRoot, controllers, pages, hasPagesSupport);
// updating the r4mvc.json settings file
_settings._generatedByVersion = Program.GetVersion();
var r4MvcJsonFile = Path.Combine(projectRoot, Constants.R4MvcSettingsFileName);
File.WriteAllText(r4MvcJsonFile, JsonConvert.SerializeObject(_settings, Formatting.Indented));
// Ensuring a user customisable r4mvc.cs code file exists
var r4MvcFile = Path.Combine(projectRoot, Constants.R4MvcFileName);
if (!File.Exists(r4MvcFile))
CreateR4MvcUserFile(r4MvcFile);
// Cleanup old generated files
var generatedFiles = Directory.GetFiles(projectRoot, "*.generated.cs", SearchOption.AllDirectories);
foreach (var file in generatedFiles)
{
if (File.Exists(file.Replace(".generated.cs", ".cs")) ||
string.Equals(Constants.R4MvcGeneratedFileName, Path.GetFileName(file)))
continue;
using (var fileStream = File.OpenRead(file))
{
if (await _generatedFileTesterService.IsGenerated(fileStream))
{
Console.WriteLine("Deleting " + file.GetRelativePath(projectRoot));
File.Delete(file);
}
}
}
sw.Stop();
Console.WriteLine();
Console.WriteLine($"Operation completed in {sw.Elapsed}");
}
private VisualStudioInstance InitialiseMSBuild(IConfiguration configuration)
{
var instances = MSBuildLocator.QueryVisualStudioInstances().ToArray();
if (instances.Length == 0)
Console.WriteLine("No Visual Studio instances found. The code generation might fail");
var vsInstanceIndex = configuration.GetValue<int?>("vsinstance") ?? 0;
if (vsInstanceIndex < 0 || vsInstanceIndex > instances.Length)
{
Console.WriteLine("Invalid VS instance. Falling back to the default one");
vsInstanceIndex = 0;
}
VisualStudioInstance instance;
if (vsInstanceIndex > 0)
{
// Register the selected vs instance. This will cause MSBuildWorkspace to use the MSBuild installed in that instance.
// Note: This has to be registered *before* creating MSBuildWorkspace. Otherwise, the MEF composition used by MSBuildWorkspace will fail to compose.
instance = instances[vsInstanceIndex - 1];
MSBuildLocator.RegisterInstance(instance);
}
else
{
// Use the default vs instance and it's MSBuild
instance = MSBuildLocator.RegisterDefaults();
}
return instance;
}
public IDictionary<string, string> GenerateAreaMap(IEnumerable<ControllerDefinition> controllers)
{
var areaMap = controllers.Select(c => c.Area).Where(a => !string.IsNullOrEmpty(a)).Distinct(StringComparer.OrdinalIgnoreCase).ToDictionary(a => a);
foreach (var area in areaMap.Keys.ToArray())
if (controllers.Any(c => c.Area == string.Empty && c.Name == area))
areaMap[area] = area + "Area";
return areaMap;
}
public void CreateR4MvcUserFile(string filePath)
{
var result = new CodeFileBuilder(_settings, false)
.WithMembers(new ClassBuilder("R4MvcExtensions")
.WithModifiers(SyntaxKind.InternalKeyword)
.WithComment("// Use this file to add custom extensions and helper methods to R4Mvc in your project")
.Build())
.Build();
_filePersistService.WriteFile(result, filePath);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using Microsoft.Win32;
using System;
using System.Text;
using System.Threading;
namespace Microsoft.Win32.RegistryTests
{
public class RegistryKey_SetValueKind_str_obj_valueKind : IDisposable
{
// Variables needed
private RegistryKey _rk1, _rk2;
private String _testKeyName = "Test_Key";
private String _valueName = "";
private String _strExpected = "";
private RegistryValueKind[] _ExpectedKinds;
private Object[] _objArr2 = new Object[2], _objArr;
private Byte[] _byteArr;
private static int s_keyCount = 0;
public void TestInitialize()
{
var counter = Interlocked.Increment(ref s_keyCount);
_testKeyName += counter.ToString();
Random rand = new Random(10);
_ExpectedKinds = new RegistryValueKind[38];
Object obj = new Object();
_objArr2[0] = obj;
_objArr2[1] = obj;
_byteArr = new Byte[rand.Next(0, 100)];
rand.NextBytes(_byteArr);
_objArr = new Object[38];
// Standard Random Numbers
_objArr[0] = (Byte)(rand.Next(Byte.MinValue, Byte.MaxValue));
_objArr[1] = (SByte)(rand.Next(SByte.MinValue, SByte.MaxValue));
_objArr[2] = (Int16)(rand.Next(Int16.MinValue, Int16.MaxValue));
_objArr[3] = (UInt16)(rand.Next(UInt16.MinValue, UInt16.MaxValue));
_objArr[4] = (Char)(rand.Next(UInt16.MinValue, UInt16.MaxValue));
_objArr[5] = (Int32)(rand.Next(Int32.MinValue, Int32.MaxValue));
// Random Numbers that can fit into Int32
_objArr[6] = (UInt32)(rand.NextDouble() * Int32.MaxValue);
_objArr[7] = (Int64)(rand.NextDouble() * Int32.MaxValue);
_objArr[8] = (Int64)(rand.NextDouble() * Int32.MinValue);
_objArr[9] = (UInt64)(rand.NextDouble() * Int32.MaxValue);
_objArr[10] = (Decimal)(rand.NextDouble() * Int32.MaxValue);
_objArr[11] = (Decimal)(rand.NextDouble() * Int32.MinValue);
_objArr[12] = (Single)(rand.NextDouble() * Int32.MaxValue);
_objArr[13] = (Single)(rand.NextDouble() * Int32.MinValue);
_objArr[14] = (Double)(rand.NextDouble() * Int32.MaxValue);
_objArr[15] = (Double)(rand.NextDouble() * Int32.MinValue);
// Random Numbers that can't fit into Int32 but can fit into Int64
_objArr[16] = (UInt32)(rand.NextDouble() * (UInt32.MaxValue - (UInt32)Int32.MaxValue) + (UInt32)Int32.MaxValue);
_objArr[17] = (Int64)(rand.NextDouble() * (Int64.MaxValue - (Int64)Int32.MaxValue) + (Int64)Int32.MaxValue);
_objArr[18] = (Int64)(rand.NextDouble() * (Int64.MinValue - (Int64)Int32.MinValue) + (Int64)Int32.MinValue);
_objArr[19] = (UInt64)(rand.NextDouble() * ((UInt64)Int64.MaxValue - (UInt64)Int32.MaxValue) + (UInt64)Int32.MaxValue);
_objArr[20] = (Decimal)(rand.NextDouble() * (Int64.MaxValue - (Int64)Int32.MaxValue) + (Int64)Int32.MaxValue);
_objArr[21] = (Decimal)(rand.NextDouble() * (Int64.MinValue - (Int64)Int32.MinValue) + (Int64)Int32.MinValue);
_objArr[22] = (Single)(rand.NextDouble() * (Int64.MaxValue - Int32.MaxValue) + Int32.MaxValue);
_objArr[23] = (Single)(rand.NextDouble() * (Int64.MinValue - Int32.MinValue) + Int32.MinValue);
_objArr[24] = (Double)(rand.NextDouble() * (Int64.MaxValue - Int32.MaxValue) + Int32.MaxValue);
_objArr[25] = (Double)(rand.NextDouble() * (Int64.MinValue - Int32.MinValue) + Int32.MinValue);
// Random Numbers that can't fit into Int32 or Int64
_objArr[26] = (UInt64)(rand.NextDouble() * (UInt64.MaxValue - (UInt64)Int64.MaxValue) + (UInt64)Int64.MaxValue);
_objArr[27] = Decimal.MaxValue;
_objArr[28] = Decimal.MinValue;
_objArr[29] = Single.MaxValue;
_objArr[30] = Single.MinValue;
_objArr[31] = Double.MaxValue;
_objArr[32] = Double.MinValue;
// Various other types
_objArr[33] = (String)"Hello World";
_objArr[34] = (String)"Hello %path5% World";
_objArr[35] = new String[] { "Hello World", "Hello %path% World" };
_objArr[36] = (Object)obj;
_objArr[37] = (Byte[])(_byteArr);
_rk1 = Microsoft.Win32.Registry.CurrentUser;
if (_rk1.OpenSubKey(_testKeyName) != null)
_rk1.DeleteSubKeyTree(_testKeyName);
if (_rk1.GetValue(_testKeyName) != null)
_rk1.DeleteValue(_testKeyName);
_rk2 = _rk1.CreateSubKey(_testKeyName);
}
public RegistryKey_SetValueKind_str_obj_valueKind()
{
TestInitialize();
}
[Fact]
public void Test01()
{
// [] Test RegistryValueKind.Unknown
try
{
_ExpectedKinds[0] = RegistryValueKind.String;
_ExpectedKinds[1] = RegistryValueKind.String;
_ExpectedKinds[2] = RegistryValueKind.String;
_ExpectedKinds[3] = RegistryValueKind.String;
_ExpectedKinds[4] = RegistryValueKind.String;
_ExpectedKinds[5] = RegistryValueKind.DWord;
_ExpectedKinds[6] = RegistryValueKind.String;
_ExpectedKinds[7] = RegistryValueKind.String;
_ExpectedKinds[8] = RegistryValueKind.String;
_ExpectedKinds[9] = RegistryValueKind.String;
_ExpectedKinds[10] = RegistryValueKind.String;
_ExpectedKinds[11] = RegistryValueKind.String;
_ExpectedKinds[12] = RegistryValueKind.String;
_ExpectedKinds[13] = RegistryValueKind.String;
_ExpectedKinds[14] = RegistryValueKind.String;
_ExpectedKinds[15] = RegistryValueKind.String;
_ExpectedKinds[16] = RegistryValueKind.String;
_ExpectedKinds[17] = RegistryValueKind.String;
_ExpectedKinds[18] = RegistryValueKind.String;
_ExpectedKinds[19] = RegistryValueKind.String;
_ExpectedKinds[20] = RegistryValueKind.String;
_ExpectedKinds[21] = RegistryValueKind.String;
_ExpectedKinds[22] = RegistryValueKind.String;
_ExpectedKinds[22] = RegistryValueKind.String;
_ExpectedKinds[23] = RegistryValueKind.String;
_ExpectedKinds[24] = RegistryValueKind.String;
_ExpectedKinds[25] = RegistryValueKind.String;
_ExpectedKinds[26] = RegistryValueKind.String;
_ExpectedKinds[27] = RegistryValueKind.String;
_ExpectedKinds[28] = RegistryValueKind.String;
_ExpectedKinds[29] = RegistryValueKind.String;
_ExpectedKinds[30] = RegistryValueKind.String;
_ExpectedKinds[31] = RegistryValueKind.String;
_ExpectedKinds[32] = RegistryValueKind.String;
_ExpectedKinds[33] = RegistryValueKind.String;
_ExpectedKinds[34] = RegistryValueKind.String;
_ExpectedKinds[35] = RegistryValueKind.MultiString;
_ExpectedKinds[36] = RegistryValueKind.String;
_ExpectedKinds[37] = RegistryValueKind.Binary;
for (int i = 0; i < _objArr.Length; i++)
{
_valueName = "Testing " + i;
_rk2.SetValue(_valueName, _objArr[i], RegistryValueKind.Unknown);
if (_rk2.GetValue(_valueName).ToString() != _objArr[i].ToString() || _rk2.GetValueKind(_valueName) != _ExpectedKinds[i])
{
Assert.False(true, "Error Type==" + _objArr[i].GetType() + " Expected==" + _objArr[i].ToString() + " kind==" + _ExpectedKinds[i].ToString() + ", got value==" + _rk2.GetValue(_valueName).ToString() + " kind==" + _rk2.GetValueKind(_valueName).ToString());
}
}
}
catch (Exception e)
{
Assert.False(true, "Err_2121 Unexpected exception :: " + e.ToString());
}
}
[Fact]
public void Test02()
{
// [] Test RegistryValueKind.String
try
{
for (int i = 0; i < _objArr.Length; i++)
{
_valueName = "Testing " + i;
_rk2.SetValue(_valueName, _objArr[i], RegistryValueKind.String);
if (_rk2.GetValue(_valueName).ToString() != _objArr[i].ToString() || _rk2.GetValueKind(_valueName) != RegistryValueKind.String)
{
Assert.False(true, "Error Type==" + _objArr[i].GetType() + " Expected==" + _objArr[i].ToString() + " kind==" + RegistryValueKind.String + ", got value==" + _rk2.GetValue(_valueName).ToString() + " kind==" + _rk2.GetValueKind(_valueName).ToString());
}
}
}
catch (Exception e)
{
Assert.False(true, "Err_782sg Unexpected exception :: " + e.ToString());
}
}
[Fact]
public void Test03()
{
// [] Test RegistryValueKind.ExpandString
try
{
for (int i = 0; i < _objArr.Length; i++)
{
_valueName = "Testing " + i;
_rk2.SetValue(_valueName, _objArr[i], RegistryValueKind.ExpandString);
if (_rk2.GetValue(_valueName).ToString() != _objArr[i].ToString() || _rk2.GetValueKind(_valueName) != RegistryValueKind.ExpandString)
{
Assert.False(true, "Error Type==" + _objArr[i].GetType() + " Expected==" + _objArr[i].ToString() + " kind==" + RegistryValueKind.ExpandString + ", got value==" + _rk2.GetValue(_valueName).ToString() + " kind==" + _rk2.GetValueKind(_valueName).ToString());
}
}
}
catch (Exception e)
{
Assert.False(true, "Err_482hv Unexpected exception :: " + e.ToString());
}
}
[Fact]
public void Test04()
{
// [] Test RegistryValueKind.MultiString
try
{
for (int i = 0; i < _objArr.Length; i++)
{
try
{
_valueName = "Testing " + i;
_rk2.SetValue(_valueName, _objArr[i], RegistryValueKind.MultiString);
if (_rk2.GetValue(_valueName).ToString() != _objArr[i].ToString() || _rk2.GetValueKind(_valueName) != RegistryValueKind.MultiString)
{
Assert.False(true, "Error Type==" + _objArr[i].GetType() + " Expected==" + _objArr[i].ToString() + " kind==" + RegistryValueKind.MultiString + ", got value==" + _rk2.GetValue(_valueName).ToString() + " kind==" + _rk2.GetValueKind(_valueName).ToString());
}
}
catch (ArgumentException)
{ }
catch (Exception ioe)
{
if ((ioe.GetType() == typeof(ArgumentException)) && (_objArr[i].GetType() == (new string[0]).GetType()))
{
Assert.False(true, "Error Type==" + _objArr[i].GetType() + " Expected==" + _objArr[i].ToString() + " kind==" + RegistryValueKind.MultiString + ", got exception==" + ioe.ToString());
}
else
{
Assert.False(true, "Error Incorrect exception , got exc==" + ioe.ToString());
}
}
}
}
catch (Exception e)
{
Assert.False(true, "Err_152wk Unexpected exception :: " + e.ToString());
}
}
[Fact]
public void Test05()
{
// [] Test RegistryValueKind.Binary
try
{
for (int i = 0; i < _objArr.Length; i++)
{
try
{
_valueName = "Testing " + i;
_rk2.SetValue(_valueName, _objArr[i], RegistryValueKind.Binary);
if (_rk2.GetValue(_valueName).ToString() != _objArr[i].ToString() || _rk2.GetValueKind(_valueName) != RegistryValueKind.Binary)
{
Assert.False(true, "Error Type==" + _objArr[i].GetType() + " Expected==" + _objArr[i].ToString() + " kind==" + RegistryValueKind.Binary + ", got value==" + _rk2.GetValue(_valueName).ToString() + " kind==" + _rk2.GetValueKind(_valueName).ToString());
}
}
catch (ArgumentException)
{ }
catch (Exception ioe)
{
if ((ioe.GetType() == typeof(ArgumentException)) && (_objArr[i].GetType() == (new byte[0]).GetType()))
{
Assert.False(true, "Error Type==" + _objArr[i].GetType() + " Expected==" + _objArr[i].ToString() + " kind==" + RegistryValueKind.Binary + ", got exception==" + ioe.ToString());
}
else
{
Assert.False(true, "Error Incorrect exception , got exc==" + ioe.ToString());
}
}
}
}
catch (Exception e)
{
Assert.False(true, "Err_152ex Unexpected exception :: " + e.ToString());
}
}
[Fact]
public void Test06()
{
// [] Test RegistryValueKind.DWord
try
{
for (int i = 0; i < _objArr.Length; i++)
{
try
{
if (i <= 15)
{
_strExpected = (Convert.ToInt32(_objArr[i])).ToString();
}
_valueName = "Testing " + i;
_rk2.SetValue(_valueName, _objArr[i], RegistryValueKind.DWord);
if (_rk2.GetValue(_valueName).ToString() != _strExpected || _rk2.GetValueKind(_valueName) != RegistryValueKind.DWord)
{
Assert.False(true, "Error Type==" + _objArr[i].GetType() + " Expected==" + _strExpected + " kind==" + RegistryValueKind.DWord + ", got value==" + _rk2.GetValue(_valueName).ToString() + " kind==" + _rk2.GetValueKind(_valueName).ToString());
}
if (i > 15)
{
Assert.False(true, "Error Type==" + _objArr[i].GetType() + " Expected==Exception, got value==" + _rk2.GetValue(_valueName).ToString() + " kind==" + _rk2.GetValueKind(_valueName).ToString());
}
}
catch (ArgumentException)
{ }
catch (Exception ioe)
{
if (i < 15)
{
Assert.False(true, "Error Type==" + _objArr[i].GetType() + " Expected==" + _objArr[i].ToString() + " kind==" + RegistryValueKind.DWord + ", got exception==" + ioe.ToString());
}
else
{
Assert.False(true, "Error Incorrect exception , got exc==" + ioe.ToString());
}
}
}
}
catch (Exception e)
{
Assert.False(true, "Err_744ss Unexpected exception :: " + e.ToString());
}
}
[Fact]
public void Test07()
{
// [] Test RegistryValueKind.QWord
try
{
for (int i = 0; i < _objArr.Length; i++)
{
try
{
if (i <= 25)
{
_strExpected = (Convert.ToInt64(_objArr[i])).ToString();
}
_valueName = "Testing " + i;
_rk2.SetValue(_valueName, _objArr[i], RegistryValueKind.QWord);
if (_rk2.GetValue(_valueName).ToString() != _strExpected || _rk2.GetValueKind(_valueName) != RegistryValueKind.QWord)
{
Assert.False(true, "Error Type==" + _objArr[i].GetType() + " Expected==" + _strExpected + " kind==" + RegistryValueKind.QWord + ", got value==" + _rk2.GetValue(_valueName).ToString() + " kind==" + _rk2.GetValueKind(_valueName).ToString());
}
if (i > 25)
{
Assert.False(true, "Error Type==" + _objArr[i].GetType() + " Expected==Exception, got value==" + _rk2.GetValue(_valueName).ToString() + " kind==" + _rk2.GetValueKind(_valueName).ToString());
}
}
catch (ArgumentException)
{ }
catch (Exception ioe)
{
if (i < 25)
{
Assert.False(true, "Error Type==" + _objArr[i].GetType() + " Expected==" + _objArr[i].ToString() + " kind==" + RegistryValueKind.QWord + ", got exception==" + ioe.ToString());
}
else
{
Assert.False(true, "Error Incorrect exception , got exc==" + ioe.ToString());
}
}
}
}
catch (Exception e)
{
Assert.False(true, "Err_745ss Unexpected exception :: " + e.ToString());
}
}
[Fact]
public void Test08()
{
// [] Registry Key does not exist
try
{
_valueName = "FooBar";
_rk2.SetValue(_valueName, _objArr[5], RegistryValueKind.DWord);
if (_rk2.GetValue(_valueName).ToString() != _objArr[5].ToString() || _rk2.GetValueKind(_valueName) != RegistryValueKind.DWord)
{
Assert.False(true, "Error Type==" + _objArr[5].GetType() + " Expected==" + _objArr[5].ToString() + " kind==" + RegistryValueKind.DWord + ", got value==" + _rk2.GetValue(_valueName).ToString() + " kind==" + _rk2.GetValueKind(_valueName).ToString());
}
}
catch (Exception e)
{
Assert.False(true, "Err_484ec Unexpected exception :: " + e.ToString());
}
}
[Fact]
public void Test09()
{
// [] Registry Key already exists
try
{
_valueName = "FooBar";
_rk2.SetValue(_valueName, _objArr[7], RegistryValueKind.QWord);
if (_rk2.GetValue(_valueName).ToString() != _objArr[7].ToString() || _rk2.GetValueKind(_valueName) != RegistryValueKind.QWord)
{
Assert.False(true, "Error Type==" + _objArr[7].GetType() + " Expected==" + _objArr[7].ToString() + " kind==" + RegistryValueKind.QWord + ", got value==" + _rk2.GetValue(_valueName).ToString() + " kind==" + _rk2.GetValueKind(_valueName).ToString());
}
}
catch (Exception e)
{
Assert.False(true, "Err_541ll Unexpected exception :: " + e.ToString());
}
}
[Fact]
public void Test10()
{
// [] Name is null
try
{
_valueName = null;
_rk2.SetValue(_valueName, _objArr[5], RegistryValueKind.DWord);
if (_rk2.GetValue(_valueName).ToString() != _objArr[5].ToString() || _rk2.GetValueKind(_valueName) != RegistryValueKind.DWord)
{
Assert.False(true, "Error Type==" + _objArr[5].GetType() + " Expected==" + _objArr[5].ToString() + " kind==" + RegistryValueKind.DWord + ", got value==" + _rk2.GetValue(_valueName).ToString() + " kind==" + _rk2.GetValueKind(_valueName).ToString());
}
}
catch (Exception e)
{
Assert.False(true, "Err_556po Unexpected exception :: " + e.ToString());
}
}
[Fact]
public void Test11()
{
// [] Name is ""
try
{
_valueName = "";
_rk2.SetValue(_valueName, _objArr[7], RegistryValueKind.QWord);
if (_rk2.GetValue(_valueName).ToString() != _objArr[7].ToString() || _rk2.GetValueKind(_valueName) != RegistryValueKind.QWord)
{
Assert.False(true, "Error Type==" + _objArr[7].GetType() + " Expected==" + _objArr[7].ToString() + " kind==" + RegistryValueKind.QWord + ", got value==" + _rk2.GetValue(_valueName).ToString() + " kind==" + _rk2.GetValueKind(_valueName).ToString());
}
}
catch (Exception e)
{
Assert.False(true, "Err_548ov Unexpected exception :: " + e.ToString());
}
}
[Fact]
public void Test12()
{
// [] Name is 255 characters
try
{
_valueName = "12345678901111111110222222222033333333304444444440555555555066666666607777777770888888888099999999901234567890111111111022222222203333333330444444444055555555506666666660777777777088888888809999999990123456789011111111102222222220333333333044444444405555";
_rk2.SetValue(_valueName, _objArr[7], RegistryValueKind.QWord);
if (_rk2.GetValue(_valueName).ToString() != _objArr[7].ToString() || _rk2.GetValueKind(_valueName) != RegistryValueKind.QWord)
{
Assert.False(true, "Error Type==" + _objArr[7].GetType() + " Expected==" + _objArr[7].ToString() + " kind==" + RegistryValueKind.QWord + ", got value==" + _rk2.GetValue(_valueName).ToString() + " kind==" + _rk2.GetValueKind(_valueName).ToString());
}
}
catch (Exception e)
{
Assert.False(true, "Err_458mn Unexpected exception :: " + e.ToString());
}
}
[Fact]
public void Test13()
{
// [] Name is longer then 16383 characters
Action a = () =>
{
int MaxValueNameLength = 16383; // prior to V4, the limit is 255
StringBuilder sb = new StringBuilder(MaxValueNameLength + 1);
for (int i = 0; i <= MaxValueNameLength; i++)
sb.Append('a');
_valueName = sb.ToString();
_rk2.SetValue(_valueName, _objArr[7], RegistryValueKind.QWord);
};
Assert.Throws<ArgumentException>(() => { a(); });
}
[Fact]
public void Test14()
{
// [] Value is null
Action a = () =>
{
_valueName = "FooBar";
_rk2.SetValue(_valueName, null, RegistryValueKind.QWord);
};
Assert.Throws<ArgumentNullException>(() => { a(); });
}
[Fact]
public void Test15()
{
// [] ValueKind is equal to -2 which is not an acceptable value
Action a = () =>
{
_valueName = "FooBar";
_rk2.SetValue(_valueName, _objArr[5], (RegistryValueKind)(-2));
};
Assert.Throws<ArgumentException>(() => { a(); });
}
[Fact]
public void Test16()
{
// [] value is a string[] with null values
Action a = () =>
{
_valueName = "FooBar";
string[] strArr = new String[] { "one", "two", null, "three" };
_rk2.SetValue(_valueName, strArr, RegistryValueKind.MultiString);
};
Assert.Throws<ArgumentException>(() => { a(); });
}
[Fact]
public void Test17()
{
// [] value is a object[]
Action a = () =>
{
_valueName = "FooBar";
_rk2.SetValue(_valueName, _objArr2, RegistryValueKind.MultiString);
};
Assert.Throws<ArgumentException>(() => { a(); });
}
[Fact]
public void Test18()
{
// [] RegistryKey is readonly
Action a = () =>
{
_valueName = "FooBar";
RegistryKey rk3 = _rk1.OpenSubKey(_testKeyName, false);
rk3.SetValue(_valueName, _objArr[5], RegistryValueKind.DWord);
};
Assert.Throws<UnauthorizedAccessException>(() => { a(); });
}
[Fact]
public void Test19()
{
// [] Set RegistryKey to bad array type. // To improve code coverage
Action a = () =>
{
object[] objTemp = new object[] { "my string", "your string", "Any once string" };
_rk2.SetValue(_valueName, objTemp, RegistryValueKind.Unknown);
};
Assert.Throws<ArgumentException>(() => { a(); });
}
[Fact]
public void Test20()
{
// [] RegistryKey is closed
Action a = () =>
{
_rk2.Dispose();
_valueName = "FooBar";
_rk2.SetValue(_valueName, _objArr[5], RegistryValueKind.DWord);
};
Assert.Throws<ObjectDisposedException>(() => { a(); });
}
public void Dispose()
{
if (_rk1.OpenSubKey(_testKeyName) != null)
_rk1.DeleteSubKeyTree(_testKeyName);
if (_rk1.GetValue(_testKeyName) != null)
_rk1.DeleteValue(_testKeyName);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEditor.Experimental.VFX;
using UnityEngine.Experimental.VFX;
namespace UnityEditor.VFX
{
// TODO Move this
// Must match enum in C++
public enum VFXCoordinateSpace
{
Local = 0,
World = 1,
}
// TODO Move this
public interface ISpaceable
{
VFXCoordinateSpace space { get; set; }
}
abstract class VFXData : VFXModel
{
public abstract VFXDataType type { get; }
public virtual uint sourceCount
{
get
{
return 0u;
}
}
public IEnumerable<VFXContext> owners
{
get { return m_Owners; }
}
public string title;
public int index
{
get
{
if ( m_Parent == null)
{
string assetPath = AssetDatabase.GetAssetPath(this);
m_Parent = VisualEffectResource.GetResourceAtPath(assetPath).GetOrCreateGraph();
}
VFXGraph graph = GetGraph();
HashSet<VFXData> datas = new HashSet<VFXData>();
foreach (var child in graph.children.OfType<VFXContext>())
{
VFXData data = (child as VFXContext).GetData();
if (data != null)
datas.Add(data);
if (data == this)
return datas.Count();
}
throw new InvalidOperationException("Can't determine index of a VFXData without context");
}
}
public string fileName {
get {
if( ! string.IsNullOrWhiteSpace(title))
return title;
int i = this.index;
if (i < 0)
return string.Empty;
return string.IsNullOrEmpty(title)?string.Format("System {0}",index):title;
}
}
public IEnumerable<VFXContext> implicitContexts
{
get { return Enumerable.Empty<VFXContext>(); }
}
public static VFXData CreateDataType(VFXGraph graph,VFXDataType type)
{
VFXData newVFXData;
switch (type)
{
case VFXDataType.kParticle:
newVFXData = ScriptableObject.CreateInstance<VFXDataParticle>();
break;
case VFXDataType.kMesh:
newVFXData = ScriptableObject.CreateInstance<VFXDataMesh>();
break;
default: return null;
}
newVFXData.m_Parent = graph;
return newVFXData;
}
public override void OnEnable()
{
base.OnEnable();
if (m_Owners == null)
m_Owners = new List<VFXContext>();
else
{
// Remove bad references if any
// The code below was replaced because it caused some strange crashes for unknown reasons
//int nbRemoved = m_Owners.RemoveAll(o => o == null);
int nbRemoved = 0;
for (int i = 0; i < m_Owners.Count; ++i)
if (m_Owners[i] == null)
{
m_Owners.RemoveAt(i--);
++nbRemoved;
}
if (nbRemoved > 0)
Debug.Log(String.Format("Remove {0} owners that couldnt be deserialized from {1} of type {2}", nbRemoved, name, GetType()));
}
}
public override void Sanitize(int version)
{
base.Sanitize(version);
if( m_Parent == null)
{
string assetPath = AssetDatabase.GetAssetPath(this);
m_Parent = VisualEffectResource.GetResourceAtPath(assetPath).GetOrCreateGraph();
}
}
public abstract void CopySettings<T>(T dst) where T : VFXData;
public virtual bool CanBeCompiled()
{
return true;
}
public virtual void FillDescs(
List<VFXGPUBufferDesc> outBufferDescs,
List<VFXEditorSystemDesc> outSystemDescs,
VFXExpressionGraph expressionGraph,
Dictionary<VFXContext, VFXContextCompiledData> contextToCompiledData,
Dictionary<VFXContext, int> contextSpawnToBufferIndex,
Dictionary<VFXData, int> attributeBuffer,
Dictionary<VFXData, int> eventBuffer)
{
// Empty implementation by default
}
// Never call this directly ! Only context must call this through SetData
public void OnContextAdded(VFXContext context)
{
if (context == null)
throw new ArgumentNullException();
if (m_Owners.Contains(context))
throw new ArgumentException(string.Format("{0} is already in the owner list of {1}", context, this));
m_Owners.Add(context);
}
// Never call this directly ! Only context must call this through SetData
public void OnContextRemoved(VFXContext context)
{
if (!m_Owners.Remove(context))
throw new ArgumentException(string.Format("{0} is not in the owner list of {1}", context, this));
}
public bool IsCurrentAttributeRead(VFXAttribute attrib) { return (GetAttributeMode(attrib) & VFXAttributeMode.Read) != 0; }
public bool IsCurrentAttributeWritten(VFXAttribute attrib) { return (GetAttributeMode(attrib) & VFXAttributeMode.Write) != 0; }
public bool IsCurrentAttributeRead(VFXAttribute attrib, VFXContext context) { return (GetAttributeMode(attrib, context) & VFXAttributeMode.Read) != 0; }
public bool IsCurrentAttributeWritten(VFXAttribute attrib, VFXContext context) { return (GetAttributeMode(attrib, context) & VFXAttributeMode.Write) != 0; }
public bool IsAttributeUsed(VFXAttribute attrib) { return GetAttributeMode(attrib) != VFXAttributeMode.None; }
public bool IsAttributeUsed(VFXAttribute attrib, VFXContext context) { return GetAttributeMode(attrib, context) != VFXAttributeMode.None; }
public bool IsCurrentAttributeUsed(VFXAttribute attrib) { return (GetAttributeMode(attrib) & VFXAttributeMode.ReadWrite) != 0; }
public bool IsSourceAttributeUsed(VFXAttribute attrib) { return (GetAttributeMode(attrib) & VFXAttributeMode.ReadSource) != 0; }
public bool IsSourceAttributeUsed(VFXAttribute attrib, VFXContext context) { return (GetAttributeMode(attrib, context) & VFXAttributeMode.ReadSource) != 0; }
public bool IsAttributeLocal(VFXAttribute attrib) { return m_LocalCurrentAttributes.Contains(attrib); }
public bool IsAttributeStored(VFXAttribute attrib) { return m_StoredCurrentAttributes.ContainsKey(attrib); }
public VFXAttributeMode GetAttributeMode(VFXAttribute attrib, VFXContext context)
{
Dictionary<VFXContext, VFXAttributeMode> contexts;
if (m_AttributesToContexts.TryGetValue(attrib, out contexts))
{
foreach (var c in contexts)
if (c.Key == context)
return c.Value;
}
return VFXAttributeMode.None;
}
public VFXAttributeMode GetAttributeMode(VFXAttribute attrib)
{
VFXAttributeMode mode = VFXAttributeMode.None;
Dictionary<VFXContext, VFXAttributeMode> contexts;
if (m_AttributesToContexts.TryGetValue(attrib, out contexts))
{
foreach (var context in contexts)
mode |= context.Value;
}
return mode;
}
public int GetNbAttributes()
{
return m_AttributesToContexts.Count;
}
public IEnumerable<VFXAttributeInfo> GetAttributes()
{
foreach (var attrib in m_AttributesToContexts)
{
VFXAttributeInfo info;
info.attrib = attrib.Key;
info.mode = VFXAttributeMode.None;
foreach (var context in attrib.Value)
info.mode |= context.Value;
yield return info;
}
}
public IEnumerable<VFXAttributeInfo> GetAttributesForContext(VFXContext context)
{
Dictionary<VFXAttribute, VFXAttributeMode> attribs;
if (m_ContextsToAttributes.TryGetValue(context, out attribs))
{
foreach (var attrib in attribs)
{
VFXAttributeInfo info;
info.attrib = attrib.Key;
info.mode = attrib.Value;
yield return info;
}
}
else
throw new ArgumentException("Context does not exist");
}
private struct VFXAttributeInfoContext
{
public VFXAttributeInfo[] attributes;
public VFXContext context;
}
public abstract VFXDeviceTarget GetCompilationTarget(VFXContext context);
// Create implicit contexts and initialize cached contexts list
public virtual IEnumerable<VFXContext> InitImplicitContexts()
{
m_Contexts = m_Owners;
return Enumerable.Empty<VFXContext>();
}
public void CollectAttributes()
{
if (m_Contexts == null) // Context hasnt been initialized (may happen in unity tests but not during actual compilation)
InitImplicitContexts();
m_DependenciesIn = new HashSet<VFXData>(
m_Contexts.Where(c => c.contextType == VFXContextType.kInit)
.SelectMany(c => c.inputContexts.Where(i => i.contextType == VFXContextType.kSpawnerGPU))
.SelectMany(c => c.allLinkedInputSlot)
.Where(s =>
{
if (s.owner is VFXBlock)
{
VFXBlock block = (VFXBlock)(s.owner);
if (block.enabled)
return true;
}
else if (s.owner is VFXContext)
{
return true;
}
return false;
})
.Select(s => ((VFXModel)s.owner).GetFirstOfType<VFXContext>())
.Where(c => c.CanBeCompiled())
.Select(c => c.GetData())
);
m_DependenciesOut = new HashSet<VFXData>(
owners.SelectMany(o => o.allLinkedOutputSlot)
.Select(s => (VFXContext)s.owner)
.Where(c => c.CanBeCompiled())
.SelectMany(c => c.outputContexts)
.Where(c => c.CanBeCompiled())
.Select(c => c.GetData())
);
m_ContextsToAttributes.Clear();
m_AttributesToContexts.Clear();
var processedExp = new HashSet<VFXExpression>();
bool changed = true;
int count = 0;
while (changed)
{
++count;
var attributeContexts = new List<VFXAttributeInfoContext>();
foreach (var context in m_Contexts)
{
processedExp.Clear();
var attributes = Enumerable.Empty<VFXAttributeInfo>();
attributes = attributes.Concat(context.attributes);
foreach (var block in context.activeChildrenWithImplicit)
attributes = attributes.Concat(block.attributes);
var mapper = context.GetExpressionMapper(GetCompilationTarget(context));
if (mapper != null)
foreach (var exp in mapper.expressions)
attributes = attributes.Concat(CollectInputAttributes(exp, processedExp));
attributeContexts.Add(new VFXAttributeInfoContext
{
attributes = attributes.ToArray(),
context = context
});
}
changed = false;
foreach (var context in attributeContexts)
{
foreach (var attribute in context.attributes)
{
if (AddAttribute(context.context, attribute))
{
changed = true;
}
}
}
}
ProcessAttributes();
//TMP Debug only
DebugLogAttributes();
}
public void ProcessDependencies()
{
ComputeLayer();
// Update attributes
foreach (var childData in m_DependenciesOut)
{
foreach (var attrib in childData.m_ReadSourceAttributes)
{
if (!m_StoredCurrentAttributes.ContainsKey(attrib))
{
m_LocalCurrentAttributes.Remove(attrib);
m_StoredCurrentAttributes.Add(attrib, 0);
}
}
}
}
private static uint ComputeLayer(IEnumerable<VFXData> dependenciesIn)
{
if (dependenciesIn.Any())
{
return 1u + ComputeLayer(dependenciesIn.SelectMany(o => o.m_DependenciesIn));
}
return 0u;
}
private void ComputeLayer()
{
if (!m_DependenciesIn.Any() && !m_DependenciesOut.Any())
{
m_Layer = uint.MaxValue; //Completely independent system
}
else
{
m_Layer = ComputeLayer(m_DependenciesIn);
}
}
protected bool HasImplicitInit(VFXAttribute attrib)
{
return (attrib.Equals(VFXAttribute.Seed) || attrib.Equals(VFXAttribute.ParticleId));
}
private void ProcessAttributes()
{
m_StoredCurrentAttributes.Clear();
m_LocalCurrentAttributes.Clear();
m_ReadSourceAttributes.Clear();
if (type == VFXDataType.kParticle)
{
m_ReadSourceAttributes.Add(new VFXAttribute("spawnCount", VFXValueType.Float)); // TODO dirty
}
int contextCount = m_Contexts.Count;
if (contextCount > 16)
throw new InvalidOperationException(string.Format("Too many contexts that use particle data {0} > 16", contextCount));
foreach (var kvp in m_AttributesToContexts)
{
bool local = false;
var attribute = kvp.Key;
int key = 0;
bool onlyInit = true;
bool onlyOutput = true;
bool onlyUpdateRead = true;
bool onlyUpdateWrite = true;
bool needsSpecialInit = HasImplicitInit(attribute);
bool writtenInInit = needsSpecialInit;
bool readSourceInInit = false;
foreach (var kvp2 in kvp.Value)
{
var context = kvp2.Key;
if (context.contextType == VFXContextType.kInit
&& (kvp2.Value & VFXAttributeMode.ReadSource) != 0)
{
readSourceInInit = true;
}
if (kvp2.Value == VFXAttributeMode.None)
{
throw new InvalidOperationException("Unexpected attribute mode : " + attribute);
}
if (kvp2.Value == VFXAttributeMode.ReadSource)
{
continue;
}
if (context.contextType != VFXContextType.kInit)
onlyInit = false;
if (context.contextType != VFXContextType.kOutput)
onlyOutput = false;
if (context.contextType != VFXContextType.kUpdate)
{
onlyUpdateRead = false;
onlyUpdateWrite = false;
}
else
{
if ((kvp2.Value & VFXAttributeMode.Read) != 0)
onlyUpdateWrite = false;
if ((kvp2.Value & VFXAttributeMode.Write) != 0)
onlyUpdateRead = false;
}
if (context.contextType != VFXContextType.kInit) // Init isnt taken into account for key computation
{
int shift = m_Contexts.IndexOf(context) << 1;
int value = 0;
if ((kvp2.Value & VFXAttributeMode.Read) != 0)
value |= 0x01;
if (((kvp2.Value & VFXAttributeMode.Write) != 0) && context.contextType == VFXContextType.kUpdate)
value |= 0x02;
key |= (value << shift);
}
else if ((kvp2.Value & VFXAttributeMode.Write) != 0)
writtenInInit = true;
}
if ((key & ~0xAAAAAAAA) == 0) // no read
local = true;
if (onlyUpdateWrite || onlyInit || (!needsSpecialInit && (onlyUpdateRead || onlyOutput))) // no shared atributes
local = true;
if (!writtenInInit && (key & 0xAAAAAAAA) == 0) // no write mask
local = true;
if (VFXAttribute.AllAttributeLocalOnly.Contains(attribute))
local = true;
if (local)
m_LocalCurrentAttributes.Add(attribute);
else
m_StoredCurrentAttributes.Add(attribute, key);
if (readSourceInInit)
m_ReadSourceAttributes.Add(attribute);
}
}
public abstract void GenerateAttributeLayout();
public abstract string GetAttributeDataDeclaration(VFXAttributeMode mode);
public abstract string GetLoadAttributeCode(VFXAttribute attrib, VFXAttributeLocation location);
public abstract string GetStoreAttributeCode(VFXAttribute attrib, string value);
private bool AddAttribute(VFXContext context, VFXAttributeInfo attribInfo)
{
if (attribInfo.mode == VFXAttributeMode.None)
throw new ArgumentException("Cannot add an attribute without mode");
Dictionary<VFXAttribute, VFXAttributeMode> attribs;
if (!m_ContextsToAttributes.TryGetValue(context, out attribs))
{
attribs = new Dictionary<VFXAttribute, VFXAttributeMode>();
m_ContextsToAttributes.Add(context, attribs);
}
var attrib = attribInfo.attrib;
var mode = attribInfo.mode;
bool hasChanged = false;
if (attribs.ContainsKey(attrib))
{
var oldMode = attribs[attrib];
mode |= attribs[attrib];
if (mode != oldMode)
{
attribs[attrib] = mode;
hasChanged = true;
}
}
else
{
attribs[attrib] = mode;
hasChanged = true;
}
if (hasChanged)
{
Dictionary<VFXContext, VFXAttributeMode> contexts;
if (!m_AttributesToContexts.TryGetValue(attrib, out contexts))
{
contexts = new Dictionary<VFXContext, VFXAttributeMode>();
m_AttributesToContexts.Add(attrib, contexts);
}
contexts[context] = mode;
}
return hasChanged;
}
// Collect attribute expressions recursively
private IEnumerable<VFXAttributeInfo> CollectInputAttributes(VFXExpression exp, HashSet<VFXExpression> processed)
{
if (!processed.Contains(exp) && exp.Is(VFXExpression.Flags.PerElement)) // Testing per element allows to early out as it is propagated
{
processed.Add(exp);
foreach (var info in exp.GetNeededAttributes())
yield return info;
foreach (var parent in exp.parents)
{
foreach (var info in CollectInputAttributes(parent, processed))
yield return info;
}
}
}
private void DebugLogAttributes()
{
if (!VFXViewPreference.advancedLogs)
return;
var builder = new StringBuilder();
builder.AppendLine(string.Format("Attributes for data {0} of type {1}", GetHashCode(), GetType()));
foreach (var context in m_Contexts)
{
Dictionary<VFXAttribute, VFXAttributeMode> attributeInfos;
if (m_ContextsToAttributes.TryGetValue(context, out attributeInfos))
{
builder.AppendLine(string.Format("\tContext {1} {0}", context.GetHashCode(), context.contextType));
foreach (var kvp in attributeInfos)
builder.AppendLine(string.Format("\t\tAttribute {0} {1} {2}", kvp.Key.name, kvp.Key.type, kvp.Value));
}
}
if (m_StoredCurrentAttributes.Count > 0)
{
builder.AppendLine("--- STORED CURRENT ATTRIBUTES ---");
foreach (var kvp in m_StoredCurrentAttributes)
builder.AppendLine(string.Format("\t\tAttribute {0} {1} {2}", kvp.Key.name, kvp.Key.type, kvp.Value));
}
if (m_AttributesToContexts.Count > 0)
{
builder.AppendLine("--- LOCAL CURRENT ATTRIBUTES ---");
foreach (var attrib in m_LocalCurrentAttributes)
builder.AppendLine(string.Format("\t\tAttribute {0} {1}", attrib.name, attrib.type));
}
Debug.Log(builder.ToString());
}
public uint layer
{
get
{
return m_Layer;
}
}
public IEnumerable<VFXData> dependenciesIn
{
get
{
return m_DependenciesIn;
}
}
public IEnumerable<VFXData> dependenciesOut
{
get
{
return m_DependenciesOut;
}
}
[SerializeField]
protected List<VFXContext> m_Owners;
[NonSerialized]
protected List<VFXContext> m_Contexts;
[NonSerialized]
protected Dictionary<VFXContext, Dictionary<VFXAttribute, VFXAttributeMode>> m_ContextsToAttributes = new Dictionary<VFXContext, Dictionary<VFXAttribute, VFXAttributeMode>>();
[NonSerialized]
protected Dictionary<VFXAttribute, Dictionary<VFXContext, VFXAttributeMode>> m_AttributesToContexts = new Dictionary<VFXAttribute, Dictionary<VFXContext, VFXAttributeMode>>();
[NonSerialized]
protected Dictionary<VFXAttribute, int> m_StoredCurrentAttributes = new Dictionary<VFXAttribute, int>();
[NonSerialized]
protected HashSet<VFXAttribute> m_LocalCurrentAttributes = new HashSet<VFXAttribute>();
[NonSerialized]
protected HashSet<VFXAttribute> m_ReadSourceAttributes = new HashSet<VFXAttribute>();
[NonSerialized]
protected HashSet<VFXData> m_DependenciesIn = new HashSet<VFXData>();
[NonSerialized]
protected HashSet<VFXData> m_DependenciesOut = new HashSet<VFXData>();
[NonSerialized]
protected uint m_Layer;
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Diagnostics;
using System.Drawing;
using System.Reflection;
using System.Collections;
using OpenLiveWriter.Localization;
using OpenLiveWriter.Localization.Bidi;
namespace OpenLiveWriter.CoreServices
{
/// <summary>
/// Resource helper class.
/// </summary>
public sealed class ResourceHelper
{
/// <summary>
/// The bitmap cache.
/// </summary>
[ThreadStatic]
private static Dictionary<string, Bitmap> bitmapCache;
/// <summary>
/// The icon cache
/// </summary>
[ThreadStatic]
private static Hashtable iconCache;
/// <summary>
/// Initializes a new instance of the ResourceHelper class.
/// </summary>
private ResourceHelper()
{
}
/// <summary>
/// Loads a Bitmap from the calling Assembly's resource stream.
/// </summary>
/// <param name="resource">The name of the Bitmap to load (i.e. "Image.png").</param>
public static Bitmap LoadAssemblyResourceBitmap(string resource)
{
return LoadAssemblyResourceBitmap(Assembly.GetCallingAssembly(), null, resource, false);
}
public static Bitmap LoadAssemblyResourceBitmap(string resource, bool mirror)
{
return LoadAssemblyResourceBitmap(Assembly.GetCallingAssembly(), null, resource, mirror);
}
/// <summary>
/// Loads a Bitmap from the calling Assembly's resource stream.
/// </summary>
/// <param name="path">The explicit path to the Bitmap, null to use the default.</param>
/// <param name="resource">The name of the Bitmap to load (i.e. "Image.png").</param>
public static Bitmap LoadAssemblyResourceBitmap(string path, string resource)
{
return LoadAssemblyResourceBitmap(Assembly.GetCallingAssembly(), path, resource, false);
}
/// <summary>
/// Loads a Bitmap from an Assembly's resource stream.
/// </summary>
/// <param name="assembly">The Assembly to load the Bitmap from.</param>
/// <param name="resource">The name of the Bitmap to load (i.e. "Image.png").</param>
public static Bitmap LoadAssemblyResourceBitmap(Assembly assembly, string resource)
{
return LoadAssemblyResourceBitmap(assembly, null, resource, false);
}
/// <summary>
/// Loads a Bitmap from an Assembly's resource stream.
/// </summary>
/// <param name="assembly">The Assembly to load the Bitmap from.</param>
/// <param name="path">The explicit path to the Bitmap, null to use the default.</param>
/// <param name="resource">The name of the Bitmap to load (i.e. "Image.png").</param>
public static Bitmap LoadAssemblyResourceBitmap(Assembly assembly, string path, string resource, bool mirror)
{
// If a path was not specified, default to using the name of the assembly.
if (path == null)
path = assembly.GetName().Name;
// Format the schema resource name that we will load from the assembly.
string resourceName = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", path, resource);
string key = String.Format(CultureInfo.InvariantCulture, "{0},{1}", resourceName, mirror);
// Get the bitmap.
Bitmap bitmap;
lock (typeof(ResourceHelper))
{
// Initialize the bitmap cache if necessary
if (bitmapCache == null)
bitmapCache = new Dictionary<string, Bitmap>();
// Locate the resource name in the bitmap cache. If found, return it.
if (!bitmapCache.TryGetValue(key, out bitmap))
{
// Get a stream on the resource. If this fails, null will be returned. This means
// that we could not find the resource in the assembly.
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
if (stream != null)
{
// Load the bitmap.
// Bitmaps require their underlying streams to remain open
// for as long as their bitmaps are in use. We don't want to hold open the
// resource stream though, so copy it to a memory stream.
bitmap = new Bitmap(StreamHelper.CopyToMemoryStream(stream));
if (BidiHelper.IsRightToLeft && mirror)
{
Bitmap temp = BidiHelper.Mirror(bitmap);
bitmap.Dispose();
bitmap = temp;
}
}
// Cache the bitmap.
bitmapCache.Add(key, bitmap);
}
}
// Done!
return bitmap;
}
}
/// <summary>
/// Loads a Bitmap embedded in Images.resx.
/// </summary>
/// <param name="resource">The name of the Bitmap to load (i.e. "InsertPhotoAlbum_SmallImage").</param>
public static Bitmap LoadBitmap(string resource)
{
// Get the bitmap.
Bitmap bitmap;
lock (typeof(ResourceHelper))
{
// Initialize the bitmap cache if necessary
if (bitmapCache == null)
bitmapCache = new Dictionary<string, Bitmap>();
// Locate the resource name in the bitmap cache. If found, return it.
if (!bitmapCache.TryGetValue(resource, out bitmap))
{
bitmap = Images.ResourceManager.GetObject(resource) as Bitmap;
bitmapCache.Add(resource, bitmap);
}
// Done!
return bitmap;
}
}
/// <summary>
/// Loads an icon from an assembly resource.
/// </summary>
/// <param name="path">icon path.</param>
/// <returns>Icon, or null if the icon could not be found.</returns>
public static Icon LoadAssemblyResourceIcon(string path)
{
return LoadAssemblyResourceIcon(Assembly.GetCallingAssembly(), path);
}
/// <summary>
/// Loads an icon from an assembly resource.
/// </summary>
/// <param name="assembly">The assembly that contains the resource.</param>
/// <param name="path">icon path.</param>
/// <returns>Icon, or null if the icon could not be found.</returns>
public static Icon LoadAssemblyResourceIcon(Assembly assembly, string path)
{
return LoadAssemblyResourceIcon(assembly, path, 0, 0);
}
/// <summary>
/// Loads an icon from an assembly resource.
/// </summary>
/// <param name="path">icon path.</param>
/// <returns>Icon, or null if the icon could not be found.</returns>
public static Icon LoadAssemblyResourceIcon(string path, int desiredWidth, int desiredHeight)
{
return LoadAssemblyResourceIcon(Assembly.GetCallingAssembly(), path, desiredWidth, desiredHeight);
}
/// <summary>
/// Loads an icon from an assembly resource.
/// </summary>
/// <param name="path">icon path.</param>
/// <returns>Icon, or null if the icon could not be found.</returns>
private static Icon LoadAssemblyResourceIcon(Assembly callingAssembly, string path, int desiredWidth, int desiredHeight)
{
// Get the calling assembly and its name.
AssemblyName callingAssemblyName = callingAssembly.GetName();
// Format the schema resource name that we will load from the calling assembly.
string resourceName = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", callingAssemblyName.Name, path);
string resourceNameKey = String.Format(CultureInfo.InvariantCulture, "{0}/{1}x{2}", resourceName, desiredWidth, desiredHeight);
// Get the icon
Icon icon;
lock (typeof(ResourceHelper))
{
// Initialize the icon cache if necessary
if (iconCache == null)
iconCache = new Hashtable();
// Get a stream on the resource. If this fails, null will be returned. This means
// If we have the icon cached, return it.
icon = (Icon)iconCache[resourceNameKey];
if (icon != null)
return icon;
// that we could not find the resource in the caller's assembly. Throw an exception.
using (Stream stream = callingAssembly.GetManifestResourceStream(resourceName))
{
if (stream == null)
return null;
// Load the icon
// Unlike Bitmaps, icons don't need their streams to remain open
if (desiredWidth > 0 && desiredHeight > 0)
icon = new Icon(stream, desiredWidth, desiredHeight);
else
icon = new Icon(stream);
}
// Cache the icon
iconCache[resourceNameKey] = icon;
}
// Done!
return icon;
}
/// <summary>
/// Loads a raw stream from an assembly resource.
/// </summary>
/// <param name="resourcePath">Resource path.</param>
/// <returns>Stream to the specified resource, or null if the resource could not be found.</returns>
public static Stream LoadAssemblyResourceStream(string resourcePath)
{
Assembly assembly = Assembly.GetCallingAssembly();
string resourceName = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", assembly.GetName().Name, resourcePath);
return assembly.GetManifestResourceStream(resourceName);
}
/// <summary>
/// Saves an assembly resource to a file
/// </summary>
/// <param name="resourcePath">path to resource within assembly</param>
/// <param name="filePath">full path to file to save</param>
public static void SaveAssemblyResourceToFile(string resourcePath, string targetFilePath)
{
// Format the schema resource name that we will load from the assembly.
Assembly assembly = Assembly.GetCallingAssembly();
string resourceName = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", assembly.GetName().Name, resourcePath);
// transfer the resource into the file stream
using (Stream fileStream = new FileStream(targetFilePath, FileMode.Create))
{
// Load stream and transfer it to the target stream
using (Stream resourceStream = assembly.GetManifestResourceStream(resourceName))
{
StreamHelper.Transfer(resourceStream, fileStream);
}
}
}
/// <summary>
/// Saves an assembly resource to a stream
/// </summary>
/// <param name="resourcePath">path to resource within assembly</param>
/// <param name="targetStream">target stream to save to</param>
public static void SaveAssemblyResourceToStream(string resourcePath, Stream targetStream)
{
// Format the schema resource name that we will load from the assembly.
Assembly assembly = Assembly.GetCallingAssembly();
string resourceName = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", assembly.GetName().Name, resourcePath);
// Load stream and transfer it to the target stream
using (Stream resourceStream = assembly.GetManifestResourceStream(resourceName))
{
StreamHelper.Transfer(resourceStream, targetStream);
}
}
}
}
| |
/*****************************************************************
* MPAPI - Message Passing API
* A framework for writing parallel and distributed applications
*
* Author : Frank Thomsen
* Web : http://sector0.dk
* Contact : mpapi@sector0.dk
* License : New BSD licence
*
* Copyright (c) 2008, Frank Thomsen
*
* Feel free to contact me with bugs and ideas.
*****************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Reflection;
using System.Threading;
namespace MPAPI
{
public enum LogLevel
{
None = 0,
Info = 1,
Warning = 2,
Error = 4,
InfoWarningError = 7, //Info, Warning and Error
Debug = 8,
DebugCore = 16,
All = 31
}
public enum LogType
{
None = 0,
Console = 1,
File = 2,
Both = 3
}
public sealed class Log
{
private static object _logTypeLock = new object();
private static object _logLevelLock = new object();
private static object _fsLock = new object();
private static object _writerLock = new object();
private static LogType _logType = LogType.Console;
private static LogLevel _logLevel = LogLevel.InfoWarningError;
private static FileStream _fs;
private static StreamWriter _writer;
private Log()
{
OpenLogFile();
}
public static LogType LogType
{
get
{
lock (_logTypeLock)
{
return _logType;
}
}
set
{
lock (_logTypeLock)
{
_logType = value;
if ((_logType & LogType.File) != LogType.File)
CloseLogFile();
else
OpenLogFile();
}
}
}
public static LogLevel LogLevel
{
get
{
lock (_logLevelLock)
{
return _logLevel;
}
}
set
{
lock (_logLevelLock)
{
_logLevel = value;
}
}
}
public static void Info(string formattedMessage, params object[] arguments)
{
lock (_logLevelLock)
{
if ((_logLevel & LogLevel.Info) == LogLevel.Info)
LogMessage("Info", formattedMessage, arguments);
}
}
public static void Warning(string formattedMessage, params object[] arguments)
{
lock (_logLevelLock)
{
if ((_logLevel & LogLevel.Warning) == LogLevel.Warning)
LogMessage("Warning", formattedMessage, arguments);
}
}
public static void Error(string formattedMessage, params object[] arguments)
{
lock (_logLevelLock)
{
if ((_logLevel & LogLevel.Error) == LogLevel.Error)
LogMessage("Error", formattedMessage, arguments);
}
}
public static void Debug(string formattedMessage, params object[] arguments)
{
lock (_logLevelLock)
{
if ((_logLevel & LogLevel.Debug) == LogLevel.Debug)
LogMessage("Debug", formattedMessage, arguments);
}
}
//internal static void DebugCore(string formattedMessage, params object[] arguments)
//{
// lock (_logLevelLock)
// {
// if ((_logLevel & LogLevel.DebugCore) == LogLevel.DebugCore)
// LogMessage("DebugCore", formattedMessage, arguments);
// }
//}
private static void LogMessage(string header, string formattedMessage, params object[] arguments)
{
DateTime now = DateTime.Now;
string msg = string.Format("{0}:{1} | {2} | {3}", now.ToString("HH:mm:ss"), now.Millisecond.ToString().PadLeft(3,'0'), header.PadRight(9,' '), string.Format(formattedMessage, arguments));
lock (_logTypeLock)
{
if ((_logType & LogType.Console) == LogType.Console)
Console.WriteLine(msg);
if ((_logType & LogType.File) == LogType.File)
{
lock (_writerLock)
{
_writer.WriteLine(msg);
_writer.Flush();
}
}
}
}
private static void CloseLogFile()
{
if (_writer != null)
{
lock (_writerLock)
{
_writer.Flush();
_writer.Close();
_writer = null;
}
}
if (_fs != null)
{
lock (_fsLock)
{
_fs.Close();
_fs = null;
}
}
}
private static void OpenLogFile()
{
lock (_logTypeLock)
{
if ((_logType & LogType.File) == LogType.File)
{
string logFileName = Path.GetFileName(Assembly.GetEntryAssembly().CodeBase) + ".log";
string executingDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().CodeBase);
executingDir = executingDir.Replace(@"file:\", "");
lock (_fsLock)
{
_fs = File.Open(Path.Combine(executingDir, logFileName), FileMode.Append, FileAccess.Write);
}
lock (_writerLock)
{
_writer = new StreamWriter(_fs);
}
}
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Cluster;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Unmanaged;
using BinaryReader = Apache.Ignite.Core.Impl.Binary.BinaryReader;
/// <summary>
/// Native utility methods.
/// </summary>
internal static class IgniteUtils
{
/** Environment variable: JAVA_HOME. */
private const string EnvJavaHome = "JAVA_HOME";
/** Lookup paths. */
private static readonly string[] JvmDllLookupPaths = {@"jre\bin\server", @"jre\bin\default"};
/** File: jvm.dll. */
private const string FileJvmDll = "jvm.dll";
/** File: Ignite.Common.dll. */
internal const string FileIgniteJniDll = "ignite.common.dll";
/** Prefix for temp directory names. */
private const string DirIgniteTmp = "Ignite_";
/** Loaded. */
private static bool _loaded;
/** Thread-local random. */
[ThreadStatic]
private static Random _rnd;
/// <summary>
/// Initializes the <see cref="IgniteUtils"/> class.
/// </summary>
static IgniteUtils()
{
TryCleanTempDirectories();
}
/// <summary>
/// Gets thread local random.
/// </summary>
/// <returns>Thread local random.</returns>
private static Random ThreadLocalRandom()
{
return _rnd ?? (_rnd = new Random());
}
/// <summary>
/// Returns shuffled list copy.
/// </summary>
/// <returns>Shuffled list copy.</returns>
public static IList<T> Shuffle<T>(IList<T> list)
{
int cnt = list.Count;
if (cnt > 1) {
List<T> res = new List<T>(list);
Random rnd = ThreadLocalRandom();
while (cnt > 1)
{
cnt--;
int idx = rnd.Next(cnt + 1);
T val = res[idx];
res[idx] = res[cnt];
res[cnt] = val;
}
return res;
}
return list;
}
/// <summary>
/// Load JVM DLL if needed.
/// </summary>
/// <param name="configJvmDllPath">JVM DLL path from config.</param>
public static void LoadDlls(string configJvmDllPath)
{
if (_loaded) return;
// 1. Load JNI dll.
LoadJvmDll(configJvmDllPath);
// 2. Load GG JNI dll.
UnmanagedUtils.Initialize();
_loaded = true;
}
/// <summary>
/// Create new instance of specified class.
/// </summary>
/// <param name="typeName">Class name</param>
/// <returns>New Instance.</returns>
public static T CreateInstance<T>(string typeName)
{
IgniteArgumentCheck.NotNullOrEmpty(typeName, "typeName");
var type = new TypeResolver().ResolveType(typeName);
if (type == null)
throw new IgniteException("Failed to create class instance [className=" + typeName + ']');
return (T) Activator.CreateInstance(type);
}
/// <summary>
/// Set properties on the object.
/// </summary>
/// <param name="target">Target object.</param>
/// <param name="props">Properties.</param>
public static void SetProperties(object target, IEnumerable<KeyValuePair<string, object>> props)
{
if (props == null)
return;
IgniteArgumentCheck.NotNull(target, "target");
Type typ = target.GetType();
foreach (KeyValuePair<string, object> prop in props)
{
PropertyInfo prop0 = typ.GetProperty(prop.Key,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (prop0 == null)
throw new IgniteException("Property is not found [type=" + typ.Name +
", property=" + prop.Key + ']');
prop0.SetValue(target, prop.Value, null);
}
}
/// <summary>
/// Loads the JVM DLL.
/// </summary>
private static void LoadJvmDll(string configJvmDllPath)
{
var messages = new List<string>();
foreach (var dllPath in GetJvmDllPaths(configJvmDllPath))
{
var errCode = LoadDll(dllPath.Value, FileJvmDll);
if (errCode == 0)
return;
messages.Add(string.Format(CultureInfo.InvariantCulture, "[option={0}, path={1}, errorCode={2}]",
dllPath.Key, dllPath.Value, errCode));
if (dllPath.Value == configJvmDllPath)
break; // if configJvmDllPath is specified and is invalid - do not try other options
}
if (!messages.Any()) // not loaded and no messages - everything was null
messages.Add(string.Format(CultureInfo.InvariantCulture,
"Please specify IgniteConfiguration.JvmDllPath or {0}.", EnvJavaHome));
if (messages.Count == 1)
throw new IgniteException(string.Format(CultureInfo.InvariantCulture, "Failed to load {0} ({1})",
FileJvmDll, messages[0]));
var combinedMessage =
messages.Aggregate((x, y) => string.Format(CultureInfo.InvariantCulture, "{0}\n{1}", x, y));
throw new IgniteException(string.Format(CultureInfo.InvariantCulture, "Failed to load {0}:\n{1}",
FileJvmDll, combinedMessage));
}
/// <summary>
/// Try loading DLLs first using file path, then using it's simple name.
/// </summary>
/// <param name="filePath"></param>
/// <param name="simpleName"></param>
/// <returns>Zero in case of success, error code in case of failure.</returns>
private static int LoadDll(string filePath, string simpleName)
{
int res = 0;
IntPtr ptr;
if (filePath != null)
{
ptr = NativeMethods.LoadLibrary(filePath);
if (ptr == IntPtr.Zero)
res = Marshal.GetLastWin32Error();
else
return res;
}
// Failed to load using file path, fallback to simple name.
ptr = NativeMethods.LoadLibrary(simpleName);
if (ptr == IntPtr.Zero)
{
// Preserve the first error code, if any.
if (res == 0)
res = Marshal.GetLastWin32Error();
}
else
res = 0;
return res;
}
/// <summary>
/// Gets the JVM DLL paths in order of lookup priority.
/// </summary>
private static IEnumerable<KeyValuePair<string, string>> GetJvmDllPaths(string configJvmDllPath)
{
if (!string.IsNullOrEmpty(configJvmDllPath))
yield return new KeyValuePair<string, string>("IgniteConfiguration.JvmDllPath", configJvmDllPath);
var javaHomeDir = Environment.GetEnvironmentVariable(EnvJavaHome);
if (!string.IsNullOrEmpty(javaHomeDir))
foreach (var path in JvmDllLookupPaths)
yield return
new KeyValuePair<string, string>(EnvJavaHome, Path.Combine(javaHomeDir, path, FileJvmDll));
}
/// <summary>
/// Unpacks an embedded resource into a temporary folder and returns the full path of resulting file.
/// </summary>
/// <param name="resourceName">Resource name.</param>
/// <returns>Path to a temp file with an unpacked resource.</returns>
public static string UnpackEmbeddedResource(string resourceName)
{
var dllRes = Assembly.GetExecutingAssembly().GetManifestResourceNames()
.Single(x => x.EndsWith(resourceName, StringComparison.OrdinalIgnoreCase));
return WriteResourceToTempFile(dllRes, resourceName);
}
/// <summary>
/// Writes the resource to temporary file.
/// </summary>
/// <param name="resource">The resource.</param>
/// <param name="name">File name prefix</param>
/// <returns>Path to the resulting temp file.</returns>
private static string WriteResourceToTempFile(string resource, string name)
{
// Dll file name should not be changed, so we create a temp folder with random name instead.
var file = Path.Combine(GetTempDirectoryName(), name);
using (var src = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource))
using (var dest = File.OpenWrite(file))
{
// ReSharper disable once PossibleNullReferenceException
src.CopyTo(dest);
return file;
}
}
/// <summary>
/// Tries to clean temporary directories created with <see cref="GetTempDirectoryName"/>.
/// </summary>
private static void TryCleanTempDirectories()
{
foreach (var dir in Directory.GetDirectories(Path.GetTempPath(), DirIgniteTmp + "*"))
{
try
{
Directory.Delete(dir, true);
}
catch (IOException)
{
// Expected
}
catch (UnauthorizedAccessException)
{
// Expected
}
}
}
/// <summary>
/// Creates a uniquely named, empty temporary directory on disk and returns the full path of that directory.
/// </summary>
/// <returns>The full path of the temporary directory.</returns>
private static string GetTempDirectoryName()
{
while (true)
{
var dir = Path.Combine(Path.GetTempPath(), DirIgniteTmp + Path.GetRandomFileName());
try
{
return Directory.CreateDirectory(dir).FullName;
}
catch (IOException)
{
// Expected
}
catch (UnauthorizedAccessException)
{
// Expected
}
}
}
/// <summary>
/// Convert unmanaged char array to string.
/// </summary>
/// <param name="chars">Char array.</param>
/// <param name="charsLen">Char array length.</param>
/// <returns></returns>
public static unsafe string Utf8UnmanagedToString(sbyte* chars, int charsLen)
{
IntPtr ptr = new IntPtr(chars);
if (ptr == IntPtr.Zero)
return null;
byte[] arr = new byte[charsLen];
Marshal.Copy(ptr, arr, 0, arr.Length);
return Encoding.UTF8.GetString(arr);
}
/// <summary>
/// Convert string to unmanaged byte array.
/// </summary>
/// <param name="str">String.</param>
/// <returns>Unmanaged byte array.</returns>
public static unsafe sbyte* StringToUtf8Unmanaged(string str)
{
var ptr = IntPtr.Zero;
if (str != null)
{
byte[] strBytes = Encoding.UTF8.GetBytes(str);
ptr = Marshal.AllocHGlobal(strBytes.Length + 1);
Marshal.Copy(strBytes, 0, ptr, strBytes.Length);
*((byte*)ptr.ToPointer() + strBytes.Length) = 0; // NULL-terminator.
}
return (sbyte*)ptr.ToPointer();
}
/// <summary>
/// Reads node collection from stream.
/// </summary>
/// <param name="reader">Reader.</param>
/// <param name="pred">The predicate.</param>
/// <returns> Nodes list or null. </returns>
public static List<IClusterNode> ReadNodes(IBinaryRawReader reader, Func<ClusterNodeImpl, bool> pred = null)
{
var cnt = reader.ReadInt();
if (cnt < 0)
return null;
var res = new List<IClusterNode>(cnt);
var ignite = ((BinaryReader)reader).Marshaller.Ignite;
if (pred == null)
{
for (var i = 0; i < cnt; i++)
res.Add(ignite.GetNode(reader.ReadGuid()));
}
else
{
for (var i = 0; i < cnt; i++)
{
var node = ignite.GetNode(reader.ReadGuid());
if (pred(node))
res.Add(node);
}
}
return res;
}
}
}
| |
// 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 Gallio.Common;
using Gallio.Common.Diagnostics;
using Gallio.Common.Markup;
using Gallio.Framework;
using Gallio.Model;
using Gallio.Common.Reflection;
using Gallio.Framework.Pattern;
namespace MbUnit.Framework
{
/// <summary>
/// Declares that the associated test's <see cref="TestOutcome"/> should be interpreted as having completed
/// with a specified <see cref="TestOutcome"/> if a specified exception is thrown during the test.
/// </summary>
/// <remarks>
/// <para>
/// The expected contents of the detected exception's <see cref="Exception.Message"/> may optionally be specified.
/// </para>
/// <para>
/// The <see cref="TestOutcome"/> that is returned when a matching exception is thrown may optionally be specified.
/// By default, the test will be treated as <see cref="TestOutcome.Error"/> if a matching exception is thrown.
/// </para>
/// </remarks>
/// <example>
/// <para>
/// This C# example shows a test with a <see cref="CatchExceptionAttribute"/> that will
/// result in a <see cref="TestOutcome.Error"/> (the default <see cref="Outcome"/>)
/// if the test throws a <see cref="NotSupportedException"/>.
/// <code><![CDATA[
/// /// <summary>
/// /// This test will have an outcome of <see cref="TestOutcome.Error"/>.
/// /// </summary>
/// [Test]
/// [CatchException(typeof(NotSupportedException))]
/// public void CatchExceptionExample1()
/// {
/// throw new NotSupportedException();
/// }
/// ]]></code>
/// </para>
/// <para>
/// This C# example shows a test with a <see cref="CatchExceptionAttribute"/> that will
/// result in a <see cref="TestOutcome.Pending"/>
/// if the test throws a <see cref="NotImplementedException"/>.
/// <code><![CDATA[
/// /// <summary>
/// /// This test will have an outcome of <see cref="TestOutcome.Pending"/>.
/// /// </summary>
/// [Test]
/// [CatchException(typeof(NotImplementedException), StandardOutcome = "TestOutcome.Pending")]
/// public void CatchExceptionExample2()
/// {
/// throw new NotImplementedException();
/// }
/// ]]></code>
/// </para>
/// <para>
/// This C# example shows a test with a <see cref="CatchExceptionAttribute"/> that will
/// result in a <see cref="TestOutcome.Passed"/>
/// if the test throws a <see cref="NotImplementedException"/>
/// or if the test doesn't throw any exceptions.
/// <code><![CDATA[
/// /// <summary>
/// /// This test will have an outcome of <see cref="TestOutcome.Passed"/>
/// /// whether the test throws a <see cref="NotImplementedException"/> or throws no exception.
/// /// </summary>
/// [Test]
/// [CatchException(typeof(NotImplementedException), StandardOutcome = "TestOutcome.Passed")]
/// public void CatchExceptionExample3()
/// {
/// bool randomBool = new Random().Next() % 2 == 0;
/// if (randomBool)
/// throw new NotImplementedException();
/// }
/// ]]></code>
/// </para>
/// <para>
/// This C# example shows a test with multiple <see cref="CatchExceptionAttribute"/>s that will:
/// result in a <see cref="TestOutcome"/> of <see cref="TestOutcome.Pending"/>
/// if the test throws a <see cref="NotImplementedException"/>;
/// result in a <see cref="TestOutcome"/> with a
/// <see cref="TestOutcome.Status"/> of <see cref="TestStatus.Skipped"/> and a
/// <see cref="TestOutcome.Category"/> of <c>"notsupported"</c>
/// if the test throws a <see cref="NotSupportedException"/>;
/// result in a <see cref="TestOutcome"/> with a
/// <see cref="TestOutcome.Status"/> of <see cref="TestStatus.Inconclusive"/> and a
/// <see cref="TestOutcome.Category"/> of <c>"deadlock"</c>
/// if the test throws a <see cref="TimeoutException"/>
/// with a <see cref="Exception.Message"/> that contains the substring <c>"deadlock"</c>;
/// result in a <see cref="TestOutcome"/> with a
/// <see cref="TestOutcome.Status"/> of <see cref="TestStatus.Inconclusive"/> and a
/// <see cref="TestOutcome.Category"/> of <c>"timeout"</c>
/// if the test throws a <see cref="TimeoutException"/>
/// with a <see cref="Exception.Message"/> that contains the substring <c>"server not responding"</c>;
/// result in a <see cref="TestOutcome"/> of <see cref="TestOutcome.Failed"/>
/// if the test throws any other <see cref="Exception"/> not listed above;
/// result in a <see cref="TestOutcome"/> of <see cref="TestOutcome.Passed"/>
/// if the test does not throw any <see cref="Exception"/>s.
/// <code><![CDATA[
/// /// <remarks>
/// /// This test can have any of several outcomes depending on what type of exception is thrown (if any) during test execution.
/// /// </remarks>
/// [Test]
/// [CatchException(typeof(NotSupportedException), OutcomeStatus = TestStatus.Skipped, OutcomeCategory = "notsupported")]
/// [CatchException(typeof(NotImplementedException), StandardOutcome = "TestOutcome.Pending")]
/// [CatchException(typeof(TimeoutException), ExceptionMessage = "deadlock", OutcomeStatus = TestStatus.Inconclusive, OutcomeCategory = "deadlock", Order = 2)]
/// [CatchException(typeof(TimeoutException), ExceptionMessage = "server not responding", OutcomeStatus = TestStatus.Inconclusive, OutcomeCategory = "timeout", Order = 3)]
/// public void CatchExceptionExample4()
/// {
/// //throw new NotSupportedException(); //outcome would be: new TestOutcome(TestStatus.Skipped, "notsupported")
/// throw new NotImplementedException(); //outcome would be: TestOutcome.Pending
/// //throw new TimeoutException("A deadlock occurred."); //outcome would be: new TestOutcome(TestStatus.Inconclusive, "deadlock")
/// //throw new TimeoutException("The server is not responding."); //outcome would be: new TestOutcome(TestStatus.Inconclusive, "timeout")
/// //throw new TimeoutException("Transaction timeout."); //outcome would be: TestOutcome.Failed
/// //throw new TimeoutException(); //outcome would be: TestOutcome.Failed
/// //throw new ArithmeticException(); //outcome would be: TestOutcome.Failed
/// //return; //outcome would be: TestOutcome.Passed
/// }
/// ]]></code>
/// </para>
/// </example>
[AttributeUsage(PatternAttributeTargets.Test, AllowMultiple = true, Inherited = true)]
public class CatchExceptionAttribute : TestDecoratorPatternAttribute
{
private readonly Type exceptionType;
private TestStatus outcomeStatus = TestOutcome.Error.Status;
private string outcomeCategory = TestOutcome.Error.Category;
//TODO: Add the ability to specify how the ExceptionMessage is compared: Contains (the default)ExactMatch, RegEx, etc.
//private Enum exceptionMessageComparisonMethod = StringComparisonMethod.Contains;
/// <summary>
/// Declares that the associated test is expected to throw an <see cref="Exception"/> of
/// a particular type.
/// </summary>
/// <param name="exceptionType">The expected exception type.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="exceptionType"/> is null.</exception>
/// <exception cref="ArgumentException">Thrown if <paramref name="exceptionType"/> is not the <see cref="Type"/> of an <see cref="Exception"/>.</exception>
public CatchExceptionAttribute(Type exceptionType)
: this(exceptionType, TestOutcome.Error.Status, TestOutcome.Error.Category)
{
}
/// <summary>
/// Declares that the associated test is expected to throw an <see cref="Exception"/> of
/// a particular type, and the <see cref="TestStatus"/> of the <see cref="TestOutcome"/>
/// that should be used if/when it does.
/// </summary>
/// <param name="exceptionType">The expected exception type.</param>
/// <param name="outcomeStatus">
/// The <see cref="TestStatus"/> that will be used to construct the
/// <see cref="TestOutcome"/> if a detected exception is handled.
/// </param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="exceptionType"/> is null.</exception>
/// <exception cref="ArgumentException">Thrown if <paramref name="exceptionType"/> is not the <see cref="Type"/> of an <see cref="Exception"/>.</exception>
public CatchExceptionAttribute(Type exceptionType, TestStatus outcomeStatus)
: this(exceptionType, outcomeStatus, TestOutcome.Error.Category)
{
}
/// <summary>
/// Declares that the associated test is expected to throw an <see cref="Exception"/> of
/// a particular type, and the <see cref="TestOutcome"/>
/// that should be used if/when it does.
/// </summary>
/// <param name="exceptionType">The expected exception type.</param>
/// <param name="outcomeStatus">
/// The <see cref="TestStatus"/> that will be used to construct the
/// <see cref="TestOutcome"/> if a detected exception is handled.
/// </param>
/// <param name="outcomeCategory">
/// The <see cref="TestOutcome.Category"/> that will be used to construct the
/// <see cref="TestOutcome"/> if a detected exception is handled.
/// </param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="exceptionType"/> is null.</exception>
/// <exception cref="ArgumentException">Thrown if <paramref name="exceptionType"/> is not the <see cref="Type"/> of an <see cref="Exception"/>.</exception>
public CatchExceptionAttribute(Type exceptionType, TestStatus outcomeStatus, string outcomeCategory)
{
if (exceptionType == null)
throw new ArgumentNullException("exceptionType");
if (!typeof(Exception).IsAssignableFrom(exceptionType))
throw new ArgumentException(string.Format("Type '{0}' is not an Exception Type.", exceptionType.FullName), "exceptionType");
this.exceptionType = exceptionType;
this.outcomeStatus = outcomeStatus;
this.outcomeCategory = outcomeCategory;
}
/// <summary>
/// Gets the type of <see cref="Exception"/> that is handled.
/// </summary>
public Type ExceptionType
{
get { return exceptionType; }
}
/// <summary>
/// Gets or sets the substring that must be contained in the detected <see cref="Exception"/>'s <see cref="Exception.Message"/> for it to be handled,
/// or <c>null</c> if none specified.
/// </summary>
public string ExceptionMessage
{
get;
set;
}
/// <summary>
/// Gets or sets the <see cref="TestOutcome.Category"/> that will be used to construct the
/// <see cref="TestOutcome"/> when a detected exception is handled.
/// </summary>
/// <see cref="Outcome"/>
/// <see cref="OutcomeCategory"/>
public TestStatus OutcomeStatus
{
get { return outcomeStatus; }
set { outcomeStatus = value; }
}
/// <summary>
/// Gets or sets the <see cref="TestOutcome.Category"/> that will be used to construct the
/// <see cref="TestOutcome"/> if a detected exception is handled.
/// </summary>
/// <see cref="Outcome"/>
/// <see cref="OutcomeStatus"/>
public string OutcomeCategory
{
get { return outcomeCategory; }
set { outcomeCategory = value; }
}
/// <summary>
/// Gets or sets the <see cref="TestOutcome"/> that will be used if a matching exception is thrown.
/// Defaults to <see cref="TestOutcome.Error"/>.
/// </summary>
public TestOutcome Outcome
{
get { return new TestOutcome(outcomeStatus, outcomeCategory); }
set
{
OutcomeStatus = value.Status;
OutcomeCategory = value.Category;
}
}
/// <summary>
/// This is a <see cref="string"/>-typed alias of the <see cref="Outcome"/> property.
/// </summary>
public string StandardOutcome
{
get { return Outcome.DisplayName; }
set { Outcome = TestOutcome.GetStandardOutcome(value); }
}
/// <inheritdoc />
public override string ToString()
{
return string.Format("CatchExceptionAttribute(ExceptionType={0}{1}, OutcomeStatus=TestStatus.{2}{3}{4})",
ExceptionType.FullName,
((Order == 0) ? "" : string.Format(", Order={0}", Order)),
OutcomeStatus,
((OutcomeCategory == null) ? "" : string.Format(", OutcomeCategory=\"{0}\"", OutcomeCategory.Replace("\"", "\\\""))),
((ExceptionMessage == null) ? "" : string.Format(", ExceptionMessage=\"{0}\"", ExceptionMessage.Replace("\"", "\\\"")))
);
}
/// <inheritdoc />
protected override void DecorateTest(IPatternScope scope, ICodeElementInfo codeElement)
{
ActionChain<PatternTestInstanceState> executeTestInstanceChain = scope.TestBuilder.TestInstanceActions.ExecuteTestInstanceChain;
executeTestInstanceChain.Around((state, inner) => ExecuteTestInstanceChainCatchExceptionDecorator(inner, state));
}
/// <summary>
/// This method does the actual work of catching and handling (or not) <see cref="Exception"/>s.
/// </summary>
private void ExecuteTestInstanceChainCatchExceptionDecorator(Action<PatternTestInstanceState> inner, PatternTestInstanceState state)
{
try
{
inner(state);
OnInnerActionCompleted(null);
}
catch (TestException ex)
{
//If the exception is a TestException it must be rethrown
//because it represents the (non-Passed) TestOutcome of the inner action
//TODO: Review: Should we call ExceptionUtils.RethrowWithNoStackTraceLoss(ex) here?
ExceptionUtils.RethrowWithNoStackTraceLoss(ex);
throw;
}
catch (Exception ex)
{
//NOTE: Ideally, the whole catch block would be implemented inside of <see cref="OnInnerActionCompleted"/>.
//However, that is not possible for technical reasons.
//See the Implementation Note in the remarks section of the <see cref="OnInnerActionCompleted"/>
//documentation for details.
if (OnInnerActionCompleted(ex))
{
return;
}
else
{
//TODO: Review: Should we call ExceptionUtils.RethrowWithNoStackTraceLoss(ex) here?
ExceptionUtils.RethrowWithNoStackTraceLoss(ex);
throw;
}
}
}
/// <summary>
/// Performs the work of analysing (and either handling or rethrowing) a detected exception.
/// </summary>
/// <remarks>
/// <para>
/// This method could be overridden by inheritors to extend or modify the behavior
/// associated with detecting <see cref="Exception"/>s.
/// <para>
/// Theoretically, the <see cref="ExpectedExceptionAttribute"/> could be implemented as a subclass of
/// <see cref="CatchExceptionAttribute"/> that overrides the behavior of
/// <see cref="OnInnerActionCompleted(System.Exception,bool)"/> to always return <c>true</c>.
/// </para>
/// </para>
/// <para>
/// Implementation Note: Normally this method would have a return type of <c>void</c>.
/// However, since it is not possible rethrow a caught exception using "throw;"
/// except from directly within the <c>catch</c> block
/// (i.e. the same method the <c>catch</c> block is declared in),
/// it was necessary to use the returned value to indicate to the calling method whether or not the
/// detected <see cref="Exception"/> should be re-thrown.
/// </para>
/// </remarks>
/// <param name="ex">The detected <see cref="Exception"/>.</param>
/// <param name="isExpected">Indicates whether <paramref name="ex"/> matches the catch-criteria of the instance.</param>
/// <returns>
/// <c>true</c> to indicate that the <see cref="TestOutcome"/> should be <see cref="TestOutcome.Passed"/>
/// (e.g. when <paramref name="isExpected"/> is <c>true</c>).
/// Else <c>false</c> to indicate that the detected exception (if any) was not handled
/// and should be rethrown (if needed).
/// </returns>
/// <exception cref="SilentTestException">
/// Propogated when thrown by <see cref="HandleExpectedException"/> to indicate that the detected exception was handled,
/// and that the <see cref="TestOutcome"/> should be something other than <see cref="TestOutcome.Passed"/>.
/// </exception>
protected virtual bool OnInnerActionCompleted(Exception ex, bool isExpected)
{
if (isExpected)
{
HandleExpectedException(ex);
//Returning <c>true</c> signifies a <see cref="TestOutcome.Passed"/> outcome.
//Any other outcome will be "returned" as a <see cref="TestException"/> thrown by <see cref="HandleExpectedException"/>
return true;
}
else if (ex == null)
{
//We also want to treat a successful inner action (i.e. one that didn't throw an exception) as Passed
return true;
}
return false;
}
private bool OnInnerActionCompleted(Exception ex)
{
return OnInnerActionCompleted(ex, IsExpectedException(ex));
}
/// <summary>
/// Indicates whether a detected <see cref="Exception"/> (or the lack of one) is expected,
/// and should be caught and handled (by <see cref="HandleExpectedException"/>)
/// based upon the instance's matching properties.
/// </summary>
/// <seealso cref="ExceptionType"/>
/// <seealso cref="ExceptionMessage"/>
/// <seealso cref="OnInnerActionCompleted(System.Exception,bool)"/>
protected bool IsExpectedException(Exception ex)
{
//NOTE: Much of this logic was adapted from the ExpectedException logic in <see cref="TestAttribute.Execute"/>
return (ex != null)
&& (ReflectionUtils.IsAssignableFrom(exceptionType.FullName, ex.GetType())
&& (ExceptionMessage == null || ex.Message.Contains(ExceptionMessage)));
}
/// <summary>
/// Performs the work of handling a detected exception that matches the catching-criteria.
/// </summary>
/// <remarks>
/// <para>
/// This method could be overridden by inheritors to extend or modify the behavior
/// associated with handling <see cref="Exception"/>s that match the configured catching-criteria.
/// </para>
/// </remarks>
/// <param name="ex">The detected <see cref="Exception"/> that matches the catching-criteria.</param>
/// <exception cref="SilentTestException">
/// Thrown to return a non-<see cref="TestOutcome.Passed"/> outcome back up the call stack.
/// </exception>
protected virtual void HandleExpectedException(Exception ex)
{
if (ex == null)
{
//throw new ArgumentNullException("ex");
return;
}
string testExceptionMessage = string.Format("An exception was handled by a {0}.", this.ToString());
string exceptionSummary = string.Format("{0}, {1}.",
ex.GetType().FullName,
((ex.Message == null) ? "null" : string.Format("\"{0}\"", ex.Message.Replace("\"", "\\\""))));
TestLog.WriteException(ex, string.Format("Caught exception. {0}", testExceptionMessage));
//throw new SilentTestException(Outcome,
// string.Format("{0} Exception: {1}", testExceptionMessage, exceptionSummary));
TestOutcome outcome = Outcome;
bool outcomeRequiresTestException = (outcome != TestOutcome.Passed);
if (outcomeRequiresTestException)
{
throw new SilentTestException(outcome,
string.Format("{0} Exception: {1}", testExceptionMessage, exceptionSummary));
}
else
{
//simply return without throwing an exception to signify a "passed" outcome
return;
}
}
}
}
| |
namespace XenAdmin.Controls.Wlb
{
partial class WlbReportView
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region 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()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(WlbReportView));
this.labelHostCombo = new System.Windows.Forms.Label();
this.hostComboBox = new System.Windows.Forms.ComboBox();
this.btnRunReport = new System.Windows.Forms.Button();
this.btnLaterReport = new System.Windows.Forms.Button();
this.labelEndDate = new System.Windows.Forms.Label();
this.EndDatePicker = new System.Windows.Forms.DateTimePicker();
this.labelStartDate = new System.Windows.Forms.Label();
this.StartDatePicker = new System.Windows.Forms.DateTimePicker();
this.reportViewer1 = new Microsoft.Reporting.WinForms.ReportViewer();
this.btnSubscribe = new System.Windows.Forms.Button();
this.btnClose = new System.Windows.Forms.Button();
this.comboBoxView = new System.Windows.Forms.ComboBox();
this.labelShow = new System.Windows.Forms.Label();
this.panelHosts = new System.Windows.Forms.Panel();
this.panelShow = new System.Windows.Forms.Panel();
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.lblExported = new System.Windows.Forms.Label();
this.flowLayoutPanelButtons = new System.Windows.Forms.FlowLayoutPanel();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.flowLayoutPanel2 = new System.Windows.Forms.FlowLayoutPanel();
this.panelUsers = new System.Windows.Forms.Panel();
this.userComboBox = new XenAdmin.Controls.LongStringComboBox();
this.labelUsers = new System.Windows.Forms.Label();
this.panelObjects = new System.Windows.Forms.Panel();
this.labelObjects = new System.Windows.Forms.Label();
this.objectComboBox = new System.Windows.Forms.ComboBox();
this.panelHosts.SuspendLayout();
this.panelShow.SuspendLayout();
this.flowLayoutPanel1.SuspendLayout();
this.flowLayoutPanelButtons.SuspendLayout();
this.flowLayoutPanel2.SuspendLayout();
this.panelUsers.SuspendLayout();
this.panelObjects.SuspendLayout();
this.SuspendLayout();
//
// labelHostCombo
//
resources.ApplyResources(this.labelHostCombo, "labelHostCombo");
this.labelHostCombo.Name = "labelHostCombo";
//
// hostComboBox
//
this.hostComboBox.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.hostComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.hostComboBox.FormattingEnabled = true;
resources.ApplyResources(this.hostComboBox, "hostComboBox");
this.hostComboBox.Name = "hostComboBox";
this.hostComboBox.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.comboBox_DrawItem);
this.hostComboBox.Leave += new System.EventHandler(this.comboBox_DropDownClosed);
this.hostComboBox.DropDownClosed += new System.EventHandler(this.comboBox_DropDownClosed);
//
// btnRunReport
//
resources.ApplyResources(this.btnRunReport, "btnRunReport");
this.btnRunReport.Name = "btnRunReport";
this.btnRunReport.UseVisualStyleBackColor = true;
this.btnRunReport.Click += new System.EventHandler(this.btnRunReport_Click);
//
// btnLaterReport
//
resources.ApplyResources(this.btnLaterReport, "btnLaterReport");
this.btnLaterReport.Name = "btnLaterReport";
this.btnLaterReport.UseVisualStyleBackColor = true;
this.btnLaterReport.Click += new System.EventHandler(this.btnLaterReport_Click);
//
// labelEndDate
//
resources.ApplyResources(this.labelEndDate, "labelEndDate");
this.labelEndDate.Name = "labelEndDate";
//
// EndDatePicker
//
resources.ApplyResources(this.EndDatePicker, "EndDatePicker");
this.EndDatePicker.Name = "EndDatePicker";
this.EndDatePicker.ValueChanged += new System.EventHandler(this.comboBox_SelectionChanged);
//
// labelStartDate
//
resources.ApplyResources(this.labelStartDate, "labelStartDate");
this.labelStartDate.Name = "labelStartDate";
//
// StartDatePicker
//
resources.ApplyResources(this.StartDatePicker, "StartDatePicker");
this.StartDatePicker.Name = "StartDatePicker";
this.StartDatePicker.ValueChanged += new System.EventHandler(this.comboBox_SelectionChanged);
//
// reportViewer1
//
resources.ApplyResources(this.reportViewer1, "reportViewer1");
this.reportViewer1.Name = "reportViewer1";
this.reportViewer1.ShowRefreshButton = false;
this.reportViewer1.ReportExport += new Microsoft.Reporting.WinForms.ExportEventHandler(this.reportViewer1_ReportExport);
this.reportViewer1.Back += new Microsoft.Reporting.WinForms.BackEventHandler(this.reportViewer1_Back);
this.reportViewer1.Drillthrough += new Microsoft.Reporting.WinForms.DrillthroughEventHandler(this.reportViewer1_Drillthrough);
//
// btnSubscribe
//
resources.ApplyResources(this.btnSubscribe, "btnSubscribe");
this.btnSubscribe.Name = "btnSubscribe";
this.btnSubscribe.UseVisualStyleBackColor = true;
this.btnSubscribe.Click += new System.EventHandler(this.btnSubscribe_Click);
//
// btnClose
//
resources.ApplyResources(this.btnClose, "btnClose");
this.btnClose.Name = "btnClose";
this.btnClose.UseVisualStyleBackColor = true;
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
//
// comboBoxView
//
this.comboBoxView.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.comboBoxView.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxView.FormattingEnabled = true;
resources.ApplyResources(this.comboBoxView, "comboBoxView");
this.comboBoxView.Name = "comboBoxView";
this.comboBoxView.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.comboBox_DrawItem);
this.comboBoxView.SelectedIndexChanged += new System.EventHandler(this.comboBoxView_SelectedIndexChanged);
this.comboBoxView.DropDownClosed += new System.EventHandler(this.comboBox_DropDownClosed);
//
// labelShow
//
resources.ApplyResources(this.labelShow, "labelShow");
this.labelShow.Name = "labelShow";
//
// panelHosts
//
resources.ApplyResources(this.panelHosts, "panelHosts");
this.panelHosts.Controls.Add(this.hostComboBox);
this.panelHosts.Controls.Add(this.labelHostCombo);
this.panelHosts.Name = "panelHosts";
//
// panelShow
//
resources.ApplyResources(this.panelShow, "panelShow");
this.panelShow.Controls.Add(this.labelShow);
this.panelShow.Controls.Add(this.comboBoxView);
this.panelShow.Name = "panelShow";
//
// flowLayoutPanel1
//
resources.ApplyResources(this.flowLayoutPanel1, "flowLayoutPanel1");
this.flowLayoutPanel1.Controls.Add(this.panelHosts);
this.flowLayoutPanel1.Controls.Add(this.panelShow);
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
//
// timer1
//
this.timer1.Interval = 5000;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// lblExported
//
resources.ApplyResources(this.lblExported, "lblExported");
this.lblExported.BackColor = System.Drawing.Color.Khaki;
this.lblExported.Name = "lblExported";
//
// flowLayoutPanelButtons
//
resources.ApplyResources(this.flowLayoutPanelButtons, "flowLayoutPanelButtons");
this.flowLayoutPanelButtons.Controls.Add(this.btnClose);
this.flowLayoutPanelButtons.Controls.Add(this.btnSubscribe);
this.flowLayoutPanelButtons.Controls.Add(this.btnRunReport);
this.flowLayoutPanelButtons.Controls.Add(this.btnLaterReport);
this.flowLayoutPanelButtons.Name = "flowLayoutPanelButtons";
//
// flowLayoutPanel2
//
resources.ApplyResources(this.flowLayoutPanel2, "flowLayoutPanel2");
this.flowLayoutPanel2.Controls.Add(this.panelUsers);
this.flowLayoutPanel2.Controls.Add(this.panelObjects);
this.flowLayoutPanel2.Name = "flowLayoutPanel2";
//
// panelUsers
//
resources.ApplyResources(this.panelUsers, "panelUsers");
this.panelUsers.Controls.Add(this.userComboBox);
this.panelUsers.Controls.Add(this.labelUsers);
this.panelUsers.Name = "panelUsers";
//
// userComboBox
//
this.userComboBox.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.userComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.userComboBox.FormattingEnabled = true;
resources.ApplyResources(this.userComboBox, "userComboBox");
this.userComboBox.Name = "userComboBox";
this.userComboBox.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.comboBox_DrawItem);
this.userComboBox.DropDownClosed += new System.EventHandler(this.comboBox_DropDownClosed);
this.userComboBox.TextChanged += new System.EventHandler(this.comboBox_SelectionChanged);
this.userComboBox.Leave += new System.EventHandler(this.comboBox_DropDownClosed);
//
// labelUsers
//
resources.ApplyResources(this.labelUsers, "labelUsers");
this.labelUsers.Name = "labelUsers";
//
// panelObjects
//
resources.ApplyResources(this.panelObjects, "panelObjects");
this.panelObjects.Controls.Add(this.labelObjects);
this.panelObjects.Controls.Add(this.objectComboBox);
this.panelObjects.Name = "panelObjects";
//
// labelObjects
//
resources.ApplyResources(this.labelObjects, "labelObjects");
this.labelObjects.Name = "labelObjects";
//
// objectComboBox
//
this.objectComboBox.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.objectComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.objectComboBox.FormattingEnabled = true;
resources.ApplyResources(this.objectComboBox, "objectComboBox");
this.objectComboBox.Name = "objectComboBox";
this.objectComboBox.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.comboBox_DrawItem);
this.objectComboBox.DropDownClosed += new System.EventHandler(this.comboBox_DropDownClosed);
this.objectComboBox.TextChanged += new System.EventHandler(this.comboBox_SelectionChanged);
this.objectComboBox.Leave += new System.EventHandler(this.comboBox_DropDownClosed);
//
// WlbReportView
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.Controls.Add(this.flowLayoutPanel2);
this.Controls.Add(this.flowLayoutPanelButtons);
this.Controls.Add(this.flowLayoutPanel1);
this.Controls.Add(this.lblExported);
this.Controls.Add(this.labelEndDate);
this.Controls.Add(this.EndDatePicker);
this.Controls.Add(this.labelStartDate);
this.Controls.Add(this.StartDatePicker);
this.Controls.Add(this.reportViewer1);
this.Name = "WlbReportView";
this.Load += new System.EventHandler(this.ReportView_Load);
this.panelHosts.ResumeLayout(false);
this.panelHosts.PerformLayout();
this.panelShow.ResumeLayout(false);
this.flowLayoutPanel1.ResumeLayout(false);
this.flowLayoutPanel1.PerformLayout();
this.flowLayoutPanelButtons.ResumeLayout(false);
this.flowLayoutPanel2.ResumeLayout(false);
this.flowLayoutPanel2.PerformLayout();
this.panelUsers.ResumeLayout(false);
this.panelUsers.PerformLayout();
this.panelObjects.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label labelHostCombo;
private System.Windows.Forms.ComboBox hostComboBox;
private System.Windows.Forms.Button btnRunReport;
private System.Windows.Forms.Button btnLaterReport;
private System.Windows.Forms.Label labelEndDate;
private System.Windows.Forms.DateTimePicker EndDatePicker;
private System.Windows.Forms.Label labelStartDate;
private System.Windows.Forms.DateTimePicker StartDatePicker;
private Microsoft.Reporting.WinForms.ReportViewer reportViewer1;
private System.Windows.Forms.Button btnSubscribe;
private System.Windows.Forms.Button btnClose;
private System.Windows.Forms.ComboBox comboBoxView;
private System.Windows.Forms.Label labelShow;
private System.Windows.Forms.Panel panelHosts;
private System.Windows.Forms.Panel panelShow;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
private System.Windows.Forms.Timer timer1;
private System.Windows.Forms.Label lblExported;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanelButtons;
private System.Windows.Forms.ToolTip toolTip1;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel2;
private System.Windows.Forms.Panel panelUsers;
private XenAdmin.Controls.LongStringComboBox userComboBox;
private System.Windows.Forms.Label labelUsers;
private System.Windows.Forms.Panel panelObjects;
private System.Windows.Forms.Label labelObjects;
private System.Windows.Forms.ComboBox objectComboBox;
}
}
| |
using System;
using System.Drawing;
using System.Diagnostics.CodeAnalysis;
using System.Windows.Forms;
namespace WeifenLuo.WinFormsUI.Docking
{
public sealed class DockPanelExtender
{
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
public interface IDockPaneFactory
{
DockPane CreateDockPane(IDockContent content, DockState visibleState, bool show);
[SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "1#")]
DockPane CreateDockPane(IDockContent content, FloatWindow floatWindow, bool show);
DockPane CreateDockPane(IDockContent content, DockPane previousPane, DockAlignment alignment,
double proportion, bool show);
[SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "1#")]
DockPane CreateDockPane(IDockContent content, Rectangle floatWindowBounds, bool show);
}
public interface IDockPaneSplitterControlFactory
{
DockPane.SplitterControlBase CreateSplitterControl(DockPane pane);
}
public interface IDockWindowSplitterControlFactory
{
SplitterBase CreateSplitterControl();
}
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
public interface IFloatWindowFactory
{
FloatWindow CreateFloatWindow(DockPanel dockPanel, DockPane pane);
FloatWindow CreateFloatWindow(DockPanel dockPanel, DockPane pane, Rectangle bounds);
}
public interface IDockWindowFactory
{
DockWindow CreateDockWindow(DockPanel dockPanel, DockState dockState);
}
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
public interface IDockPaneCaptionFactory
{
DockPaneCaptionBase CreateDockPaneCaption(DockPane pane);
}
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
public interface IDockPaneStripFactory
{
DockPaneStripBase CreateDockPaneStrip(DockPane pane);
}
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
public interface IAutoHideStripFactory
{
AutoHideStripBase CreateAutoHideStrip(DockPanel panel);
}
public interface IAutoHideWindowFactory
{
DockPanel.AutoHideWindowControl CreateAutoHideWindow(DockPanel panel);
}
public interface IPaneIndicatorFactory
{
DockPanel.IPaneIndicator CreatePaneIndicator();
}
public interface IPanelIndicatorFactory
{
DockPanel.IPanelIndicator CreatePanelIndicator(DockStyle style);
}
public interface IDockOutlineFactory
{
DockOutlineBase CreateDockOutline();
}
#region DefaultDockPaneFactory
private class DefaultDockPaneFactory : IDockPaneFactory
{
public DockPane CreateDockPane(IDockContent content, DockState visibleState, bool show)
{
return new DockPane(content, visibleState, show);
}
public DockPane CreateDockPane(IDockContent content, FloatWindow floatWindow, bool show)
{
return new DockPane(content, floatWindow, show);
}
public DockPane CreateDockPane(IDockContent content, DockPane prevPane, DockAlignment alignment,
double proportion, bool show)
{
return new DockPane(content, prevPane, alignment, proportion, show);
}
public DockPane CreateDockPane(IDockContent content, Rectangle floatWindowBounds, bool show)
{
return new DockPane(content, floatWindowBounds, show);
}
}
#endregion
#region DefaultDockPaneSplitterControlFactory
private class DefaultDockPaneSplitterControlFactory : IDockPaneSplitterControlFactory
{
public DockPane.SplitterControlBase CreateSplitterControl(DockPane pane)
{
return new DockPane.DefaultSplitterControl(pane);
}
}
#endregion
#region DefaultDockWindowSplitterControlFactory
private class DefaultDockWindowSplitterControlFactory : IDockWindowSplitterControlFactory
{
public SplitterBase CreateSplitterControl()
{
return new DockWindow.DefaultSplitterControl();
}
}
#endregion
#region DefaultFloatWindowFactory
private class DefaultFloatWindowFactory : IFloatWindowFactory
{
public FloatWindow CreateFloatWindow(DockPanel dockPanel, DockPane pane)
{
return new FloatWindow(dockPanel, pane);
}
public FloatWindow CreateFloatWindow(DockPanel dockPanel, DockPane pane, Rectangle bounds)
{
return new FloatWindow(dockPanel, pane, bounds);
}
}
#endregion
#region DefaultDockWindowFactory
private class DefaultDockWindowFactory : IDockWindowFactory
{
public DockWindow CreateDockWindow(DockPanel dockPanel, DockState dockState)
{
return new DefaultDockWindow(dockPanel, dockState);
}
}
#endregion
#region DefaultDockPaneCaptionFactory
private class DefaultDockPaneCaptionFactory : IDockPaneCaptionFactory
{
public DockPaneCaptionBase CreateDockPaneCaption(DockPane pane)
{
return new VS2005DockPaneCaption(pane);
}
}
#endregion
#region DefaultDockPaneTabStripFactory
private class DefaultDockPaneStripFactory : IDockPaneStripFactory
{
public DockPaneStripBase CreateDockPaneStrip(DockPane pane)
{
return new VS2005DockPaneStrip(pane);
}
}
#endregion
#region DefaultAutoHideStripFactory
private class DefaultAutoHideStripFactory : IAutoHideStripFactory
{
public AutoHideStripBase CreateAutoHideStrip(DockPanel panel)
{
return new VS2005AutoHideStrip(panel);
}
}
#endregion
#region DefaultAutoHideWindowFactory
public class DefaultAutoHideWindowFactory : IAutoHideWindowFactory
{
public DockPanel.AutoHideWindowControl CreateAutoHideWindow(DockPanel panel)
{
return new DockPanel.DefaultAutoHideWindowControl(panel);
}
}
#endregion
public class DefaultPaneIndicatorFactory : IPaneIndicatorFactory
{
public DockPanel.IPaneIndicator CreatePaneIndicator()
{
return new DockPanel.DefaultPaneIndicator();
}
}
public class DefaultPanelIndicatorFactory : IPanelIndicatorFactory
{
public DockPanel.IPanelIndicator CreatePanelIndicator(DockStyle style)
{
return new DockPanel.DefaultPanelIndicator(style);
}
}
public class DefaultDockOutlineFactory : IDockOutlineFactory
{
public DockOutlineBase CreateDockOutline()
{
return new DockPanel.DefaultDockOutline();
}
}
internal DockPanelExtender(DockPanel dockPanel)
{
m_dockPanel = dockPanel;
}
private DockPanel m_dockPanel;
private DockPanel DockPanel
{
get { return m_dockPanel; }
}
private IDockPaneFactory m_dockPaneFactory = null;
public IDockPaneFactory DockPaneFactory
{
get
{
if (m_dockPaneFactory == null)
m_dockPaneFactory = new DefaultDockPaneFactory();
return m_dockPaneFactory;
}
set
{
if (DockPanel.Panes.Count > 0)
throw new InvalidOperationException();
m_dockPaneFactory = value;
}
}
private IDockPaneSplitterControlFactory m_dockPaneSplitterControlFactory;
public IDockPaneSplitterControlFactory DockPaneSplitterControlFactory
{
get
{
return m_dockPaneSplitterControlFactory ??
(m_dockPaneSplitterControlFactory = new DefaultDockPaneSplitterControlFactory());
}
set
{
if (DockPanel.Panes.Count > 0)
{
throw new InvalidOperationException();
}
m_dockPaneSplitterControlFactory = value;
}
}
private IDockWindowSplitterControlFactory m_dockWindowSplitterControlFactory;
public IDockWindowSplitterControlFactory DockWindowSplitterControlFactory
{
get
{
return m_dockWindowSplitterControlFactory ??
(m_dockWindowSplitterControlFactory = new DefaultDockWindowSplitterControlFactory());
}
set
{
m_dockWindowSplitterControlFactory = value;
DockPanel.ReloadDockWindows();
}
}
private IFloatWindowFactory m_floatWindowFactory = null;
public IFloatWindowFactory FloatWindowFactory
{
get
{
if (m_floatWindowFactory == null)
m_floatWindowFactory = new DefaultFloatWindowFactory();
return m_floatWindowFactory;
}
set
{
if (DockPanel.FloatWindows.Count > 0)
throw new InvalidOperationException();
m_floatWindowFactory = value;
}
}
private IDockWindowFactory m_dockWindowFactory;
public IDockWindowFactory DockWindowFactory
{
get { return m_dockWindowFactory ?? (m_dockWindowFactory = new DefaultDockWindowFactory()); }
set
{
m_dockWindowFactory = value;
DockPanel.ReloadDockWindows();
}
}
private IDockPaneCaptionFactory m_dockPaneCaptionFactory = null;
public IDockPaneCaptionFactory DockPaneCaptionFactory
{
get
{
if (m_dockPaneCaptionFactory == null)
m_dockPaneCaptionFactory = new DefaultDockPaneCaptionFactory();
return m_dockPaneCaptionFactory;
}
set
{
if (DockPanel.Panes.Count > 0)
throw new InvalidOperationException();
m_dockPaneCaptionFactory = value;
}
}
private IDockPaneStripFactory m_dockPaneStripFactory = null;
public IDockPaneStripFactory DockPaneStripFactory
{
get
{
if (m_dockPaneStripFactory == null)
m_dockPaneStripFactory = new DefaultDockPaneStripFactory();
return m_dockPaneStripFactory;
}
set
{
if (DockPanel.Contents.Count > 0)
throw new InvalidOperationException();
m_dockPaneStripFactory = value;
}
}
private IAutoHideStripFactory m_autoHideStripFactory = null;
public IAutoHideStripFactory AutoHideStripFactory
{
get
{
if (m_autoHideStripFactory == null)
m_autoHideStripFactory = new DefaultAutoHideStripFactory();
return m_autoHideStripFactory;
}
set
{
if (DockPanel.Contents.Count > 0)
throw new InvalidOperationException();
if (m_autoHideStripFactory == value)
return;
m_autoHideStripFactory = value;
DockPanel.ResetAutoHideStripControl();
}
}
private IAutoHideWindowFactory m_autoHideWindowFactory;
public IAutoHideWindowFactory AutoHideWindowFactory
{
get { return m_autoHideWindowFactory ?? (m_autoHideWindowFactory = new DefaultAutoHideWindowFactory()); }
set
{
if (DockPanel.Contents.Count > 0)
{
throw new InvalidOperationException();
}
if (m_autoHideWindowFactory == value)
{
return;
}
m_autoHideWindowFactory = value;
DockPanel.ResetAutoHideStripWindow();
}
}
private IPaneIndicatorFactory m_PaneIndicatorFactory;
public IPaneIndicatorFactory PaneIndicatorFactory
{
get { return m_PaneIndicatorFactory ?? (m_PaneIndicatorFactory = new DefaultPaneIndicatorFactory()); }
set { m_PaneIndicatorFactory = value; }
}
private IPanelIndicatorFactory m_PanelIndicatorFactory;
public IPanelIndicatorFactory PanelIndicatorFactory
{
get { return m_PanelIndicatorFactory ?? (m_PanelIndicatorFactory = new DefaultPanelIndicatorFactory()); }
set { m_PanelIndicatorFactory = value; }
}
private IDockOutlineFactory m_DockOutlineFactory;
public IDockOutlineFactory DockOutlineFactory
{
get { return m_DockOutlineFactory ?? (m_DockOutlineFactory = new DefaultDockOutlineFactory()); }
set { m_DockOutlineFactory = value; }
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using OmniSharp.Models;
using OmniSharp.Roslyn.CSharp.Services.Refactoring;
using OmniSharp.Tests;
using Xunit;
namespace OmniSharp.Roslyn.CSharp.Tests
{
public class RenameFacts
{
private async Task<RenameResponse> SendRequest(OmnisharpWorkspace workspace,
string renameTo,
string filename,
string fileContent,
bool wantsTextChanges = false,
bool applyTextChanges = true)
{
var lineColumn = TestHelpers.GetLineAndColumnFromDollar(fileContent);
var controller = new RenameService(workspace);
var request = new RenameRequest
{
Line = lineColumn.Line,
Column = lineColumn.Column,
RenameTo = renameTo,
FileName = filename,
Buffer = fileContent.Replace("$", ""),
WantsTextChanges = wantsTextChanges,
ApplyTextChanges = applyTextChanges
};
await workspace.BufferManager.UpdateBuffer(request);
return await controller.Handle(request);
}
[Fact]
public async Task Rename_UpdatesWorkspaceAndDocumentText()
{
const string fileContent = @"using System;
namespace OmniSharp.Models
{
public class CodeFormat$Response
{
public string Buffer { get; set; }
}
}";
var workspace = await TestHelpers.CreateSimpleWorkspace(fileContent, "test.cs");
var result = await SendRequest(workspace, "foo", "test.cs", fileContent, applyTextChanges: true);
var docId = workspace.CurrentSolution.GetDocumentIdsWithFilePath("test.cs").First();
var sourceText = await workspace.CurrentSolution.GetDocument(docId).GetTextAsync();
//compare workspace change with response
Assert.Equal(result.Changes.First().Buffer, sourceText.ToString());
//check that response refers to correct modified file
Assert.Equal(result.Changes.First().FileName, "test.cs");
//check response for change
Assert.Equal(@"using System;
namespace OmniSharp.Models
{
public class foo
{
public string Buffer { get; set; }
}
}", result.Changes.First().Buffer);
}
[Fact]
public async Task Rename_DoesNotUpdatesWorkspace()
{
const string fileContent = @"using System;
namespace OmniSharp.Models
{
public class CodeFormat$Response
{
public string Buffer { get; set; }
}
}";
var workspace = await TestHelpers.CreateSimpleWorkspace(fileContent, "test.cs");
var result = await SendRequest(workspace, "foo", "test.cs", fileContent, applyTextChanges: false);
var docId = workspace.CurrentSolution.GetDocumentIdsWithFilePath("test.cs").First();
var sourceText = await workspace.CurrentSolution.GetDocument(docId).GetTextAsync();
// check that the workspace has not been updated
Assert.Equal(fileContent.Replace("$", ""), sourceText.ToString());
}
[Fact]
public async Task Rename_UpdatesMultipleDocumentsIfNecessary()
{
const string file1 = "public class F$oo {}";
const string file2 = @"public class Bar {
public Foo Property {get; set;}
}";
var workspace = await TestHelpers.CreateSimpleWorkspace(new Dictionary<string, string> { { "test1.cs", file1 }, { "test2.cs", file2 } });
var result = await SendRequest(workspace, "xxx", "test1.cs", file1);
var doc1Id = workspace.CurrentSolution.GetDocumentIdsWithFilePath("test1.cs").First();
var doc2Id = workspace.CurrentSolution.GetDocumentIdsWithFilePath("test2.cs").First();
var source1Text = await workspace.CurrentSolution.GetDocument(doc1Id).GetTextAsync();
var source2Text = await workspace.CurrentSolution.GetDocument(doc2Id).GetTextAsync();
//compare workspace change with response for file 1
Assert.Equal(result.Changes.ElementAt(0).Buffer, source1Text.ToString());
//check that response refers to modified file 1
Assert.Equal(result.Changes.ElementAt(0).FileName, "test1.cs");
//check response for change in file 1
Assert.Equal(@"public class xxx {}", result.Changes.ElementAt(0).Buffer);
//compare workspace change with response for file 2
Assert.Equal(result.Changes.ElementAt(1).Buffer, source2Text.ToString());
//check that response refers to modified file 2
Assert.Equal(result.Changes.ElementAt(1).FileName, "test2.cs");
//check response for change in file 2
Assert.Equal(@"public class Bar {
public xxx Property {get; set;}
}", result.Changes.ElementAt(1).Buffer);
}
[Fact]
public async Task Rename_UpdatesMultipleDocumentsIfNecessaryAndProducesTextChangesIfAsked()
{
const string file1 = "public class F$oo {}";
const string file2 = @"public class Bar {
public Foo Property {get; set;}
}";
var workspace = await TestHelpers.CreateSimpleWorkspace(new Dictionary<string, string> { { "test1.cs", file1 }, { "test2.cs", file2 } });
var result = await SendRequest(workspace, "xxx", "test1.cs", file1, true);
Assert.Equal(2, result.Changes.Count());
Assert.Equal(1, result.Changes.ElementAt(0).Changes.Count());
Assert.Null(result.Changes.ElementAt(0).Buffer);
Assert.Equal("xxx", result.Changes.ElementAt(0).Changes.First().NewText);
Assert.Equal(1, result.Changes.ElementAt(0).Changes.First().StartLine);
Assert.Equal(14, result.Changes.ElementAt(0).Changes.First().StartColumn);
Assert.Equal(1, result.Changes.ElementAt(0).Changes.First().EndLine);
Assert.Equal(17, result.Changes.ElementAt(0).Changes.First().EndColumn);
Assert.Null(result.Changes.ElementAt(1).Buffer);
Assert.Equal("xxx", result.Changes.ElementAt(1).Changes.First().NewText);
Assert.Equal(2, result.Changes.ElementAt(1).Changes.First().StartLine);
Assert.Equal(44, result.Changes.ElementAt(1).Changes.First().StartColumn);
Assert.Equal(2, result.Changes.ElementAt(1).Changes.First().EndLine);
Assert.Equal(47, result.Changes.ElementAt(1).Changes.First().EndColumn);
}
[Fact]
public async Task Rename_DoesTheRightThingWhenDocumentIsNotFound()
{
const string fileContent = "class f$oo{}";
var workspace = await TestHelpers.CreateSimpleWorkspace(fileContent);
var result = await SendRequest(workspace, "xxx", "test.cs", fileContent);
Assert.Equal(1, result.Changes.Count());
Assert.Equal("test.cs", result.Changes.ElementAt(0).FileName);
}
[Fact]
public async Task Rename_DoesNotExplodeWhenAttemptingToRenameALibrarySymbol()
{
const string fileContent = @"
using System;
public class Program
{
public static void Main()
{
Console.Wri$te(1);
}
}";
var workspace = await TestHelpers.CreateSimpleWorkspace(fileContent, "test.cs");
var result = await SendRequest(workspace, "foo", "test.cs", fileContent);
Assert.Equal(0, result.Changes.Count());
Assert.NotNull(result.ErrorMessage);
}
[Fact]
public async Task Rename_DoesNotDuplicateRenamesWithMultipleFrameowrks()
{
const string fileContent = @"
using System;
public class Program
{
public void Main(bool aBool$ean)
{
Console.Write(aBoolean);
}
}";
var workspace = await TestHelpers.CreateSimpleWorkspace(fileContent, "test.cs");
var result = await SendRequest(workspace, "foo", "test.cs", fileContent, true);
Assert.Equal(1, result.Changes.Count());
Assert.Equal("test.cs", result.Changes.ElementAt(0).FileName);
Assert.Equal(2, result.Changes.ElementAt(0).Changes.Count());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Globalization;
using System.Text;
using System.Windows;
namespace ParticleModel
{
public enum ParticleType
{
Point,
Sprite,
Disc,
Billboard,
Model
}
public enum EmitterSpace
{
World,
ObjectPos,
ObjectYpr,
NodePos,
NodeYpr,
Bones
}
public enum CoordSys
{
Polar,
Cartesian
}
public enum ParticleSpace
{
SameAsEmitter,
World,
EmitterYpr
}
public enum BlendMode
{
Add,
Blend,
Multiply,
Subtract
}
public static class ParticleTypeHelper
{
public static string ToString(ParticleType type)
{
switch (type)
{
case ParticleType.Point:
return "Point";
case ParticleType.Sprite:
return "Sprite";
case ParticleType.Disc:
return "Disc";
case ParticleType.Billboard:
return "Billboard";
case ParticleType.Model:
return "Model";
default:
throw new ArgumentOutOfRangeException(nameof(type), type, null);
}
}
public static ParticleType Parse(string value)
{
switch (value.ToLowerInvariant())
{
case "point":
return ParticleType.Point;
case "sprite":
return ParticleType.Sprite;
case "disc":
return ParticleType.Disc;
case "billboard":
return ParticleType.Billboard;
case "model":
return ParticleType.Model;
default:
return ParticleType.Point;
}
}
}
public static class BlendModeHelper
{
public static string ToString(BlendMode blendMode)
{
switch (blendMode)
{
case BlendMode.Add:
return "Add";
case BlendMode.Blend:
return "Blend";
case BlendMode.Multiply:
return "Multiply";
case BlendMode.Subtract:
return "Subtract";
default:
throw new ArgumentOutOfRangeException(nameof(blendMode), blendMode, null);
}
}
public static BlendMode ParseString(string value)
{
switch (value.ToLowerInvariant())
{
case "blend":
return BlendMode.Blend;
case "multiply":
return BlendMode.Multiply;
case "subtract":
return BlendMode.Subtract;
default:
return BlendMode.Add;
}
}
}
public static class CoordSysHelper
{
public static string ToString(CoordSys coordSys)
{
switch (coordSys)
{
case CoordSys.Polar:
return "Polar";
case CoordSys.Cartesian:
return "Cartesian";
default:
throw new ArgumentOutOfRangeException(nameof(coordSys), coordSys, null);
}
}
public static CoordSys ParseString(string value)
{
switch (value.ToLowerInvariant())
{
case "polar":
return CoordSys.Polar;
default:
return CoordSys.Cartesian;
}
}
}
public static class EmitterSpaceHelper
{
public static string ToString(EmitterSpace space)
{
switch (space)
{
case EmitterSpace.World:
return "World";
case EmitterSpace.ObjectPos:
return "Object Pos";
case EmitterSpace.ObjectYpr:
return "Object YPR";
case EmitterSpace.NodePos:
return "Node Pos";
case EmitterSpace.NodeYpr:
return "Node YPR";
case EmitterSpace.Bones:
return "Bones";
default:
throw new ArgumentOutOfRangeException(nameof(space), space, null);
}
}
public static EmitterSpace ParseString(string value)
{
switch (value.ToLowerInvariant())
{
case "object pos":
return EmitterSpace.ObjectPos;
case "object ypr":
return EmitterSpace.ObjectYpr;
case "node pos":
return EmitterSpace.NodePos;
case "node ypr":
return EmitterSpace.NodeYpr;
case "bones":
return EmitterSpace.Bones;
default:
return EmitterSpace.World;
}
}
}
public static class ParticleSpaceHelper
{
public static string ToString(ParticleSpace space)
{
switch (space)
{
case ParticleSpace.World:
return "World";
case ParticleSpace.EmitterYpr:
return "Emitter YPR";
case ParticleSpace.SameAsEmitter:
return "Same as Emitter";
default:
throw new ArgumentOutOfRangeException(nameof(space), space, null);
}
}
public static ParticleSpace ParseString(string value)
{
switch (value.ToLowerInvariant())
{
case "emitter ypr":
return ParticleSpace.EmitterYpr;
case "same as emitter":
return ParticleSpace.SameAsEmitter;
default:
return ParticleSpace.World;
}
}
}
public class EmitterSpec : DependencyObject
{
private const int ColPartsysName = 0;
private const int ColEmitterName = 1;
private const int ColDelay = 2;
private const int ColEmitType = 3; // Unused
private const int ColLifespan = 4;
private const int ColParticleRate = 5;
private const int ColBoundingRadius = 6; // Unused
private const int ColEmitterSpace = 7;
private const int ColEmitterNodeName = 8;
private const int ColEmitterCoordSys = 9;
private const int ColEmitterOffsetCoordSys = 10;
private const int ColParticleType = 11;
private const int ColParticleSpace = 12;
private const int ColParticlePosCoordSys = 13;
private const int ColParticleVelocityCoordSys = 14;
private const int ColMaterial = 15;
private const int ColPartLifespan = 16;
private const int ColBlendMode = 17;
private const int ColBounce = 18; // Unused
private const int ColAnimSpeed = 19; // Unused
private const int ColModel = 20;
// animation
private const int ColFirstParam = 22;
private const int ColBbLeft = 67;
private const int ColBbTop = 68;
private const int ColBbRight = 69;
private const int ColBbBottom = 70;
private const int ColMinParticles = 71;
private const int ColCount = 72;
public static readonly DependencyProperty NameProperty = DependencyProperty.Register("Name", typeof (string),
typeof (EmitterSpec), new PropertyMetadata(default(string)));
public static readonly DependencyProperty ParticleTypeProperty = DependencyProperty.Register("ParticleType",
typeof (ParticleType), typeof (EmitterSpec), new PropertyMetadata(ParticleType.Point));
public static readonly DependencyProperty PermanentProperty = DependencyProperty.Register("Permanent",
typeof (bool), typeof (EmitterSpec), new PropertyMetadata(default(bool)));
public static readonly DependencyProperty LifespanSecsProperty = DependencyProperty.Register("LifespanSecs",
typeof (float), typeof (EmitterSpec), new PropertyMetadata(default(float)));
public static readonly DependencyProperty DelaySecsProperty = DependencyProperty.Register("DelaySecs",
typeof (float), typeof (EmitterSpec), new PropertyMetadata(default(float)));
public static readonly DependencyProperty ParticlesPerSecProperty =
DependencyProperty.Register("ParticlesPerSec", typeof (float), typeof (EmitterSpec),
new PropertyMetadata(default(float)));
public static readonly DependencyProperty ParticleLifespanProperty =
DependencyProperty.Register("ParticleLifespan", typeof (float), typeof (EmitterSpec),
new PropertyMetadata(1.0f));
public static readonly DependencyProperty ParticlesPermanentProperty =
DependencyProperty.Register("ParticlesPermanent", typeof (bool), typeof (EmitterSpec),
new PropertyMetadata(default(bool)));
public static readonly DependencyProperty MaterialProperty = DependencyProperty.Register("Material",
typeof (string), typeof (EmitterSpec), new PropertyMetadata(default(string)));
public static readonly DependencyProperty SpaceProperty = DependencyProperty.Register("Space",
typeof (EmitterSpace), typeof (EmitterSpec), new PropertyMetadata(EmitterSpace.World));
public static readonly DependencyProperty NodeNameProperty = DependencyProperty.Register("NodeName",
typeof (string), typeof (EmitterSpec), new PropertyMetadata(default(string)));
public static readonly DependencyProperty CoordSysProperty = DependencyProperty.Register("CoordSys",
typeof (CoordSys), typeof (EmitterSpec), new PropertyMetadata(CoordSys.Cartesian));
public static readonly DependencyProperty OffsetCoordSysProperty = DependencyProperty.Register(
"OffsetCoordSys", typeof (CoordSys), typeof (EmitterSpec), new PropertyMetadata(CoordSys.Cartesian));
public static readonly DependencyProperty ParticleSpaceProperty = DependencyProperty.Register("ParticleSpace",
typeof (ParticleSpace), typeof (EmitterSpec), new PropertyMetadata(ParticleSpace.World));
public static readonly DependencyProperty ParticlePosCoordSysProperty =
DependencyProperty.Register("ParticlePosCoordSys", typeof (CoordSys), typeof (EmitterSpec),
new PropertyMetadata(CoordSys.Cartesian));
public static readonly DependencyProperty ParticleVelocityCoordSysProperty =
DependencyProperty.Register("ParticleVelocityCoordSys", typeof (CoordSys), typeof (EmitterSpec),
new PropertyMetadata(CoordSys.Cartesian));
public static readonly DependencyProperty BlendModeProperty = DependencyProperty.Register("BlendMode",
typeof (BlendMode), typeof (EmitterSpec), new PropertyMetadata(BlendMode.Add));
public static readonly DependencyProperty BoundingBoxLeftProperty =
DependencyProperty.Register("BoundingBoxLeft", typeof (float), typeof (EmitterSpec),
new PropertyMetadata(-399.0f));
public static readonly DependencyProperty BoundingBoxTopProperty = DependencyProperty.Register(
"BoundingBoxTop", typeof (float), typeof (EmitterSpec), new PropertyMetadata(-299.0f));
public static readonly DependencyProperty BoundingBoxRightProperty =
DependencyProperty.Register("BoundingBoxRight", typeof (float), typeof (EmitterSpec),
new PropertyMetadata(399.0f));
public static readonly DependencyProperty BoundingBoxBottomProperty =
DependencyProperty.Register("BoundingBoxBottom", typeof (float), typeof (EmitterSpec),
new PropertyMetadata(299.0f));
public static readonly DependencyProperty MinActiveParticlesProperty =
DependencyProperty.Register("MinActiveParticles", typeof (int?), typeof (EmitterSpec),
new PropertyMetadata(default(int?)));
public static readonly DependencyProperty ModelProperty = DependencyProperty.Register("Model", typeof (string),
typeof (EmitterSpec), new PropertyMetadata(default(string)));
public static readonly DependencyProperty ParamsProperty = DependencyProperty.Register("Params",
typeof (ObservableCollection<VariableParamSpec>), typeof (EmitterSpec),
new PropertyMetadata(default(ObservableCollection<VariableParamSpec>)));
public EmitterSpec()
{
Params = new ObservableCollection<VariableParamSpec>();
}
public ObservableCollection<VariableParamSpec> Params
{
get { return (ObservableCollection<VariableParamSpec>) GetValue(ParamsProperty); }
set
{
if (Params != null)
{
Params.CollectionChanged -= ParamsChanged;
}
SetValue(ParamsProperty, value);
//if (value != null)
{
value.CollectionChanged += ParamsChanged;
}
}
}
private void ParamsChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (var oldItem in e.OldItems)
{
((VariableParamSpec) oldItem).ParamChanged -= ParamChanged;
}
}
if (e.NewItems != null)
{
foreach (var newItem in e.NewItems)
{
((VariableParamSpec)newItem).ParamChanged += ParamChanged;
}
}
OnEmitterChanged();
}
private void ParamChanged(object sender, EventArgs e)
{
// One of the parameters has changed, go ahead and notify listeners that this emitter may have changed
OnEmitterChanged();
}
public float BoundingBoxLeft
{
get { return (float) GetValue(BoundingBoxLeftProperty); }
set { SetValue(BoundingBoxLeftProperty, value); }
}
public float BoundingBoxTop
{
get { return (float) GetValue(BoundingBoxTopProperty); }
set { SetValue(BoundingBoxTopProperty, value); }
}
public float BoundingBoxRight
{
get { return (float) GetValue(BoundingBoxRightProperty); }
set { SetValue(BoundingBoxRightProperty, value); }
}
public float BoundingBoxBottom
{
get { return (float) GetValue(BoundingBoxBottomProperty); }
set { SetValue(BoundingBoxBottomProperty, value); }
}
public int? MinActiveParticles
{
get { return (int?) GetValue(MinActiveParticlesProperty); }
set { SetValue(MinActiveParticlesProperty, value); }
}
public BlendMode BlendMode
{
get { return (BlendMode) GetValue(BlendModeProperty); }
set { SetValue(BlendModeProperty, value); }
}
public string Model
{
get { return (string) GetValue(ModelProperty); }
set { SetValue(ModelProperty, value); }
}
public ParticleSpace ParticleSpace
{
get { return (ParticleSpace) GetValue(ParticleSpaceProperty); }
set { SetValue(ParticleSpaceProperty, value); }
}
public CoordSys ParticlePosCoordSys
{
get { return (CoordSys) GetValue(ParticlePosCoordSysProperty); }
set { SetValue(ParticlePosCoordSysProperty, value); }
}
public CoordSys ParticleVelocityCoordSys
{
get { return (CoordSys) GetValue(ParticleVelocityCoordSysProperty); }
set { SetValue(ParticleVelocityCoordSysProperty, value); }
}
public string NodeName
{
get { return (string) GetValue(NodeNameProperty); }
set { SetValue(NodeNameProperty, value); }
}
public string Name
{
get { return (string) GetValue(NameProperty); }
set { SetValue(NameProperty, value); }
}
public ParticleType ParticleType
{
get { return (ParticleType) GetValue(ParticleTypeProperty); }
set { SetValue(ParticleTypeProperty, value); }
}
public bool Permanent
{
get { return (bool) GetValue(PermanentProperty); }
set { SetValue(PermanentProperty, value); }
}
public float LifespanSecs
{
get { return (float) GetValue(LifespanSecsProperty); }
set { SetValue(LifespanSecsProperty, value); }
}
public float DelaySecs
{
get { return (float) GetValue(DelaySecsProperty); }
set { SetValue(DelaySecsProperty, value); }
}
public float ParticlesPerSec
{
get { return (float) GetValue(ParticlesPerSecProperty); }
set { SetValue(ParticlesPerSecProperty, value); }
}
public float ParticleLifespan
{
get { return (float) GetValue(ParticleLifespanProperty); }
set { SetValue(ParticleLifespanProperty, value); }
}
public bool ParticlesPermanent
{
get { return (bool) GetValue(ParticlesPermanentProperty); }
set { SetValue(ParticlesPermanentProperty, value); }
}
public string Material
{
get { return (string) GetValue(MaterialProperty); }
set { SetValue(MaterialProperty, value); }
}
public EmitterSpace Space
{
get { return (EmitterSpace) GetValue(SpaceProperty); }
set { SetValue(SpaceProperty, value); }
}
public CoordSys CoordSys
{
get { return (CoordSys) GetValue(CoordSysProperty); }
set { SetValue(CoordSysProperty, value); }
}
public CoordSys OffsetCoordSys
{
get { return (CoordSys) GetValue(OffsetCoordSysProperty); }
set { SetValue(OffsetCoordSysProperty, value); }
}
public event EventHandler EmitterChanged;
public static EmitterSpec Parse(string line)
{
var result = new EmitterSpec();
var cols = line.Split('\t');
// Sanitize line parts (vertical tabs, spaces)
for (var i = 0; i < cols.Length; ++i)
{
cols[i] = cols[i].Trim(' ', '\v');
}
result.Name = cols[ColEmitterName];
result.ParticlesPerSec = float.Parse(cols[ColParticleRate], CultureInfo.InvariantCulture);
result.ParticleType = ParticleTypeHelper.Parse(cols[ColParticleType]);
if (cols[ColLifespan].Equals("perm", StringComparison.InvariantCultureIgnoreCase))
{
result.Permanent = true;
}
else
{
result.LifespanSecs = float.Parse(cols[ColLifespan]);
}
if (cols[ColPartLifespan].Equals("perm", StringComparison.InvariantCultureIgnoreCase))
{
result.ParticlesPermanent = true;
}
else
{
float floatVal;
if (float.TryParse(cols[ColPartLifespan], out floatVal))
{
result.ParticleLifespan = floatVal;
}
}
result.Material = cols[ColMaterial];
result.Space = EmitterSpaceHelper.ParseString(cols[ColEmitterSpace]);
result.NodeName = cols[ColEmitterNodeName];
result.CoordSys = CoordSysHelper.ParseString(cols[ColEmitterCoordSys]);
result.OffsetCoordSys = CoordSysHelper.ParseString(cols[ColEmitterOffsetCoordSys]);
result.ParticleSpace = ParticleSpaceHelper.ParseString(cols[ColParticleSpace]);
result.ParticlePosCoordSys = CoordSysHelper.ParseString(cols[ColParticlePosCoordSys]);
result.ParticleVelocityCoordSys = CoordSysHelper.ParseString(cols[ColParticleVelocityCoordSys]);
result.BlendMode = BlendModeHelper.ParseString(cols[ColBlendMode]);
result.Model = cols[ColModel];
float bbVal;
if (float.TryParse(cols[ColBbLeft], out bbVal))
{
result.BoundingBoxLeft = bbVal;
}
if (float.TryParse(cols[ColBbTop], out bbVal))
{
result.BoundingBoxTop = bbVal;
}
if (float.TryParse(cols[ColBbRight], out bbVal))
{
result.BoundingBoxRight = bbVal;
}
if (float.TryParse(cols[ColBbBottom], out bbVal))
{
result.BoundingBoxBottom = bbVal;
}
int minActiveParts;
if (int.TryParse(cols[ColMinParticles], out minActiveParts))
{
result.MinActiveParticles = minActiveParts;
}
// Parse the variable parameters
foreach (ParamId paramId in Enum.GetValues(typeof (ParamId)))
{
var col = ColFirstParam + (int) paramId;
var param = new VariableParamSpec
{
Id = paramId,
Value = cols[col]
};
if (string.IsNullOrWhiteSpace(param.Value))
{
param.Value = "0";
}
result.Params.Add(param);
}
return result;
}
public string ToSpec(string partSysName)
{
var cols = new object[ColCount];
cols[ColPartsysName] = partSysName;
cols[ColEmitterName] = Name;
// Lifetime + Particle Count
cols[ColDelay] = DelaySecs;
cols[ColBounce] = 0; // Unused but this is used in the vanilla files
if (Permanent)
{
cols[ColLifespan] = "perm";
}
else
{
cols[ColLifespan] = LifespanSecs;
}
if (ParticlesPermanent)
{
cols[ColPartLifespan] = "perm";
}
else
{
cols[ColPartLifespan] = ParticleLifespan;
}
cols[ColParticleRate] = ParticlesPerSec;
// Emit type is not actually used and seems to be Point
cols[ColEmitType] = "Point";
cols[ColParticleType] = ParticleType;
cols[ColMaterial] = Material;
cols[ColEmitterSpace] = EmitterSpaceHelper.ToString(Space);
cols[ColEmitterNodeName] = NodeName;
cols[ColEmitterCoordSys] = CoordSysHelper.ToString(CoordSys);
cols[ColEmitterOffsetCoordSys] = CoordSysHelper.ToString(OffsetCoordSys);
cols[ColParticleSpace] = ParticleSpaceHelper.ToString(ParticleSpace);
cols[ColParticlePosCoordSys] = CoordSysHelper.ToString(ParticlePosCoordSys);
cols[ColParticleVelocityCoordSys] = CoordSysHelper.ToString(ParticleVelocityCoordSys);
cols[ColBlendMode] = BlendModeHelper.ToString(BlendMode);
cols[ColModel] = Model;
cols[ColBbLeft] = BoundingBoxLeft;
cols[ColBbTop] = BoundingBoxTop;
cols[ColBbRight] = BoundingBoxRight;
cols[ColBbBottom] = BoundingBoxBottom;
if (MinActiveParticles.HasValue)
{
cols[ColMinParticles] = MinActiveParticles;
}
foreach (var param in Params)
{
if (param != null)
{
cols[ColFirstParam + (int) param.Id] = param.Value;
}
}
return FormatColumns(cols);
}
private static string FormatColumns(IEnumerable<object> cols)
{
// Convert the columns to strings
var result = new StringBuilder(512);
foreach (var col in cols)
{
if (result.Length > 0)
{
result.Append('\t');
}
// Do the proper formatting of the column type
result.AppendFormat(CultureInfo.InvariantCulture, "{0}", col);
}
return result.ToString();
}
protected virtual void OnEmitterChanged()
{
EmitterChanged?.Invoke(this, EventArgs.Empty);
}
protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);
OnEmitterChanged();
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the route53-2013-04-01.normal.json service model.
*/
using System;
using Amazon.Runtime;
namespace Amazon.Route53
{
/// <summary>
/// Constants used for properties of type ChangeAction.
/// </summary>
public class ChangeAction : ConstantClass
{
/// <summary>
/// Constant CREATE for ChangeAction
/// </summary>
public static readonly ChangeAction CREATE = new ChangeAction("CREATE");
/// <summary>
/// Constant DELETE for ChangeAction
/// </summary>
public static readonly ChangeAction DELETE = new ChangeAction("DELETE");
/// <summary>
/// Constant UPSERT for ChangeAction
/// </summary>
public static readonly ChangeAction UPSERT = new ChangeAction("UPSERT");
/// <summary>
/// Default Constructor
/// </summary>
public ChangeAction(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ChangeAction FindValue(string value)
{
return FindValue<ChangeAction>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ChangeAction(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ChangeStatus.
/// </summary>
public class ChangeStatus : ConstantClass
{
/// <summary>
/// Constant INSYNC for ChangeStatus
/// </summary>
public static readonly ChangeStatus INSYNC = new ChangeStatus("INSYNC");
/// <summary>
/// Constant PENDING for ChangeStatus
/// </summary>
public static readonly ChangeStatus PENDING = new ChangeStatus("PENDING");
/// <summary>
/// Default Constructor
/// </summary>
public ChangeStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ChangeStatus FindValue(string value)
{
return FindValue<ChangeStatus>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ChangeStatus(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type HealthCheckType.
/// </summary>
public class HealthCheckType : ConstantClass
{
/// <summary>
/// Constant CALCULATED for HealthCheckType
/// </summary>
public static readonly HealthCheckType CALCULATED = new HealthCheckType("CALCULATED");
/// <summary>
/// Constant HTTP for HealthCheckType
/// </summary>
public static readonly HealthCheckType HTTP = new HealthCheckType("HTTP");
/// <summary>
/// Constant HTTP_STR_MATCH for HealthCheckType
/// </summary>
public static readonly HealthCheckType HTTP_STR_MATCH = new HealthCheckType("HTTP_STR_MATCH");
/// <summary>
/// Constant HTTPS for HealthCheckType
/// </summary>
public static readonly HealthCheckType HTTPS = new HealthCheckType("HTTPS");
/// <summary>
/// Constant HTTPS_STR_MATCH for HealthCheckType
/// </summary>
public static readonly HealthCheckType HTTPS_STR_MATCH = new HealthCheckType("HTTPS_STR_MATCH");
/// <summary>
/// Constant TCP for HealthCheckType
/// </summary>
public static readonly HealthCheckType TCP = new HealthCheckType("TCP");
/// <summary>
/// Default Constructor
/// </summary>
public HealthCheckType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static HealthCheckType FindValue(string value)
{
return FindValue<HealthCheckType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator HealthCheckType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ResourceRecordSetFailover.
/// </summary>
public class ResourceRecordSetFailover : ConstantClass
{
/// <summary>
/// Constant PRIMARY for ResourceRecordSetFailover
/// </summary>
public static readonly ResourceRecordSetFailover PRIMARY = new ResourceRecordSetFailover("PRIMARY");
/// <summary>
/// Constant SECONDARY for ResourceRecordSetFailover
/// </summary>
public static readonly ResourceRecordSetFailover SECONDARY = new ResourceRecordSetFailover("SECONDARY");
/// <summary>
/// Default Constructor
/// </summary>
public ResourceRecordSetFailover(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ResourceRecordSetFailover FindValue(string value)
{
return FindValue<ResourceRecordSetFailover>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ResourceRecordSetFailover(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ResourceRecordSetRegion.
/// </summary>
public class ResourceRecordSetRegion : ConstantClass
{
/// <summary>
/// Constant ApNortheast1 for ResourceRecordSetRegion
/// </summary>
public static readonly ResourceRecordSetRegion ApNortheast1 = new ResourceRecordSetRegion("ap-northeast-1");
/// <summary>
/// Constant ApSoutheast1 for ResourceRecordSetRegion
/// </summary>
public static readonly ResourceRecordSetRegion ApSoutheast1 = new ResourceRecordSetRegion("ap-southeast-1");
/// <summary>
/// Constant ApSoutheast2 for ResourceRecordSetRegion
/// </summary>
public static readonly ResourceRecordSetRegion ApSoutheast2 = new ResourceRecordSetRegion("ap-southeast-2");
/// <summary>
/// Constant CnNorth1 for ResourceRecordSetRegion
/// </summary>
public static readonly ResourceRecordSetRegion CnNorth1 = new ResourceRecordSetRegion("cn-north-1");
/// <summary>
/// Constant EuCentral1 for ResourceRecordSetRegion
/// </summary>
public static readonly ResourceRecordSetRegion EuCentral1 = new ResourceRecordSetRegion("eu-central-1");
/// <summary>
/// Constant EuWest1 for ResourceRecordSetRegion
/// </summary>
public static readonly ResourceRecordSetRegion EuWest1 = new ResourceRecordSetRegion("eu-west-1");
/// <summary>
/// Constant SaEast1 for ResourceRecordSetRegion
/// </summary>
public static readonly ResourceRecordSetRegion SaEast1 = new ResourceRecordSetRegion("sa-east-1");
/// <summary>
/// Constant UsEast1 for ResourceRecordSetRegion
/// </summary>
public static readonly ResourceRecordSetRegion UsEast1 = new ResourceRecordSetRegion("us-east-1");
/// <summary>
/// Constant UsWest1 for ResourceRecordSetRegion
/// </summary>
public static readonly ResourceRecordSetRegion UsWest1 = new ResourceRecordSetRegion("us-west-1");
/// <summary>
/// Constant UsWest2 for ResourceRecordSetRegion
/// </summary>
public static readonly ResourceRecordSetRegion UsWest2 = new ResourceRecordSetRegion("us-west-2");
/// <summary>
/// Default Constructor
/// </summary>
public ResourceRecordSetRegion(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ResourceRecordSetRegion FindValue(string value)
{
return FindValue<ResourceRecordSetRegion>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ResourceRecordSetRegion(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type RRType.
/// </summary>
public class RRType : ConstantClass
{
/// <summary>
/// Constant A for RRType
/// </summary>
public static readonly RRType A = new RRType("A");
/// <summary>
/// Constant AAAA for RRType
/// </summary>
public static readonly RRType AAAA = new RRType("AAAA");
/// <summary>
/// Constant CNAME for RRType
/// </summary>
public static readonly RRType CNAME = new RRType("CNAME");
/// <summary>
/// Constant MX for RRType
/// </summary>
public static readonly RRType MX = new RRType("MX");
/// <summary>
/// Constant NS for RRType
/// </summary>
public static readonly RRType NS = new RRType("NS");
/// <summary>
/// Constant PTR for RRType
/// </summary>
public static readonly RRType PTR = new RRType("PTR");
/// <summary>
/// Constant SOA for RRType
/// </summary>
public static readonly RRType SOA = new RRType("SOA");
/// <summary>
/// Constant SPF for RRType
/// </summary>
public static readonly RRType SPF = new RRType("SPF");
/// <summary>
/// Constant SRV for RRType
/// </summary>
public static readonly RRType SRV = new RRType("SRV");
/// <summary>
/// Constant TXT for RRType
/// </summary>
public static readonly RRType TXT = new RRType("TXT");
/// <summary>
/// Default Constructor
/// </summary>
public RRType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static RRType FindValue(string value)
{
return FindValue<RRType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator RRType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type TagResourceType.
/// </summary>
public class TagResourceType : ConstantClass
{
/// <summary>
/// Constant Healthcheck for TagResourceType
/// </summary>
public static readonly TagResourceType Healthcheck = new TagResourceType("healthcheck");
/// <summary>
/// Constant Hostedzone for TagResourceType
/// </summary>
public static readonly TagResourceType Hostedzone = new TagResourceType("hostedzone");
/// <summary>
/// Default Constructor
/// </summary>
public TagResourceType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static TagResourceType FindValue(string value)
{
return FindValue<TagResourceType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator TagResourceType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type VPCRegion.
/// </summary>
public class VPCRegion : ConstantClass
{
/// <summary>
/// Constant ApNortheast1 for VPCRegion
/// </summary>
public static readonly VPCRegion ApNortheast1 = new VPCRegion("ap-northeast-1");
/// <summary>
/// Constant ApSoutheast1 for VPCRegion
/// </summary>
public static readonly VPCRegion ApSoutheast1 = new VPCRegion("ap-southeast-1");
/// <summary>
/// Constant ApSoutheast2 for VPCRegion
/// </summary>
public static readonly VPCRegion ApSoutheast2 = new VPCRegion("ap-southeast-2");
/// <summary>
/// Constant CnNorth1 for VPCRegion
/// </summary>
public static readonly VPCRegion CnNorth1 = new VPCRegion("cn-north-1");
/// <summary>
/// Constant EuCentral1 for VPCRegion
/// </summary>
public static readonly VPCRegion EuCentral1 = new VPCRegion("eu-central-1");
/// <summary>
/// Constant EuWest1 for VPCRegion
/// </summary>
public static readonly VPCRegion EuWest1 = new VPCRegion("eu-west-1");
/// <summary>
/// Constant SaEast1 for VPCRegion
/// </summary>
public static readonly VPCRegion SaEast1 = new VPCRegion("sa-east-1");
/// <summary>
/// Constant UsEast1 for VPCRegion
/// </summary>
public static readonly VPCRegion UsEast1 = new VPCRegion("us-east-1");
/// <summary>
/// Constant UsWest1 for VPCRegion
/// </summary>
public static readonly VPCRegion UsWest1 = new VPCRegion("us-west-1");
/// <summary>
/// Constant UsWest2 for VPCRegion
/// </summary>
public static readonly VPCRegion UsWest2 = new VPCRegion("us-west-2");
/// <summary>
/// Default Constructor
/// </summary>
public VPCRegion(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static VPCRegion FindValue(string value)
{
return FindValue<VPCRegion>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator VPCRegion(string value)
{
return FindValue(value);
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic{
/// <summary>
/// Strongly-typed collection for the VwAspnetMembershipUser class.
/// </summary>
[Serializable]
public partial class VwAspnetMembershipUserCollection : ReadOnlyList<VwAspnetMembershipUser, VwAspnetMembershipUserCollection>
{
public VwAspnetMembershipUserCollection() {}
}
/// <summary>
/// This is Read-only wrapper class for the vw_aspnet_MembershipUsers view.
/// </summary>
[Serializable]
public partial class VwAspnetMembershipUser : ReadOnlyRecord<VwAspnetMembershipUser>, IReadOnlyRecord
{
#region Default Settings
protected static void SetSQLProps()
{
GetTableSchema();
}
#endregion
#region Schema Accessor
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
{
SetSQLProps();
}
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("vw_aspnet_MembershipUsers", TableType.View, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarUserId = new TableSchema.TableColumn(schema);
colvarUserId.ColumnName = "UserId";
colvarUserId.DataType = DbType.Guid;
colvarUserId.MaxLength = 0;
colvarUserId.AutoIncrement = false;
colvarUserId.IsNullable = false;
colvarUserId.IsPrimaryKey = false;
colvarUserId.IsForeignKey = false;
colvarUserId.IsReadOnly = false;
schema.Columns.Add(colvarUserId);
TableSchema.TableColumn colvarPasswordFormat = new TableSchema.TableColumn(schema);
colvarPasswordFormat.ColumnName = "PasswordFormat";
colvarPasswordFormat.DataType = DbType.Int32;
colvarPasswordFormat.MaxLength = 0;
colvarPasswordFormat.AutoIncrement = false;
colvarPasswordFormat.IsNullable = false;
colvarPasswordFormat.IsPrimaryKey = false;
colvarPasswordFormat.IsForeignKey = false;
colvarPasswordFormat.IsReadOnly = false;
schema.Columns.Add(colvarPasswordFormat);
TableSchema.TableColumn colvarMobilePIN = new TableSchema.TableColumn(schema);
colvarMobilePIN.ColumnName = "MobilePIN";
colvarMobilePIN.DataType = DbType.String;
colvarMobilePIN.MaxLength = 16;
colvarMobilePIN.AutoIncrement = false;
colvarMobilePIN.IsNullable = true;
colvarMobilePIN.IsPrimaryKey = false;
colvarMobilePIN.IsForeignKey = false;
colvarMobilePIN.IsReadOnly = false;
schema.Columns.Add(colvarMobilePIN);
TableSchema.TableColumn colvarEmail = new TableSchema.TableColumn(schema);
colvarEmail.ColumnName = "Email";
colvarEmail.DataType = DbType.String;
colvarEmail.MaxLength = 256;
colvarEmail.AutoIncrement = false;
colvarEmail.IsNullable = true;
colvarEmail.IsPrimaryKey = false;
colvarEmail.IsForeignKey = false;
colvarEmail.IsReadOnly = false;
schema.Columns.Add(colvarEmail);
TableSchema.TableColumn colvarLoweredEmail = new TableSchema.TableColumn(schema);
colvarLoweredEmail.ColumnName = "LoweredEmail";
colvarLoweredEmail.DataType = DbType.String;
colvarLoweredEmail.MaxLength = 256;
colvarLoweredEmail.AutoIncrement = false;
colvarLoweredEmail.IsNullable = true;
colvarLoweredEmail.IsPrimaryKey = false;
colvarLoweredEmail.IsForeignKey = false;
colvarLoweredEmail.IsReadOnly = false;
schema.Columns.Add(colvarLoweredEmail);
TableSchema.TableColumn colvarPasswordQuestion = new TableSchema.TableColumn(schema);
colvarPasswordQuestion.ColumnName = "PasswordQuestion";
colvarPasswordQuestion.DataType = DbType.String;
colvarPasswordQuestion.MaxLength = 256;
colvarPasswordQuestion.AutoIncrement = false;
colvarPasswordQuestion.IsNullable = true;
colvarPasswordQuestion.IsPrimaryKey = false;
colvarPasswordQuestion.IsForeignKey = false;
colvarPasswordQuestion.IsReadOnly = false;
schema.Columns.Add(colvarPasswordQuestion);
TableSchema.TableColumn colvarPasswordAnswer = new TableSchema.TableColumn(schema);
colvarPasswordAnswer.ColumnName = "PasswordAnswer";
colvarPasswordAnswer.DataType = DbType.String;
colvarPasswordAnswer.MaxLength = 128;
colvarPasswordAnswer.AutoIncrement = false;
colvarPasswordAnswer.IsNullable = true;
colvarPasswordAnswer.IsPrimaryKey = false;
colvarPasswordAnswer.IsForeignKey = false;
colvarPasswordAnswer.IsReadOnly = false;
schema.Columns.Add(colvarPasswordAnswer);
TableSchema.TableColumn colvarIsApproved = new TableSchema.TableColumn(schema);
colvarIsApproved.ColumnName = "IsApproved";
colvarIsApproved.DataType = DbType.Boolean;
colvarIsApproved.MaxLength = 0;
colvarIsApproved.AutoIncrement = false;
colvarIsApproved.IsNullable = false;
colvarIsApproved.IsPrimaryKey = false;
colvarIsApproved.IsForeignKey = false;
colvarIsApproved.IsReadOnly = false;
schema.Columns.Add(colvarIsApproved);
TableSchema.TableColumn colvarIsLockedOut = new TableSchema.TableColumn(schema);
colvarIsLockedOut.ColumnName = "IsLockedOut";
colvarIsLockedOut.DataType = DbType.Boolean;
colvarIsLockedOut.MaxLength = 0;
colvarIsLockedOut.AutoIncrement = false;
colvarIsLockedOut.IsNullable = false;
colvarIsLockedOut.IsPrimaryKey = false;
colvarIsLockedOut.IsForeignKey = false;
colvarIsLockedOut.IsReadOnly = false;
schema.Columns.Add(colvarIsLockedOut);
TableSchema.TableColumn colvarCreateDate = new TableSchema.TableColumn(schema);
colvarCreateDate.ColumnName = "CreateDate";
colvarCreateDate.DataType = DbType.DateTime;
colvarCreateDate.MaxLength = 0;
colvarCreateDate.AutoIncrement = false;
colvarCreateDate.IsNullable = false;
colvarCreateDate.IsPrimaryKey = false;
colvarCreateDate.IsForeignKey = false;
colvarCreateDate.IsReadOnly = false;
schema.Columns.Add(colvarCreateDate);
TableSchema.TableColumn colvarLastLoginDate = new TableSchema.TableColumn(schema);
colvarLastLoginDate.ColumnName = "LastLoginDate";
colvarLastLoginDate.DataType = DbType.DateTime;
colvarLastLoginDate.MaxLength = 0;
colvarLastLoginDate.AutoIncrement = false;
colvarLastLoginDate.IsNullable = false;
colvarLastLoginDate.IsPrimaryKey = false;
colvarLastLoginDate.IsForeignKey = false;
colvarLastLoginDate.IsReadOnly = false;
schema.Columns.Add(colvarLastLoginDate);
TableSchema.TableColumn colvarLastPasswordChangedDate = new TableSchema.TableColumn(schema);
colvarLastPasswordChangedDate.ColumnName = "LastPasswordChangedDate";
colvarLastPasswordChangedDate.DataType = DbType.DateTime;
colvarLastPasswordChangedDate.MaxLength = 0;
colvarLastPasswordChangedDate.AutoIncrement = false;
colvarLastPasswordChangedDate.IsNullable = false;
colvarLastPasswordChangedDate.IsPrimaryKey = false;
colvarLastPasswordChangedDate.IsForeignKey = false;
colvarLastPasswordChangedDate.IsReadOnly = false;
schema.Columns.Add(colvarLastPasswordChangedDate);
TableSchema.TableColumn colvarLastLockoutDate = new TableSchema.TableColumn(schema);
colvarLastLockoutDate.ColumnName = "LastLockoutDate";
colvarLastLockoutDate.DataType = DbType.DateTime;
colvarLastLockoutDate.MaxLength = 0;
colvarLastLockoutDate.AutoIncrement = false;
colvarLastLockoutDate.IsNullable = false;
colvarLastLockoutDate.IsPrimaryKey = false;
colvarLastLockoutDate.IsForeignKey = false;
colvarLastLockoutDate.IsReadOnly = false;
schema.Columns.Add(colvarLastLockoutDate);
TableSchema.TableColumn colvarFailedPasswordAttemptCount = new TableSchema.TableColumn(schema);
colvarFailedPasswordAttemptCount.ColumnName = "FailedPasswordAttemptCount";
colvarFailedPasswordAttemptCount.DataType = DbType.Int32;
colvarFailedPasswordAttemptCount.MaxLength = 0;
colvarFailedPasswordAttemptCount.AutoIncrement = false;
colvarFailedPasswordAttemptCount.IsNullable = false;
colvarFailedPasswordAttemptCount.IsPrimaryKey = false;
colvarFailedPasswordAttemptCount.IsForeignKey = false;
colvarFailedPasswordAttemptCount.IsReadOnly = false;
schema.Columns.Add(colvarFailedPasswordAttemptCount);
TableSchema.TableColumn colvarFailedPasswordAttemptWindowStart = new TableSchema.TableColumn(schema);
colvarFailedPasswordAttemptWindowStart.ColumnName = "FailedPasswordAttemptWindowStart";
colvarFailedPasswordAttemptWindowStart.DataType = DbType.DateTime;
colvarFailedPasswordAttemptWindowStart.MaxLength = 0;
colvarFailedPasswordAttemptWindowStart.AutoIncrement = false;
colvarFailedPasswordAttemptWindowStart.IsNullable = false;
colvarFailedPasswordAttemptWindowStart.IsPrimaryKey = false;
colvarFailedPasswordAttemptWindowStart.IsForeignKey = false;
colvarFailedPasswordAttemptWindowStart.IsReadOnly = false;
schema.Columns.Add(colvarFailedPasswordAttemptWindowStart);
TableSchema.TableColumn colvarFailedPasswordAnswerAttemptCount = new TableSchema.TableColumn(schema);
colvarFailedPasswordAnswerAttemptCount.ColumnName = "FailedPasswordAnswerAttemptCount";
colvarFailedPasswordAnswerAttemptCount.DataType = DbType.Int32;
colvarFailedPasswordAnswerAttemptCount.MaxLength = 0;
colvarFailedPasswordAnswerAttemptCount.AutoIncrement = false;
colvarFailedPasswordAnswerAttemptCount.IsNullable = false;
colvarFailedPasswordAnswerAttemptCount.IsPrimaryKey = false;
colvarFailedPasswordAnswerAttemptCount.IsForeignKey = false;
colvarFailedPasswordAnswerAttemptCount.IsReadOnly = false;
schema.Columns.Add(colvarFailedPasswordAnswerAttemptCount);
TableSchema.TableColumn colvarFailedPasswordAnswerAttemptWindowStart = new TableSchema.TableColumn(schema);
colvarFailedPasswordAnswerAttemptWindowStart.ColumnName = "FailedPasswordAnswerAttemptWindowStart";
colvarFailedPasswordAnswerAttemptWindowStart.DataType = DbType.DateTime;
colvarFailedPasswordAnswerAttemptWindowStart.MaxLength = 0;
colvarFailedPasswordAnswerAttemptWindowStart.AutoIncrement = false;
colvarFailedPasswordAnswerAttemptWindowStart.IsNullable = false;
colvarFailedPasswordAnswerAttemptWindowStart.IsPrimaryKey = false;
colvarFailedPasswordAnswerAttemptWindowStart.IsForeignKey = false;
colvarFailedPasswordAnswerAttemptWindowStart.IsReadOnly = false;
schema.Columns.Add(colvarFailedPasswordAnswerAttemptWindowStart);
TableSchema.TableColumn colvarComment = new TableSchema.TableColumn(schema);
colvarComment.ColumnName = "Comment";
colvarComment.DataType = DbType.String;
colvarComment.MaxLength = 1073741823;
colvarComment.AutoIncrement = false;
colvarComment.IsNullable = true;
colvarComment.IsPrimaryKey = false;
colvarComment.IsForeignKey = false;
colvarComment.IsReadOnly = false;
schema.Columns.Add(colvarComment);
TableSchema.TableColumn colvarApplicationId = new TableSchema.TableColumn(schema);
colvarApplicationId.ColumnName = "ApplicationId";
colvarApplicationId.DataType = DbType.Guid;
colvarApplicationId.MaxLength = 0;
colvarApplicationId.AutoIncrement = false;
colvarApplicationId.IsNullable = false;
colvarApplicationId.IsPrimaryKey = false;
colvarApplicationId.IsForeignKey = false;
colvarApplicationId.IsReadOnly = false;
schema.Columns.Add(colvarApplicationId);
TableSchema.TableColumn colvarUserName = new TableSchema.TableColumn(schema);
colvarUserName.ColumnName = "UserName";
colvarUserName.DataType = DbType.String;
colvarUserName.MaxLength = 256;
colvarUserName.AutoIncrement = false;
colvarUserName.IsNullable = false;
colvarUserName.IsPrimaryKey = false;
colvarUserName.IsForeignKey = false;
colvarUserName.IsReadOnly = false;
schema.Columns.Add(colvarUserName);
TableSchema.TableColumn colvarMobileAlias = new TableSchema.TableColumn(schema);
colvarMobileAlias.ColumnName = "MobileAlias";
colvarMobileAlias.DataType = DbType.String;
colvarMobileAlias.MaxLength = 16;
colvarMobileAlias.AutoIncrement = false;
colvarMobileAlias.IsNullable = true;
colvarMobileAlias.IsPrimaryKey = false;
colvarMobileAlias.IsForeignKey = false;
colvarMobileAlias.IsReadOnly = false;
schema.Columns.Add(colvarMobileAlias);
TableSchema.TableColumn colvarIsAnonymous = new TableSchema.TableColumn(schema);
colvarIsAnonymous.ColumnName = "IsAnonymous";
colvarIsAnonymous.DataType = DbType.Boolean;
colvarIsAnonymous.MaxLength = 0;
colvarIsAnonymous.AutoIncrement = false;
colvarIsAnonymous.IsNullable = false;
colvarIsAnonymous.IsPrimaryKey = false;
colvarIsAnonymous.IsForeignKey = false;
colvarIsAnonymous.IsReadOnly = false;
schema.Columns.Add(colvarIsAnonymous);
TableSchema.TableColumn colvarLastActivityDate = new TableSchema.TableColumn(schema);
colvarLastActivityDate.ColumnName = "LastActivityDate";
colvarLastActivityDate.DataType = DbType.DateTime;
colvarLastActivityDate.MaxLength = 0;
colvarLastActivityDate.AutoIncrement = false;
colvarLastActivityDate.IsNullable = false;
colvarLastActivityDate.IsPrimaryKey = false;
colvarLastActivityDate.IsForeignKey = false;
colvarLastActivityDate.IsReadOnly = false;
schema.Columns.Add(colvarLastActivityDate);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("vw_aspnet_MembershipUsers",schema);
}
}
#endregion
#region Query Accessor
public static Query CreateQuery()
{
return new Query(Schema);
}
#endregion
#region .ctors
public VwAspnetMembershipUser()
{
SetSQLProps();
SetDefaults();
MarkNew();
}
public VwAspnetMembershipUser(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
{
ForceDefaults();
}
MarkNew();
}
public VwAspnetMembershipUser(object keyID)
{
SetSQLProps();
LoadByKey(keyID);
}
public VwAspnetMembershipUser(string columnName, object columnValue)
{
SetSQLProps();
LoadByParam(columnName,columnValue);
}
#endregion
#region Props
[XmlAttribute("UserId")]
[Bindable(true)]
public Guid UserId
{
get
{
return GetColumnValue<Guid>("UserId");
}
set
{
SetColumnValue("UserId", value);
}
}
[XmlAttribute("PasswordFormat")]
[Bindable(true)]
public int PasswordFormat
{
get
{
return GetColumnValue<int>("PasswordFormat");
}
set
{
SetColumnValue("PasswordFormat", value);
}
}
[XmlAttribute("MobilePIN")]
[Bindable(true)]
public string MobilePIN
{
get
{
return GetColumnValue<string>("MobilePIN");
}
set
{
SetColumnValue("MobilePIN", value);
}
}
[XmlAttribute("Email")]
[Bindable(true)]
public string Email
{
get
{
return GetColumnValue<string>("Email");
}
set
{
SetColumnValue("Email", value);
}
}
[XmlAttribute("LoweredEmail")]
[Bindable(true)]
public string LoweredEmail
{
get
{
return GetColumnValue<string>("LoweredEmail");
}
set
{
SetColumnValue("LoweredEmail", value);
}
}
[XmlAttribute("PasswordQuestion")]
[Bindable(true)]
public string PasswordQuestion
{
get
{
return GetColumnValue<string>("PasswordQuestion");
}
set
{
SetColumnValue("PasswordQuestion", value);
}
}
[XmlAttribute("PasswordAnswer")]
[Bindable(true)]
public string PasswordAnswer
{
get
{
return GetColumnValue<string>("PasswordAnswer");
}
set
{
SetColumnValue("PasswordAnswer", value);
}
}
[XmlAttribute("IsApproved")]
[Bindable(true)]
public bool IsApproved
{
get
{
return GetColumnValue<bool>("IsApproved");
}
set
{
SetColumnValue("IsApproved", value);
}
}
[XmlAttribute("IsLockedOut")]
[Bindable(true)]
public bool IsLockedOut
{
get
{
return GetColumnValue<bool>("IsLockedOut");
}
set
{
SetColumnValue("IsLockedOut", value);
}
}
[XmlAttribute("CreateDate")]
[Bindable(true)]
public DateTime CreateDate
{
get
{
return GetColumnValue<DateTime>("CreateDate");
}
set
{
SetColumnValue("CreateDate", value);
}
}
[XmlAttribute("LastLoginDate")]
[Bindable(true)]
public DateTime LastLoginDate
{
get
{
return GetColumnValue<DateTime>("LastLoginDate");
}
set
{
SetColumnValue("LastLoginDate", value);
}
}
[XmlAttribute("LastPasswordChangedDate")]
[Bindable(true)]
public DateTime LastPasswordChangedDate
{
get
{
return GetColumnValue<DateTime>("LastPasswordChangedDate");
}
set
{
SetColumnValue("LastPasswordChangedDate", value);
}
}
[XmlAttribute("LastLockoutDate")]
[Bindable(true)]
public DateTime LastLockoutDate
{
get
{
return GetColumnValue<DateTime>("LastLockoutDate");
}
set
{
SetColumnValue("LastLockoutDate", value);
}
}
[XmlAttribute("FailedPasswordAttemptCount")]
[Bindable(true)]
public int FailedPasswordAttemptCount
{
get
{
return GetColumnValue<int>("FailedPasswordAttemptCount");
}
set
{
SetColumnValue("FailedPasswordAttemptCount", value);
}
}
[XmlAttribute("FailedPasswordAttemptWindowStart")]
[Bindable(true)]
public DateTime FailedPasswordAttemptWindowStart
{
get
{
return GetColumnValue<DateTime>("FailedPasswordAttemptWindowStart");
}
set
{
SetColumnValue("FailedPasswordAttemptWindowStart", value);
}
}
[XmlAttribute("FailedPasswordAnswerAttemptCount")]
[Bindable(true)]
public int FailedPasswordAnswerAttemptCount
{
get
{
return GetColumnValue<int>("FailedPasswordAnswerAttemptCount");
}
set
{
SetColumnValue("FailedPasswordAnswerAttemptCount", value);
}
}
[XmlAttribute("FailedPasswordAnswerAttemptWindowStart")]
[Bindable(true)]
public DateTime FailedPasswordAnswerAttemptWindowStart
{
get
{
return GetColumnValue<DateTime>("FailedPasswordAnswerAttemptWindowStart");
}
set
{
SetColumnValue("FailedPasswordAnswerAttemptWindowStart", value);
}
}
[XmlAttribute("Comment")]
[Bindable(true)]
public string Comment
{
get
{
return GetColumnValue<string>("Comment");
}
set
{
SetColumnValue("Comment", value);
}
}
[XmlAttribute("ApplicationId")]
[Bindable(true)]
public Guid ApplicationId
{
get
{
return GetColumnValue<Guid>("ApplicationId");
}
set
{
SetColumnValue("ApplicationId", value);
}
}
[XmlAttribute("UserName")]
[Bindable(true)]
public string UserName
{
get
{
return GetColumnValue<string>("UserName");
}
set
{
SetColumnValue("UserName", value);
}
}
[XmlAttribute("MobileAlias")]
[Bindable(true)]
public string MobileAlias
{
get
{
return GetColumnValue<string>("MobileAlias");
}
set
{
SetColumnValue("MobileAlias", value);
}
}
[XmlAttribute("IsAnonymous")]
[Bindable(true)]
public bool IsAnonymous
{
get
{
return GetColumnValue<bool>("IsAnonymous");
}
set
{
SetColumnValue("IsAnonymous", value);
}
}
[XmlAttribute("LastActivityDate")]
[Bindable(true)]
public DateTime LastActivityDate
{
get
{
return GetColumnValue<DateTime>("LastActivityDate");
}
set
{
SetColumnValue("LastActivityDate", value);
}
}
#endregion
#region Columns Struct
public struct Columns
{
public static string UserId = @"UserId";
public static string PasswordFormat = @"PasswordFormat";
public static string MobilePIN = @"MobilePIN";
public static string Email = @"Email";
public static string LoweredEmail = @"LoweredEmail";
public static string PasswordQuestion = @"PasswordQuestion";
public static string PasswordAnswer = @"PasswordAnswer";
public static string IsApproved = @"IsApproved";
public static string IsLockedOut = @"IsLockedOut";
public static string CreateDate = @"CreateDate";
public static string LastLoginDate = @"LastLoginDate";
public static string LastPasswordChangedDate = @"LastPasswordChangedDate";
public static string LastLockoutDate = @"LastLockoutDate";
public static string FailedPasswordAttemptCount = @"FailedPasswordAttemptCount";
public static string FailedPasswordAttemptWindowStart = @"FailedPasswordAttemptWindowStart";
public static string FailedPasswordAnswerAttemptCount = @"FailedPasswordAnswerAttemptCount";
public static string FailedPasswordAnswerAttemptWindowStart = @"FailedPasswordAnswerAttemptWindowStart";
public static string Comment = @"Comment";
public static string ApplicationId = @"ApplicationId";
public static string UserName = @"UserName";
public static string MobileAlias = @"MobileAlias";
public static string IsAnonymous = @"IsAnonymous";
public static string LastActivityDate = @"LastActivityDate";
}
#endregion
#region IAbstractRecord Members
public new CT GetColumnValue<CT>(string columnName) {
return base.GetColumnValue<CT>(columnName);
}
public object GetColumnValue(string columnName) {
return base.GetColumnValue<object>(columnName);
}
#endregion
}
}
| |
namespace Nancy.Tests.Unit
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using FakeItEasy;
using Nancy.Helpers;
using Nancy.IO;
using Xunit;
using Xunit.Extensions;
public class RequestFixture
{
[Fact]
public void Should_dispose_request_stream_when_being_disposed()
{
// Given
var stream = A.Fake<RequestStream>(x =>
{
x.Implements(typeof(IDisposable));
x.WithArgumentsForConstructor(() => new RequestStream(0, false));
});
var url = new Url()
{
Scheme = "http",
Path = "localhost"
};
var request = new Request("GET", url, stream);
// When
request.Dispose();
// Then
A.CallTo(() => ((IDisposable)stream).Dispose()).MustHaveHappened();
}
[Fact]
public void Should_be_disposable()
{
// Given, When, Then
typeof(Request).ShouldImplementInterface<IDisposable>();
}
[Fact]
public void Should_override_request_method_on_post()
{
// Given
const string bodyContent = "_method=GET";
var memory = CreateRequestStream();
var writer = new StreamWriter(memory);
writer.Write(bodyContent);
writer.Flush();
memory.Position = 0;
var headers =
new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "application/x-www-form-urlencoded" } } };
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, memory, headers);
// Then
request.Method.ShouldEqual("GET");
}
[Theory]
[InlineData("GET")]
[InlineData("PUT")]
[InlineData("DELETE")]
[InlineData("HEAD")]
public void Should_only_override_method_on_post(string method)
{
// Given
const string bodyContent = "_method=TEST";
var memory = CreateRequestStream();
var writer = new StreamWriter(memory);
writer.Write(bodyContent);
writer.Flush();
memory.Position = 0;
var headers =
new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "application/x-www-form-urlencoded" } } };
// When
var request = new Request(method, new Url { Path = "/", Scheme = "http" }, memory, headers);
// Then
request.Method.ShouldEqual(method);
}
[Fact]
public void Should_throw_argumentoutofrangeexception_when_initialized_with_null_method()
{
// Given, When
var exception =
Record.Exception(() => new Request(null, "/", "http"));
// Then
exception.ShouldBeOfType<ArgumentOutOfRangeException>();
}
[Fact]
public void Should_throw_argumentoutofrangeexception_when_initialized_with_empty_method()
{
// Given, When
var exception =
Record.Exception(() => new Request(string.Empty, "/", "http"));
// Then
exception.ShouldBeOfType<ArgumentOutOfRangeException>();
}
[Fact]
public void Should_throw_null_exception_when_initialized_with_null_uri()
{
// Given, When
var exception =
Record.Exception(() => new Request("GET", null, "http"));
// Then
exception.ShouldBeOfType<ArgumentNullException>();
}
[Fact]
public void Should_set_method_parameter_value_to_method_property_when_initialized()
{
// Given
const string method = "GET";
// When
var request = new Request(method, "/", "http");
// Then
request.Method.ShouldEqual(method);
}
[Fact]
public void Should_set_uri_parameter_value_to_uri_property_when_initialized()
{
// Given
const string path = "/";
// When
var request = new Request("GET", path, "http");
// Then
request.Path.ShouldEqual(path);
}
[Fact]
public void Should_set_header_parameter_value_to_header_property_when_initialized()
{
// Given
var headers = new Dictionary<string, IEnumerable<string>>()
{
{ "content-type", new[] {"foo/bar"} }
};
// When
var request = new Request("GET", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(), headers);
// Then
request.Headers.ContentType.ShouldNotBeNull();
}
[Fact]
public void Should_set_body_parameter_value_to_body_property_when_initialized()
{
// Given
var body = CreateRequestStream();
// When
var request = new Request("GET", new Url { Path = "/", Scheme = "http" }, body, new Dictionary<string, IEnumerable<string>>());
// Then
request.Body.ShouldBeSameAs(body);
}
[Fact]
public void Should_set_extract_form_data_from_body_when_content_type_is_x_www_form_urlencoded()
{
// Given
const string bodyContent = "name=John+Doe&gender=male&family=5&city=kent&city=miami&other=abc%0D%0Adef&nickname=J%26D";
var memory = CreateRequestStream();
var writer = new StreamWriter(memory);
writer.Write(bodyContent);
writer.Flush();
memory.Position = 0;
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "application/x-www-form-urlencoded" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, memory, headers);
// Then
((string)request.Form.name).ShouldEqual("John Doe");
}
[Fact]
public void Should_set_extract_form_data_from_body_when_content_type_is_x_www_form_urlencoded_with_character_set()
{
// Given
const string bodyContent = "name=John+Doe&gender=male&family=5&city=kent&city=miami&other=abc%0D%0Adef&nickname=J%26D";
var memory = CreateRequestStream();
var writer = new StreamWriter(memory);
writer.Write(bodyContent);
writer.Flush();
memory.Position = 0;
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "application/x-www-form-urlencoded; charset=UTF-8" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, memory, headers);
// Then
((string)request.Form.name).ShouldEqual("John Doe");
}
[Fact]
public void Should_set_extracted_form_data_from_body_when_content_type_is_multipart_form_data()
{
// Given
var memory =
new MemoryStream(BuildMultipartFormValues(new Dictionary<string, string>
{
{ "name", "John Doe"},
{ "age", "42"}
}));
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers);
// Then
((string)request.Form.name).ShouldEqual("John Doe");
((string)request.Form.age).ShouldEqual("42");
}
[Fact]
public void Should_respect_case_insensitivity_when_extracting_form_data_from_body_when_content_type_is_x_www_form_urlencoded()
{
// Given
StaticConfiguration.CaseSensitive = false;
const string bodyContent = "key=value&key=value&KEY=VALUE";
var memory = CreateRequestStream();
var writer = new StreamWriter(memory);
writer.Write(bodyContent);
writer.Flush();
memory.Position = 0;
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "application/x-www-form-urlencoded" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, memory, headers);
// Then
((string)request.Form.key).ShouldEqual("value,value,VALUE");
((string)request.Form.KEY).ShouldEqual("value,value,VALUE");
}
[Fact]
public void Should_respect_case_sensitivity_when_extracting_form_data_from_body_when_content_type_is_x_www_form_urlencoded()
{
// Given
StaticConfiguration.CaseSensitive = true;
const string bodyContent = "key=value&key=value&KEY=VALUE";
var memory = CreateRequestStream();
var writer = new StreamWriter(memory);
writer.Write(bodyContent);
writer.Flush();
memory.Position = 0;
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "application/x-www-form-urlencoded" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, memory, headers);
// Then
((string)request.Form.key).ShouldEqual("value,value");
((string)request.Form.KEY).ShouldEqual("VALUE");
}
[Fact]
public void Should_respect_case_insensitivity_when_extracting_form_data_from_body_when_content_type_is_multipart_form_data()
{
// Given
StaticConfiguration.CaseSensitive = false;
var memory =
new MemoryStream(BuildMultipartFormValues(new Dictionary<string, string>(StringComparer.Ordinal)
{
{ "key", "value" },
{ "KEY", "VALUE" }
}));
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers);
// Then
((string)request.Form.key).ShouldEqual("value,VALUE");
((string)request.Form.KEY).ShouldEqual("value,VALUE");
}
[Fact]
public void Should_respect_case_sensitivity_when_extracting_form_data_from_body_when_content_type_is_multipart_form_data()
{
// Given
StaticConfiguration.CaseSensitive = true;
var memory =
new MemoryStream(BuildMultipartFormValues(new Dictionary<string, string>(StringComparer.Ordinal)
{
{ "key", "value" },
{ "KEY", "VALUE" }
}));
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers);
// Then
((string)request.Form.key).ShouldEqual("value");
((string)request.Form.KEY).ShouldEqual("VALUE");
}
[Fact]
public void Should_set_extracted_files_to_files_collection_when_body_content_type_is_multipart_form_data()
{
// Given
var memory =
new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>>
{
{ "test", new Tuple<string, string, string>("content/type", "some test content", "whatever")}
}));
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers);
// Then
request.Files.ShouldHaveCount(1);
}
[Fact]
public void Should_set_content_type_on_file_extracted_from_multipart_form_data_body()
{
// Given
var memory =
new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>>
{
{ "sample.txt", new Tuple<string, string, string>("content/type", "some test content", "whatever")}
}));
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers);
// Then
request.Files.First().ContentType.ShouldEqual("content/type");
}
[Fact]
public void Should_set_name_on_file_extracted_from_multipart_form_data_body()
{
// Given
var memory =
new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>>
{
{ "sample.txt", new Tuple<string, string, string>("content/type", "some test content", "whatever")}
}));
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers);
// Then
request.Files.First().Name.ShouldEqual("sample.txt");
}
[Fact]
public void Should_value_on_file_extracted_from_multipart_form_data_body()
{
// Given
var memory =
new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>>
{
{ "sample.txt", new Tuple<string, string, string>("content/type", "some test content", "whatever")}
}));
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers);
// Then
GetStringValue(request.Files.First().Value).ShouldEqual("some test content");
}
[Fact]
public void Should_set_key_on_file_extracted_from_multipart_data_body()
{
// Given
var memory =
new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>>
{
{ "sample.txt", new Tuple<string, string, string>("content/type", "some test content", "fieldname")}
}));
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers);
// Then
request.Files.First().Key.ShouldEqual("fieldname");
}
private static string GetStringValue(Stream stream)
{
var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
[Fact]
public void Should_be_able_to_invoke_form_repeatedly()
{
const string bodyContent = "name=John+Doe&gender=male&family=5&city=kent&city=miami&other=abc%0D%0Adef&nickname=J%26D";
var memory = new MemoryStream();
var writer = new StreamWriter(memory);
writer.Write(bodyContent);
writer.Flush();
memory.Position = 0;
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "application/x-www-form-urlencoded" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers);
// Then
((string)request.Form.name).ShouldEqual("John Doe");
}
[Fact]
public void Should_throw_argumentoutofrangeexception_when_initialized_with_null_protocol()
{
// Given, When
var exception =
Record.Exception(() => new Request("GET", "/", null));
// Then
exception.ShouldBeOfType<ArgumentOutOfRangeException>();
}
[Fact]
public void Should_throw_argumentoutofrangeexception_when_initialized_with_an_empty_protocol()
{
// Given, When
var exception =
Record.Exception(() => new Request("GET", "/", string.Empty));
// Then
exception.ShouldBeOfType<ArgumentOutOfRangeException>();
}
[Fact]
public void Should_set_protocol_parameter_value_to_protocol_property_when_initialized()
{
// Given
const string protocol = "http";
// When
var request = new Request("GET", "/", protocol);
// Then
request.Url.Scheme.ShouldEqual(protocol);
}
[Fact]
public void Should_split_cookie_in_two_parts_only()
{
// Given, when
var cookieName = "_nc";
var cookieData = "Y+M3rcC/7ssXvHTx9pwCbwQVV4g=sp0hUZVApYgGbKZIU4bvXbBCVl9fhSEssEXSGdrt4jVag6PO1oed8lSd+EJD1nzWx4OTTCTZKjYRWeHE97QVND4jJIl+DuKRgJnSl3hWI5gdgGjcxqCSTvMOMGmW3NHLVyKpajGD8tq1DXhXMyXHjTzrCAYl8TGzwyJJGx/gd7VMJeRbAy9JdHOxEUlCKUnPneWN6q+/ITFryAa5hAdfcjXmh4Fgym75whKOMkWO+yM2icdsciX0ShcvnEQ/bXcTHTya6d7dJVfZl7qQ8AgIQv8ucQHxD3NxIvHNPBwms2ClaPds0HG5N+7pu7eMSFZjUHpDrrCnFvYN+JDiG3GMpf98LuCCvxemvipJo2MUkY4J1LvaDFoWA5tIxAfItZJkSIW2d8JPDwFk8OHJy8zhyn8AjD2JFqWaUZr4y9KZOtgI0V0Qlq0mS3mDSlLn29xapgoPHBvykwQjR6TwF2pBLpStsfZa/tXbEv2mc3VO3CnErIA1lEfKNqn9C/Dw6hqW";
var headers = new Dictionary<string, IEnumerable<string>>();
var cookies = new List<string>();
cookies.Add(string.Format("{0}={1}", cookieName, HttpUtility.UrlEncode(cookieData)));
headers.Add("cookie", cookies);
var newUrl = new Url
{
Path = "/"
};
var request = new Request("GET", newUrl, null, headers);
// Then
request.Cookies[cookieName].ShouldEqual(cookieData);
}
[Fact]
public void Should_split_cookie_in_two_parts_with_secure_attribute()
{
// Given, when
const string cookieName = "path";
const string cookieData = "/";
var headers = new Dictionary<string, IEnumerable<string>>();
var cookies = new List<string> { string.Format("{0}={1}; Secure", cookieName, cookieData)} ;
headers.Add("cookie", cookies);
var newUrl = new Url
{
Path = "/"
};
var request = new Request("GET", newUrl, null, headers);
// Then
request.Cookies[cookieName].ShouldEqual(cookieData);
}
[Fact]
public void Should_split_cookie_in_two_parts_with_httponly_and_secure_attribute()
{
// Given, when
const string cookieName = "path";
const string cookieData = "/";
var headers = new Dictionary<string, IEnumerable<string>>();
var cookies = new List<string> { string.Format("{0}={1}; HttpOnly; Secure", cookieName, cookieData) };
headers.Add("cookie", cookies);
var newUrl = new Url
{
Path = "/"
};
var request = new Request("GET", newUrl, null, headers);
// Then
request.Cookies[cookieName].ShouldEqual(cookieData);
}
[Fact]
public void Should_split_cookie_in_two_parts_with_httponly_and_secure_attribute_ignoring_case()
{
// Given, when
const string cookieName = "path";
const string cookieData = "/";
var headers = new Dictionary<string, IEnumerable<string>>();
var cookies = new List<string> { string.Format("{0}={1}; httponly; secure", cookieName, cookieData) };
headers.Add("cookie", cookies);
var newUrl = new Url
{
Path = "/"
};
var request = new Request("GET", newUrl, null, headers);
// Then
request.Cookies[cookieName].ShouldEqual(cookieData);
}
[Fact]
public void Should_split_cookie_in_two_parts_with_httponly_attribute()
{
// Given, when
const string cookieName = "path";
const string cookieData = "/";
var headers = new Dictionary<string, IEnumerable<string>>();
var cookies = new List<string> { string.Format("{0}={1}; HttpOnly", cookieName, cookieData) };
headers.Add("cookie", cookies);
var newUrl = new Url
{
Path = "/"
};
var request = new Request("GET", newUrl, null, headers);
// Then
request.Cookies[cookieName].ShouldEqual(cookieData);
}
[Fact]
public void Should_add_attribute_in_cookie_as_empty_value()
{
// Given, when
const string cookieName = "path";
const string cookieData = "/";
const string cookieAttribute = "SomeAttribute";
var headers = new Dictionary<string, IEnumerable<string>>();
var cookies = new List<string> { string.Format("{0}={1}; {2}", cookieName, cookieData, cookieAttribute) };
headers.Add("cookie", cookies);
var newUrl = new Url
{
Path = "/"
};
var request = new Request("GET", newUrl, null, headers);
// Then
request.Cookies[cookieName].ShouldEqual(cookieData);
request.Cookies[cookieAttribute].ShouldEqual(string.Empty);
}
[Fact]
public void Should_move_request_body_position_to_zero_after_parsing_url_encoded_data()
{
// Given
const string bodyContent = "name=John+Doe&gender=male&family=5&city=kent&city=miami&other=abc%0D%0Adef&nickname=J%26D";
var memory = CreateRequestStream();
var writer = new StreamWriter(memory);
writer.Write(bodyContent);
writer.Flush();
memory.Position = 0;
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "application/x-www-form-urlencoded; charset=UTF-8" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, memory, headers);
// Then
memory.Position.ShouldEqual(0L);
}
[Fact]
public void Should_move_request_body_position_to_zero_after_parsing_multipart_encoded_data()
{
// Given
var memory =
new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>>
{
{ "sample.txt", new Tuple<string, string, string>("content/type", "some test content", "whatever")}
}));
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers);
// Then
memory.Position.ShouldEqual(0L);
}
[Fact]
public void Should_preserve_all_values_when_multiple_are_posted_using_same_name_after_parsing_multipart_encoded_data()
{
// Given
var memory =
new MemoryStream(BuildMultipartFormValues(
new KeyValuePair<string, string>("age", "32"),
new KeyValuePair<string, string>("age", "42"),
new KeyValuePair<string, string>("age", "52")
));
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers);
// Then
((string)request.Form.age).ShouldEqual("32,42,52");
}
[Fact]
public void Should_limit_the_amount_of_form_fields_parsed()
{
// Given
var sb = new StringBuilder();
for (int i = 0; i < StaticConfiguration.RequestQueryFormMultipartLimit + 10; i++)
{
if (i > 0)
{
sb.Append('&');
}
sb.AppendFormat("Field{0}=Value{0}", i);
}
var memory = CreateRequestStream();
var writer = new StreamWriter(memory);
writer.Write(sb.ToString());
writer.Flush();
memory.Position = 0;
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "application/x-www-form-urlencoded" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, memory, headers);
// Then
((IEnumerable<string>)request.Form.GetDynamicMemberNames()).Count().ShouldEqual(StaticConfiguration.RequestQueryFormMultipartLimit);
}
[Fact]
public void Should_limit_the_amount_of_querystring_fields_parsed()
{
// Given
var sb = new StringBuilder();
for (int i = 0; i < StaticConfiguration.RequestQueryFormMultipartLimit + 10; i++)
{
if (i > 0)
{
sb.Append('&');
}
sb.AppendFormat("Field{0}=Value{0}", i);
}
var memory = CreateRequestStream();
// When
var request = new Request("GET", new Url { Path = "/", Scheme = "http", Query = sb.ToString() }, memory, new Dictionary<string, IEnumerable<string>>());
// Then
((IEnumerable<string>)request.Query.GetDynamicMemberNames()).Count().ShouldEqual(StaticConfiguration.RequestQueryFormMultipartLimit);
}
[Fact]
public void Should_change_empty_path_to_root()
{
var request = new Request("GET", "", "http");
request.Path.ShouldEqual("/");
}
[Fact]
public void Should_replace_value_of_query_key_without_value_with_true()
{
// Given
var memory = CreateRequestStream();
// When
var request = new Request("GET", new Url { Path = "/", Scheme = "http", Query = "key1" }, memory);
// Then
((bool)request.Query.key1).ShouldBeTrue();
((string)request.Query.key1).ShouldEqual("key1");
}
[Fact]
public void Should_not_replace_equal_key_value_query_with_bool()
{
// Given
var memory = CreateRequestStream();
// When
var request = new Request("GET", new Url { Path = "/", Scheme = "http", Query = "key1=key1" }, memory);
// Then
ShouldAssertExtensions.ShouldBeOfType<string>(request.Query["key1"].Value);
}
[Fact]
public void Should_not_flush_underlying_stream_if_it_is_not_writable()
{
var largeStream = new NonWriteableStream(
new MemoryStream(new byte[1025]));
// Given
var memory = new RequestStream(largeStream, 1025, 1024, false);
// When
var exception = Record.Exception(() => new Request("POST", new Url { Path = "/", Scheme = "http" }, memory));
// Then
exception.ShouldBeNull();
}
private static RequestStream CreateRequestStream()
{
return CreateRequestStream(new MemoryStream());
}
private static RequestStream CreateRequestStream(Stream stream)
{
return RequestStream.FromStream(stream);
}
private static byte[] BuildMultipartFormValues(params KeyValuePair<string, string>[] values)
{
var boundaryBuilder = new StringBuilder();
foreach (var pair in values)
{
boundaryBuilder.Append('\r');
boundaryBuilder.Append('\n');
boundaryBuilder.Append("--");
boundaryBuilder.Append("----NancyFormBoundary");
boundaryBuilder.Append('\r');
boundaryBuilder.Append('\n');
boundaryBuilder.AppendFormat("Content-Disposition: form-data; name=\"{0}\"", pair.Key);
boundaryBuilder.Append('\r');
boundaryBuilder.Append('\n');
boundaryBuilder.Append('\r');
boundaryBuilder.Append('\n');
boundaryBuilder.Append(pair.Value);
}
boundaryBuilder.Append('\r');
boundaryBuilder.Append('\n');
boundaryBuilder.Append("------NancyFormBoundary--");
var bytes =
Encoding.ASCII.GetBytes(boundaryBuilder.ToString());
return bytes;
}
private static byte[] BuildMultipartFormValues(Dictionary<string, string> formValues)
{
var pairs =
formValues.Keys.Select(key => new KeyValuePair<string, string>(key, formValues[key]));
return BuildMultipartFormValues(pairs.ToArray());
}
private static byte[] BuildMultipartFileValues(Dictionary<string, Tuple<string, string, string>> formValues)
{
var boundaryBuilder = new StringBuilder();
foreach (var key in formValues.Keys)
{
boundaryBuilder.Append('\r');
boundaryBuilder.Append('\n');
boundaryBuilder.Append("--");
boundaryBuilder.Append("----NancyFormBoundary");
boundaryBuilder.Append('\r');
boundaryBuilder.Append('\n');
boundaryBuilder.AppendFormat("Content-Disposition: form-data; name=\"{1}\"; filename=\"{0}\"", key, formValues[key].Item3);
boundaryBuilder.Append('\r');
boundaryBuilder.Append('\n');
boundaryBuilder.AppendFormat("Content-Type: {0}", formValues[key].Item1);
boundaryBuilder.Append('\r');
boundaryBuilder.Append('\n');
boundaryBuilder.Append('\r');
boundaryBuilder.Append('\n');
boundaryBuilder.Append(formValues[key].Item2);
}
boundaryBuilder.Append('\r');
boundaryBuilder.Append('\n');
boundaryBuilder.Append("------NancyFormBoundary--");
var bytes =
Encoding.ASCII.GetBytes(boundaryBuilder.ToString());
return bytes;
}
private class NonWriteableStream : Stream
{
private readonly MemoryStream inner;
public NonWriteableStream(MemoryStream inner)
{
this.inner = inner;
}
public override void Flush()
{
throw new NotSupportedException();
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
throw new NotSupportedException();
}
public override int Read(byte[] buffer, int offset, int count)
{
return this.inner.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return this.inner.Seek(offset, origin);
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
throw new NotSupportedException();
}
public override void WriteByte(byte value)
{
throw new NotSupportedException();
}
public override bool CanRead
{
get { return this.inner.CanRead; }
}
public override bool CanSeek
{
get { return this.inner.CanSeek; }
}
public override bool CanWrite
{
get { return false; }
}
public override long Length
{
get { return this.inner.Length; }
}
public override long Position
{
get { return this.inner.Position; }
set { this.inner.Position = value; }
}
}
}
}
| |
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Markup;
namespace AdventureWorks.Shopper.Controls
{
public class AutoRotatingGridView : GridView
{
// Dependency Properties for portrait layout
public static readonly DependencyProperty PortraitItemTemplateProperty =
DependencyProperty.Register("PortraitItemTemplate", typeof(DataTemplate), typeof(AutoRotatingGridView), new PropertyMetadata(null));
public static readonly DependencyProperty PortraitItemsPanelProperty =
DependencyProperty.Register("PortraitItemsPanel", typeof(ItemsPanelTemplate), typeof(AutoRotatingGridView), new PropertyMetadata(null));
public static readonly DependencyProperty PortraitGroupStyleProperty =
DependencyProperty.Register("PortraitGroupStyle", typeof(ObservableCollection<GroupStyle>), typeof(AutoRotatingGridView), new PropertyMetadata(null));
// Dependency Properties for minimum layout
public static readonly DependencyProperty MinimalItemTemplateProperty =
DependencyProperty.Register("MinimalItemTemplate", typeof(DataTemplate), typeof(AutoRotatingGridView), new PropertyMetadata(null));
public static readonly DependencyProperty MinimalItemsPanelProperty =
DependencyProperty.Register("MinimalItemsPanel", typeof(ItemsPanelTemplate), typeof(AutoRotatingGridView), new PropertyMetadata(null));
public static readonly DependencyProperty MinimalGroupStyleProperty =
DependencyProperty.Register("MinimalGroupStyle", typeof(ObservableCollection<GroupStyle>), typeof(AutoRotatingGridView), new PropertyMetadata(null));
public static readonly DependencyProperty MinimalLayoutWidthProperty =
DependencyProperty.Register("MinimalLayoutWidth", typeof(int), typeof(AutoRotatingGridView), new PropertyMetadata(500));
// Default styles
protected static readonly string DefaultLandscapeItemsPanelTemplate =
"<ItemsPanelTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'><ItemsWrapGrid Orientation='Vertical' /></ItemsPanelTemplate>";
protected static readonly string DefaultPortraitItemsPanelTemplate =
"<ItemsPanelTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'><ItemsWrapGrid Orientation='Horizontal' /></ItemsPanelTemplate>";
// Private members
private DataTemplate landscapeItemTemplate = null;
private ItemsPanelTemplate landscapeItemsPanel = null;
private IList<GroupStyle> landscapeGroupStyle = null;
private AutoRotateGridViewLayouts previousState = AutoRotateGridViewLayouts.Unknown;
public AutoRotatingGridView()
{
this.SizeChanged += RotatingGridview_SizeChanged;
// These styles will be overriden by the custom ones
this.ItemsPanel = XamlReader.Load(DefaultLandscapeItemsPanelTemplate) as ItemsPanelTemplate;
this.PortraitItemsPanel = XamlReader.Load(DefaultPortraitItemsPanelTemplate) as ItemsPanelTemplate;
this.PortraitGroupStyle = new ObservableCollection<GroupStyle>();
this.MinimalGroupStyle = new ObservableCollection<GroupStyle>();
}
// Layouts
private enum AutoRotateGridViewLayouts
{
Landscape,
Portrait,
Minimal,
Unknown,
}
// Properties
public DataTemplate PortraitItemTemplate
{
get { return (DataTemplate)GetValue(PortraitItemTemplateProperty); }
set { SetValue(PortraitItemTemplateProperty, value); }
}
public ItemsPanelTemplate PortraitItemsPanel
{
get { return (ItemsPanelTemplate)GetValue(PortraitItemsPanelProperty); }
set { SetValue(PortraitItemsPanelProperty, value); }
}
public ObservableCollection<GroupStyle> PortraitGroupStyle
{
get { return (ObservableCollection<GroupStyle>)GetValue(PortraitGroupStyleProperty); }
set { SetValue(PortraitGroupStyleProperty, value); }
}
public DataTemplate MinimalItemTemplate
{
get { return (DataTemplate)GetValue(MinimalItemTemplateProperty); }
set { SetValue(MinimalItemTemplateProperty, value); }
}
public ItemsPanelTemplate MinimalItemsPanel
{
get { return (ItemsPanelTemplate)GetValue(MinimalItemsPanelProperty); }
set { SetValue(MinimalItemsPanelProperty, value); }
}
public ObservableCollection<GroupStyle> MinimalGroupStyle
{
get { return (ObservableCollection<GroupStyle>)GetValue(MinimalGroupStyleProperty); }
set { SetValue(MinimalGroupStyleProperty, value); }
}
public int MinimalLayoutWidth
{
get { return (int)GetValue(MinimalLayoutWidthProperty); }
set { SetValue(MinimalLayoutWidthProperty, value); }
}
// Methods and handlers
private void RotatingGridview_SizeChanged(object sender, SizeChangedEventArgs e)
{
// We save the landscape styles as these properties will be changed later
if (this.landscapeItemTemplate == null)
{
this.landscapeItemTemplate = this.ItemTemplate;
}
if (this.landscapeItemsPanel == null)
{
this.landscapeItemsPanel = this.ItemsPanel;
}
if (this.landscapeGroupStyle == null)
{
this.landscapeGroupStyle = new List<GroupStyle>();
foreach (GroupStyle style in this.GroupStyle)
{
this.landscapeGroupStyle.Add(style);
}
}
// We search for the corresponding layout and update it if it changed
if (this.MinimalLayoutWidth > Window.Current.Bounds.Width)
{
if (this.previousState != AutoRotateGridViewLayouts.Minimal)
{
this.previousState = AutoRotateGridViewLayouts.Minimal;
UpdateLayout(AutoRotateGridViewLayouts.Minimal);
}
}
else if (Window.Current.Bounds.Height > Window.Current.Bounds.Width)
{
if (this.previousState != AutoRotateGridViewLayouts.Portrait)
{
this.previousState = AutoRotateGridViewLayouts.Portrait;
UpdateLayout(AutoRotateGridViewLayouts.Portrait);
}
}
else
{
if (this.previousState != AutoRotateGridViewLayouts.Landscape)
{
this.previousState = AutoRotateGridViewLayouts.Landscape;
UpdateLayout(AutoRotateGridViewLayouts.Landscape);
}
}
}
private void UpdateLayout(AutoRotateGridViewLayouts layout)
{
// Landscape layout
if (layout == AutoRotateGridViewLayouts.Landscape)
{
this.SetValue(ScrollViewer.HorizontalScrollBarVisibilityProperty, ScrollBarVisibility.Auto);
this.SetValue(ScrollViewer.VerticalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled);
this.SetValue(ScrollViewer.HorizontalScrollModeProperty, ScrollMode.Enabled);
this.SetValue(ScrollViewer.VerticalScrollModeProperty, ScrollMode.Disabled);
this.SetValue(ScrollViewer.ZoomModeProperty, ZoomMode.Disabled);
}
else
{
this.SetValue(ScrollViewer.HorizontalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled);
this.SetValue(ScrollViewer.VerticalScrollBarVisibilityProperty, ScrollBarVisibility.Auto);
this.SetValue(ScrollViewer.HorizontalScrollModeProperty, ScrollMode.Disabled);
this.SetValue(ScrollViewer.VerticalScrollModeProperty, ScrollMode.Enabled);
this.SetValue(ScrollViewer.ZoomModeProperty, ZoomMode.Disabled);
}
this.ChangeItemsPanel(layout);
this.ChangeGroupStyle(layout);
this.ChangeItemTemplate(layout);
}
// Styles setter methods with fallback
private void ChangeItemTemplate(AutoRotateGridViewLayouts layout)
{
switch (layout)
{
case AutoRotateGridViewLayouts.Minimal:
if (this.MinimalItemTemplate != null)
{
this.ItemTemplate = this.MinimalItemTemplate;
}
else
{
this.ChangeItemTemplate(AutoRotateGridViewLayouts.Portrait);
}
break;
case AutoRotateGridViewLayouts.Portrait:
if (this.PortraitItemTemplate != null)
{
this.ItemTemplate = this.PortraitItemTemplate;
}
else
{
this.ChangeItemTemplate(AutoRotateGridViewLayouts.Landscape);
}
break;
case AutoRotateGridViewLayouts.Landscape:
this.ItemTemplate = landscapeItemTemplate;
break;
}
}
private void ChangeItemsPanel(AutoRotateGridViewLayouts layout)
{
switch (layout)
{
case AutoRotateGridViewLayouts.Minimal:
if (this.MinimalItemsPanel != null)
{
this.ItemsPanel = this.MinimalItemsPanel;
}
else
{
this.ChangeItemsPanel(AutoRotateGridViewLayouts.Portrait);
}
break;
case AutoRotateGridViewLayouts.Portrait:
if (this.PortraitItemsPanel != null)
{
this.ItemsPanel = this.PortraitItemsPanel;
}
else
{
this.ChangeItemsPanel(AutoRotateGridViewLayouts.Landscape);
}
break;
case AutoRotateGridViewLayouts.Landscape:
this.ItemsPanel = landscapeItemsPanel;
break;
}
}
private void ChangeGroupStyle(AutoRotateGridViewLayouts layout)
{
switch (layout)
{
case AutoRotateGridViewLayouts.Minimal:
if (this.MinimalGroupStyle != null && this.MinimalGroupStyle.Count > 0)
{
this.GroupStyle.Clear();
foreach (GroupStyle style in this.MinimalGroupStyle)
{
this.GroupStyle.Add(style);
}
}
else
{
this.ChangeGroupStyle(AutoRotateGridViewLayouts.Portrait);
}
break;
case AutoRotateGridViewLayouts.Portrait:
if (this.PortraitGroupStyle != null && this.PortraitGroupStyle.Count > 0)
{
this.GroupStyle.Clear();
foreach (GroupStyle style in this.PortraitGroupStyle)
{
this.GroupStyle.Add(style);
}
}
else
{
this.ChangeGroupStyle(AutoRotateGridViewLayouts.Landscape);
}
break;
case AutoRotateGridViewLayouts.Landscape:
this.GroupStyle.Clear();
if (this.landscapeGroupStyle != null)
{
foreach (GroupStyle style in this.landscapeGroupStyle)
{
this.GroupStyle.Add(style);
}
}
break;
}
}
}
}
| |
// 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.
// File System.Windows.Media.Geometry.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Media
{
abstract public partial class Geometry : System.Windows.Media.Animation.Animatable, IFormattable, System.Windows.Media.Composition.DUCE.IResource
{
#region Methods and constructors
public Geometry Clone()
{
return default(Geometry);
}
public Geometry CloneCurrentValue()
{
return default(Geometry);
}
public static PathGeometry Combine(Geometry geometry1, Geometry geometry2, GeometryCombineMode mode, Transform transform, double tolerance, ToleranceType type)
{
return default(PathGeometry);
}
public static PathGeometry Combine(Geometry geometry1, Geometry geometry2, GeometryCombineMode mode, Transform transform)
{
return default(PathGeometry);
}
public bool FillContains(System.Windows.Point hitPoint)
{
return default(bool);
}
public bool FillContains(System.Windows.Point hitPoint, double tolerance, ToleranceType type)
{
return default(bool);
}
public bool FillContains(Geometry geometry)
{
return default(bool);
}
public bool FillContains(Geometry geometry, double tolerance, ToleranceType type)
{
return default(bool);
}
public IntersectionDetail FillContainsWithDetail(Geometry geometry)
{
return default(IntersectionDetail);
}
public virtual new IntersectionDetail FillContainsWithDetail(Geometry geometry, double tolerance, ToleranceType type)
{
return default(IntersectionDetail);
}
internal Geometry()
{
}
public virtual new double GetArea(double tolerance, ToleranceType type)
{
return default(double);
}
public double GetArea()
{
return default(double);
}
public PathGeometry GetFlattenedPathGeometry()
{
return default(PathGeometry);
}
public virtual new PathGeometry GetFlattenedPathGeometry(double tolerance, ToleranceType type)
{
return default(PathGeometry);
}
public virtual new PathGeometry GetOutlinedPathGeometry(double tolerance, ToleranceType type)
{
return default(PathGeometry);
}
public PathGeometry GetOutlinedPathGeometry()
{
return default(PathGeometry);
}
public System.Windows.Rect GetRenderBounds(Pen pen)
{
return default(System.Windows.Rect);
}
public virtual new System.Windows.Rect GetRenderBounds(Pen pen, double tolerance, ToleranceType type)
{
return default(System.Windows.Rect);
}
public virtual new PathGeometry GetWidenedPathGeometry(Pen pen, double tolerance, ToleranceType type)
{
return default(PathGeometry);
}
public PathGeometry GetWidenedPathGeometry(Pen pen)
{
return default(PathGeometry);
}
public abstract bool IsEmpty();
public abstract bool MayHaveCurves();
public static Geometry Parse(string source)
{
return default(Geometry);
}
public bool ShouldSerializeTransform()
{
return default(bool);
}
public bool StrokeContains(Pen pen, System.Windows.Point hitPoint, double tolerance, ToleranceType type)
{
return default(bool);
}
public bool StrokeContains(Pen pen, System.Windows.Point hitPoint)
{
return default(bool);
}
public IntersectionDetail StrokeContainsWithDetail(Pen pen, Geometry geometry, double tolerance, ToleranceType type)
{
return default(IntersectionDetail);
}
public IntersectionDetail StrokeContainsWithDetail(Pen pen, Geometry geometry)
{
return default(IntersectionDetail);
}
string System.IFormattable.ToString(string format, IFormatProvider provider)
{
return default(string);
}
int System.Windows.Media.Composition.DUCE.IResource.GetChannelCount()
{
return default(int);
}
public string ToString(IFormatProvider provider)
{
return default(string);
}
#endregion
#region Properties and indexers
public virtual new System.Windows.Rect Bounds
{
get
{
return default(System.Windows.Rect);
}
}
public static System.Windows.Media.Geometry Empty
{
get
{
return default(System.Windows.Media.Geometry);
}
}
public static double StandardFlatteningTolerance
{
get
{
return default(double);
}
}
public Transform Transform
{
get
{
return default(Transform);
}
set
{
}
}
#endregion
#region Fields
public readonly static System.Windows.DependencyProperty TransformProperty;
#endregion
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using NAudio.Wave.SampleProviders;
namespace NAudio.Wave
{
/// <summary>
/// This class writes WAV data to a .wav file on disk
/// </summary>
public class WaveFileWriter : Stream
{
private readonly string filename;
private readonly WaveFormat format;
private readonly byte[] value24 = new byte[3]; // keep this around to save us creating it every time
private readonly BinaryWriter writer;
private int dataChunkSize;
private long dataSizePos;
private long factSampleCountPos;
private Stream outStream;
/// <summary>
/// WaveFileWriter that actually writes to a stream
/// </summary>
/// <param name="outStream">Stream to be written to</param>
/// <param name="format">Wave format to use</param>
public WaveFileWriter(Stream outStream, WaveFormat format)
{
this.outStream = outStream;
this.format = format;
writer = new BinaryWriter(outStream, Encoding.UTF8);
writer.Write(Encoding.UTF8.GetBytes("RIFF"));
writer.Write(0); // placeholder
writer.Write(Encoding.UTF8.GetBytes("WAVE"));
writer.Write(Encoding.UTF8.GetBytes("fmt "));
format.Serialize(writer);
CreateFactChunk();
WriteDataChunkHeader();
}
/// <summary>
/// Creates a new WaveFileWriter
/// </summary>
/// <param name="filename">The filename to write to</param>
/// <param name="format">The Wave Format of the output data</param>
public WaveFileWriter(string filename, WaveFormat format)
: this(new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Read), format)
{
this.filename = filename;
}
/// <summary>
/// The wave file name or null if not applicable
/// </summary>
public string Filename
{
get { return filename; }
}
/// <summary>
/// Number of bytes of audio in the data chunk
/// </summary>
public override long Length
{
get { return dataChunkSize; }
}
/// <summary>
/// WaveFormat of this wave file
/// </summary>
public WaveFormat WaveFormat
{
get { return format; }
}
/// <summary>
/// Returns false: Cannot read from a WaveFileWriter
/// </summary>
public override bool CanRead
{
get { return false; }
}
/// <summary>
/// Returns true: Can write to a WaveFileWriter
/// </summary>
public override bool CanWrite
{
get { return true; }
}
/// <summary>
/// Returns false: Cannot seek within a WaveFileWriter
/// </summary>
public override bool CanSeek
{
get { return false; }
}
/// <summary>
/// Gets the Position in the WaveFile (i.e. number of bytes written so far)
/// </summary>
public override long Position
{
get { return dataChunkSize; }
set { throw new InvalidOperationException("Repositioning a WaveFileWriter is not supported"); }
}
/// <summary>
/// Creates a 16 bit Wave File from an ISampleProvider
/// BEWARE: the source provider must not return data indefinitely
/// </summary>
/// <param name="filename">The filename to write to</param>
/// <param name="sourceProvider">The source sample provider</param>
public static void CreateWaveFile16(string filename, ISampleProvider sourceProvider)
{
CreateWaveFile(filename, new SampleToWaveProvider16(sourceProvider));
}
/// <summary>
/// Creates a Wave file by reading all the data from a WaveProvider
/// BEWARE: the WaveProvider MUST return 0 from its Read method when it is finished,
/// or the Wave File will grow indefinitely.
/// </summary>
/// <param name="filename">The filename to use</param>
/// <param name="sourceProvider">The source WaveProvider</param>
public static void CreateWaveFile(string filename, IWaveProvider sourceProvider)
{
using (var writer = new WaveFileWriter(filename, sourceProvider.WaveFormat))
{
long outputLength = 0;
var buffer = new byte[sourceProvider.WaveFormat.AverageBytesPerSecond*4];
while (true)
{
int bytesRead = sourceProvider.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
// end of source provider
break;
}
outputLength += bytesRead;
if (outputLength > Int32.MaxValue)
{
throw new InvalidOperationException(
"WAV File cannot be greater than 2GB. Check that sourceProvider is not an endless stream.");
}
writer.Write(buffer, 0, bytesRead);
}
}
}
private void WriteDataChunkHeader()
{
writer.Write(Encoding.UTF8.GetBytes("data"));
dataSizePos = outStream.Position;
writer.Write(0); // placeholder
}
private void CreateFactChunk()
{
if (HasFactChunk())
{
writer.Write(Encoding.UTF8.GetBytes("fact"));
writer.Write(4);
factSampleCountPos = outStream.Position;
writer.Write(0); // number of samples
}
}
private bool HasFactChunk()
{
return format.Encoding != WaveFormatEncoding.Pcm && format.BitsPerSample != 0;
}
/// <summary>
/// Read is not supported for a WaveFileWriter
/// </summary>
public override int Read(byte[] buffer, int offset, int count)
{
throw new InvalidOperationException("Cannot read from a WaveFileWriter");
}
/// <summary>
/// Seek is not supported for a WaveFileWriter
/// </summary>
public override long Seek(long offset, SeekOrigin origin)
{
throw new InvalidOperationException("Cannot seek within a WaveFileWriter");
}
/// <summary>
/// SetLength is not supported for WaveFileWriter
/// </summary>
/// <param name="value"></param>
public override void SetLength(long value)
{
throw new InvalidOperationException("Cannot set length of a WaveFileWriter");
}
/// <summary>
/// Appends bytes to the WaveFile (assumes they are already in the correct format)
/// </summary>
/// <param name="data">the buffer containing the wave data</param>
/// <param name="offset">the offset from which to start writing</param>
/// <param name="count">the number of bytes to write</param>
[Obsolete("Use Write instead")]
public void WriteData(byte[] data, int offset, int count)
{
Write(data, offset, count);
}
/// <summary>
/// Appends bytes to the WaveFile (assumes they are already in the correct format)
/// </summary>
/// <param name="data">the buffer containing the wave data</param>
/// <param name="offset">the offset from which to start writing</param>
/// <param name="count">the number of bytes to write</param>
public override void Write(byte[] data, int offset, int count)
{
outStream.Write(data, offset, count);
dataChunkSize += count;
}
/// <summary>
/// Writes a single sample to the Wave file
/// </summary>
/// <param name="sample">the sample to write (assumed floating point with 1.0f as max value)</param>
public void WriteSample(float sample)
{
if (WaveFormat.BitsPerSample == 16)
{
writer.Write((Int16) (Int16.MaxValue*sample));
dataChunkSize += 2;
}
else if (WaveFormat.BitsPerSample == 24)
{
byte[] value = BitConverter.GetBytes((Int32) (Int32.MaxValue*sample));
value24[0] = value[1];
value24[1] = value[2];
value24[2] = value[3];
writer.Write(value24);
dataChunkSize += 3;
}
else if (WaveFormat.BitsPerSample == 32 && WaveFormat.Encoding == WaveFormatEncoding.Extensible)
{
writer.Write(UInt16.MaxValue*(Int32) sample);
dataChunkSize += 4;
}
else if (WaveFormat.Encoding == WaveFormatEncoding.IeeeFloat)
{
writer.Write(sample);
dataChunkSize += 4;
}
else
{
throw new InvalidOperationException("Only 16, 24 or 32 bit PCM or IEEE float audio data supported");
}
}
/// <summary>
/// Writes 32 bit floating point samples to the Wave file
/// They will be converted to the appropriate bit depth depending on the WaveFormat of the WAV file
/// </summary>
/// <param name="samples">The buffer containing the floating point samples</param>
/// <param name="offset">The offset from which to start writing</param>
/// <param name="count">The number of floating point samples to write</param>
public void WriteSamples(float[] samples, int offset, int count)
{
for (int n = 0; n < count; n++)
{
WriteSample(samples[offset + n]);
}
}
/// <summary>
/// Writes 16 bit samples to the Wave file
/// </summary>
/// <param name="samples">The buffer containing the 16 bit samples</param>
/// <param name="offset">The offset from which to start writing</param>
/// <param name="count">The number of 16 bit samples to write</param>
[Obsolete("Use WriteSamples instead")]
public void WriteData(short[] samples, int offset, int count)
{
WriteSamples(samples, offset, count);
}
/// <summary>
/// Writes 16 bit samples to the Wave file
/// </summary>
/// <param name="samples">The buffer containing the 16 bit samples</param>
/// <param name="offset">The offset from which to start writing</param>
/// <param name="count">The number of 16 bit samples to write</param>
public void WriteSamples(short[] samples, int offset, int count)
{
// 16 bit PCM data
if (WaveFormat.BitsPerSample == 16)
{
for (int sample = 0; sample < count; sample++)
{
writer.Write(samples[sample + offset]);
}
dataChunkSize += (count*2);
}
// 24 bit PCM data
else if (WaveFormat.BitsPerSample == 24)
{
byte[] value;
for (int sample = 0; sample < count; sample++)
{
value = BitConverter.GetBytes(UInt16.MaxValue*samples[sample + offset]);
value24[0] = value[1];
value24[1] = value[2];
value24[2] = value[3];
writer.Write(value24);
}
dataChunkSize += (count*3);
}
// 32 bit PCM data
else if (WaveFormat.BitsPerSample == 32 && WaveFormat.Encoding == WaveFormatEncoding.Extensible)
{
for (int sample = 0; sample < count; sample++)
{
writer.Write(UInt16.MaxValue*samples[sample + offset]);
}
dataChunkSize += (count*4);
}
// IEEE float data
else if (WaveFormat.BitsPerSample == 32 && WaveFormat.Encoding == WaveFormatEncoding.IeeeFloat)
{
for (int sample = 0; sample < count; sample++)
{
writer.Write(samples[sample + offset]/(float) (Int16.MaxValue + 1));
}
dataChunkSize += (count*4);
}
else
{
throw new InvalidOperationException("Only 16, 24 or 32 bit PCM or IEEE float audio data supported");
}
}
/// <summary>
/// Ensures data is written to disk
/// </summary>
public override void Flush()
{
writer.Flush();
}
#region IDisposable Members
/// <summary>
/// Actually performs the close,making sure the header contains the correct data
/// </summary>
/// <param name="disposing">True if called from <see>Dispose</see></param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (outStream != null)
{
try
{
UpdateHeader(writer);
}
finally
{
// in a finally block as we don't want the FileStream to run its disposer in
// the GC thread if the code above caused an IOException (e.g. due to disk full)
outStream.Close(); // will close the underlying base stream
outStream = null;
}
}
}
}
/// <summary>
/// Updates the header with file size information
/// </summary>
protected virtual void UpdateHeader(BinaryWriter writer)
{
Flush();
UpdateRiffChunk(writer);
UpdateFactChunk(writer);
UpdateDataChunk(writer);
}
private void UpdateDataChunk(BinaryWriter writer)
{
writer.Seek((int) dataSizePos, SeekOrigin.Begin);
writer.Write(dataChunkSize);
}
private void UpdateRiffChunk(BinaryWriter writer)
{
writer.Seek(4, SeekOrigin.Begin);
writer.Write((int) (outStream.Length - 8));
}
private void UpdateFactChunk(BinaryWriter writer)
{
if (HasFactChunk())
{
int bitsPerSample = (format.BitsPerSample*format.Channels);
if (bitsPerSample != 0)
{
writer.Seek((int) factSampleCountPos, SeekOrigin.Begin);
writer.Write((dataChunkSize*8)/bitsPerSample);
}
}
}
/// <summary>
/// Finaliser - should only be called if the user forgot to close this WaveFileWriter
/// </summary>
~WaveFileWriter()
{
Debug.Assert(false, "WaveFileWriter was not disposed");
Dispose(false);
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace IngService.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Camera Path 3
// Available on the Unity Asset Store
// Copyright (c) 2013 Jasper Stocker http://support.jasperstocker.com/camera-path/
// For support contact email@jasperstocker.com
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
using UnityEngine;
using UnityEditor;
public class CameraPathEditorSceneGUI
{
private const float LINE_RESOLUTION = 0.005f;
private const float HANDLE_SCALE = 0.1f;
public static CameraPath _cameraPath;
public static CameraPathAnimator _animator;
public static int selectedPointIndex
{
get { return _cameraPath.selectedPoint; }
set { _cameraPath.selectedPoint = value; }
}
public static CameraPath.PointModes _pointMode
{
get { return _cameraPath.pointMode; }
set { _cameraPath.pointMode = value; }
}
public static void OnSceneGUI()
{
if(!_cameraPath.showGizmos)
return;
if(_cameraPath.transform.rotation != Quaternion.identity)
return;
_pointMode = _cameraPath.pointMode;
if (SceneView.focusedWindow != null)
SceneView.focusedWindow.wantsMouseMove = false;
//draw small point indicators
Handles.color = CameraPathColours.GREY;
int numberOfCPoints = _cameraPath.fovList.realNumberOfPoints;
for (int i = 0; i < numberOfCPoints; i++)
{
CameraPathPoint point = _cameraPath.fovList[i];
if (point.positionModes == CameraPathPoint.PositionModes.Free)
Handles.DotCap(0, point.worldPosition, Quaternion.identity, 0.2f);
}
numberOfCPoints = _cameraPath.delayList.realNumberOfPoints;
for (int i = 0; i < numberOfCPoints; i++)
{
CameraPathPoint point = _cameraPath.delayList[i];
if (point.positionModes == CameraPathPoint.PositionModes.Free)
Handles.DotCap(0, point.worldPosition, Quaternion.identity, 0.2f);
}
numberOfCPoints = _cameraPath.orientationList.realNumberOfPoints;
for (int i = 0; i < numberOfCPoints; i++)
{
CameraPathPoint point = _cameraPath.orientationList[i];
if (point.positionModes == CameraPathPoint.PositionModes.Free)
Handles.DotCap(0, point.worldPosition, Quaternion.identity, 0.2f);
}
numberOfCPoints = _cameraPath.speedList.realNumberOfPoints;
for (int i = 0; i < numberOfCPoints; i++)
{
CameraPathPoint point = _cameraPath.speedList[i];
if (point.positionModes == CameraPathPoint.PositionModes.Free)
Handles.DotCap(0, point.worldPosition, Quaternion.identity, 0.2f);
}
numberOfCPoints = _cameraPath.tiltList.realNumberOfPoints;
for (int i = 0; i < numberOfCPoints; i++)
{
CameraPathPoint point = _cameraPath.tiltList[i];
if (point.positionModes == CameraPathPoint.PositionModes.Free)
Handles.DotCap(0, point.worldPosition, Quaternion.identity, 0.2f);
}
//draw path outline
Camera sceneCamera = Camera.current;
int numberOfPoints = _cameraPath.numberOfPoints;
Handles.color = _cameraPath.selectedPathColour;
float pointPercentage = 1.0f / (numberOfPoints - 1);
for(int i = 0; i < numberOfPoints-1; i++)
{
CameraPathControlPoint pointA = _cameraPath.GetPoint(i);
CameraPathControlPoint pointB = _cameraPath.GetPoint(i+1);
float dotPA = Vector3.Dot(sceneCamera.transform.forward, pointA.worldPosition - sceneCamera.transform.position);
float dotPB = Vector3.Dot(sceneCamera.transform.forward, pointB.worldPosition - sceneCamera.transform.position);
if (dotPA < 0 && dotPB < 0)//points are both behind camera - don't render
continue;
float pointAPercentage = pointPercentage * i;
float pointBPercentage = pointPercentage * (i + 1);
float arcPercentage = pointBPercentage - pointAPercentage;
Vector3 arcCentre = (pointA.worldPosition + pointB.worldPosition) * 0.5f;
float arcLength = _cameraPath.StoredArcLength(_cameraPath.GetCurveIndex(pointA.index));
float arcDistance = Vector3.Distance(sceneCamera.transform.position, arcCentre);
int arcPoints = Mathf.Max(Mathf.RoundToInt(arcLength * (40 / Mathf.Max(arcDistance,20))), 10);
float arcTime = 1.0f / arcPoints;
float endLoop = 1.0f - arcTime;
Vector3 lastPoint = Vector3.zero;
for (float p = 0; p < endLoop; p += arcTime)
{
float p2 = p + arcTime;
float pathPercentageA = pointAPercentage + arcPercentage * p;
float pathPercentageB = pointAPercentage + arcPercentage * p2;
Vector3 lineStart = _cameraPath.GetPathPosition(pathPercentageA, true);
Vector3 lineEnd = _cameraPath.GetPathPosition(pathPercentageB, true);
Handles.DrawLine(lineStart, lineEnd);
lastPoint = lineEnd;
}
Handles.DrawLine(lastPoint, _cameraPath.GetPathPosition(pointBPercentage, true));
}
switch(_pointMode)
{
case CameraPath.PointModes.Transform:
SceneGUIPointBased();
break;
case CameraPath.PointModes.ControlPoints:
SceneGUIPointBased();
break;
case CameraPath.PointModes.Orientations:
SceneGUIOrientationBased();
break;
case CameraPath.PointModes.FOV:
SceneGUIFOVBased();
break;
case CameraPath.PointModes.Events:
SceneGUIEventBased();
break;
case CameraPath.PointModes.Speed:
SceneGUISpeedBased();
break;
case CameraPath.PointModes.Tilt:
SceneGUITiltBased();
break;
case CameraPath.PointModes.Delay:
SceneGUIDelayBased();
break;
case CameraPath.PointModes.Ease:
SceneGUIEaseBased();
break;
case CameraPath.PointModes.AddPathPoints:
AddPathPoints();
break;
case CameraPath.PointModes.RemovePathPoints:
RemovePathPoints();
break;
case CameraPath.PointModes.AddOrientations:
AddCPathPoints();
break;
case CameraPath.PointModes.AddFovs:
AddCPathPoints();
break;
case CameraPath.PointModes.AddTilts:
AddCPathPoints();
break;
case CameraPath.PointModes.AddEvents:
AddCPathPoints();
break;
case CameraPath.PointModes.AddSpeeds:
AddCPathPoints();
break;
case CameraPath.PointModes.AddDelays:
AddCPathPoints();
break;
case CameraPath.PointModes.RemoveOrientations:
RemoveCPathPoints();
break;
case CameraPath.PointModes.RemoveTilts:
RemoveCPathPoints();
break;
case CameraPath.PointModes.RemoveFovs:
RemoveCPathPoints();
break;
case CameraPath.PointModes.RemoveEvents:
RemoveCPathPoints();
break;
case CameraPath.PointModes.RemoveSpeeds:
RemoveCPathPoints();
break;
case CameraPath.PointModes.RemoveDelays:
RemoveCPathPoints();
break;
}
if (Event.current.type == EventType.ValidateCommand)
{
switch (Event.current.commandName)
{
case "UndoRedoPerformed":
GUI.changed = true;
break;
}
}
}
private static void SceneGUIPointBased()
{
Camera sceneCamera = Camera.current;
int realNumberOfPoints = _cameraPath.realNumberOfPoints;
for (int i = 0; i < realNumberOfPoints; i++)
{
CameraPathControlPoint point = _cameraPath[i];
if (Vector3.Dot(sceneCamera.transform.forward, point.worldPosition - sceneCamera.transform.position) < 0)
continue;
if (_cameraPath.enableUndo) Undo.RecordObject(point, "Modifying Path Point");
Handles.Label(point.worldPosition, point.displayName+"\n"+(point.percentage*100).ToString("F1")+"%");
float pointHandleSize = HandleUtility.GetHandleSize(point.worldPosition) * HANDLE_SCALE;
Handles.color = (i == selectedPointIndex) ? _cameraPath.selectedPointColour : _cameraPath.unselectedPointColour;
if (Handles.Button(point.worldPosition, Quaternion.identity, pointHandleSize, pointHandleSize, Handles.DotCap))
{
ChangeSelectedPointIndex(i);
GUI.changed = true;
}
if(i == selectedPointIndex)
{
if (_pointMode == CameraPath.PointModes.Transform || _cameraPath.interpolation != CameraPath.Interpolation.Bezier)
{
Vector3 currentPosition = point.worldPosition;
currentPosition = Handles.DoPositionHandle(currentPosition, Quaternion.identity);
point.worldPosition = currentPosition;
if(_cameraPath.interpolation == CameraPath.Interpolation.Bezier)
{
Handles.color = CameraPathColours.DARKGREY;
float pointSize = pointHandleSize * 0.5f;
Handles.DrawLine(point.worldPosition, point.forwardControlPointWorld);
Handles.DrawLine(point.worldPosition, point.backwardControlPointWorld);
if (Handles.Button(point.forwardControlPointWorld, Quaternion.identity, pointSize, pointSize, Handles.DotCap))
_cameraPath.pointMode = CameraPath.PointModes.ControlPoints;
if (Handles.Button(point.backwardControlPointWorld, Quaternion.identity, pointSize, pointSize, Handles.DotCap))
_cameraPath.pointMode = CameraPath.PointModes.ControlPoints;
}
}
else
{
//Backward ControlPoints point - render first so it's behind the forward
Handles.DrawLine(point.worldPosition, point.backwardControlPointWorld);
point.backwardControlPointWorld = Handles.DoPositionHandle(point.backwardControlPointWorld, Quaternion.identity);
if (Vector3.Dot(sceneCamera.transform.forward, point.worldPosition - sceneCamera.transform.position) > 0)
Handles.Label(point.backwardControlPoint, "point " + i + " reverse ControlPoints point");
//Forward ControlPoints point
if (Vector3.Dot(sceneCamera.transform.forward, point.worldPosition - sceneCamera.transform.position) > 0)
Handles.Label(point.forwardControlPoint, "point " + i + " ControlPoints point");
Handles.color = _cameraPath.selectedPointColour;
Handles.DrawLine(point.worldPosition, point.forwardControlPointWorld);
point.forwardControlPointWorld = Handles.DoPositionHandle(point.forwardControlPointWorld, Quaternion.identity);
}
}
}
}
private static void SceneGUIOrientationBased()
{
DisplayAtPoint();
CameraPathOrientationList orientationList = _cameraPath.orientationList;
Camera sceneCamera = Camera.current;
int orientationCount = orientationList.realNumberOfPoints;
for (int i = 0; i < orientationCount; i++)
{
CameraPathOrientation orientation = orientationList[i];
if (_cameraPath.enableUndo) Undo.RecordObject(orientation, "Modifying Orientation Point");
if (Vector3.Dot(sceneCamera.transform.forward, orientation.worldPosition - sceneCamera.transform.position) < 0)
continue;
string orientationLabel = orientation.displayName;
orientationLabel += "\nat percentage: " + orientation.percent.ToString("F3");
switch(orientation.positionModes)
{
case CameraPathPoint.PositionModes.FixedToPoint:
orientationLabel += "\nat point: " + orientation.point.displayName;
break;
}
Handles.Label(orientation.worldPosition, orientationLabel);
float pointHandleSize = HandleUtility.GetHandleSize(orientation.worldPosition) * HANDLE_SCALE;
Handles.color = (i == selectedPointIndex) ? _cameraPath.selectedPointColour : _cameraPath.unselectedPointColour;
Handles.ArrowCap(0, orientation.worldPosition, orientation.rotation, pointHandleSize*4);
if (Handles.Button(orientation.worldPosition, Quaternion.identity, pointHandleSize, pointHandleSize, Handles.DotCap))
{
ChangeSelectedPointIndex(i);
GUI.changed = true;
}
if (i == selectedPointIndex)
{
Quaternion currentRotation = orientation.rotation;
currentRotation = Handles.DoRotationHandle(currentRotation, orientation.worldPosition);
if (currentRotation != orientation.rotation)
{
orientation.rotation = currentRotation;
}
CPPSlider(orientation);
}
}
if(_cameraPath.showOrientationIndicators)//draw orientation indicators
{
Handles.color = _cameraPath.orientationIndicatorColours;
float indicatorLength = _cameraPath.orientationIndicatorUnitLength / _cameraPath.pathLength;
for(float i = 0; i < 1; i += indicatorLength)
{
Vector3 indicatorPosition = _cameraPath.GetPathPosition(i);
Quaternion inicatorRotation = _cameraPath.GetPathRotation(i,false);
float indicatorHandleSize = HandleUtility.GetHandleSize(indicatorPosition) * HANDLE_SCALE * 4;
Handles.ArrowCap(0, indicatorPosition, inicatorRotation, indicatorHandleSize);
}
}
}
private static void SceneGUIFOVBased()
{
DisplayAtPoint();
CameraPathFOVList fovList = _cameraPath.fovList;
Camera sceneCamera = Camera.current;
int pointCount = fovList.realNumberOfPoints;
for (int i = 0; i < pointCount; i++)
{
CameraPathFOV fovPoint = fovList[i];
if (_cameraPath.enableUndo) Undo.RecordObject(fovPoint, "Modifying FOV Point");
if (Vector3.Dot(sceneCamera.transform.forward, fovPoint.worldPosition - sceneCamera.transform.position) < 0)
continue;
string pointLabel = fovPoint.displayName;
pointLabel += "\nvalue: " + fovPoint.FOV.ToString("F1");
if (fovPoint.positionModes == CameraPathPoint.PositionModes.FixedToPoint) pointLabel += "\nat point: " + fovPoint.point.displayName;
else pointLabel += "\nat percentage: " + fovPoint.percent.ToString("F3");
Handles.Label(fovPoint.worldPosition, pointLabel);
float pointHandleSize = HandleUtility.GetHandleSize(fovPoint.worldPosition) * HANDLE_SCALE;
Handles.color = (i == selectedPointIndex) ? _cameraPath.selectedPointColour : _cameraPath.unselectedPointColour;
if (Handles.Button(fovPoint.worldPosition, Quaternion.identity, pointHandleSize, pointHandleSize, Handles.DotCap))
{
ChangeSelectedPointIndex(i);
GUI.changed = true;
}
if (i == selectedPointIndex)
{
CPPSlider(fovPoint);
}
}
}
private static void SceneGUIEventBased()
{
DisplayAtPoint();
CameraPathEventList eventList = _cameraPath.eventList;
Camera sceneCamera = Camera.current;
int pointCount = eventList.realNumberOfPoints;
for (int i = 0; i < pointCount; i++)
{
CameraPathEvent eventPoint = eventList[i];
if (_cameraPath.enableUndo) Undo.RecordObject(eventPoint, "Modifying Event Point");
if (Vector3.Dot(sceneCamera.transform.forward, eventPoint.worldPosition - sceneCamera.transform.position) < 0)
continue;
string pointLabel = eventPoint.displayName;
pointLabel += "\ntype: " + eventPoint.type;
if (eventPoint.type == CameraPathEvent.Types.Broadcast) pointLabel += "\nevent name: " + eventPoint.eventName;
if (eventPoint.type == CameraPathEvent.Types.Call)
{
if (eventPoint.target != null)
pointLabel += "\nevent target: " + eventPoint.target.name + " calling: " + eventPoint.methodName;
else
pointLabel += "\nno target assigned";
}
if (eventPoint.positionModes == CameraPathPoint.PositionModes.FixedToPoint) pointLabel += "\nat point: " + eventPoint.point.displayName;
else pointLabel += "\nat percentage: " + eventPoint.percent.ToString("F3");
Handles.Label(eventPoint.worldPosition, pointLabel);
float pointHandleSize = HandleUtility.GetHandleSize(eventPoint.worldPosition) * HANDLE_SCALE;
Handles.color = (i == selectedPointIndex) ? _cameraPath.selectedPointColour : _cameraPath.unselectedPointColour;
if (Handles.Button(eventPoint.worldPosition, Quaternion.identity, pointHandleSize, pointHandleSize, Handles.DotCap))
{
ChangeSelectedPointIndex(i);
GUI.changed = true;
}
if(i == selectedPointIndex)
{
CPPSlider(eventPoint);
}
}
}
private static void SceneGUISpeedBased()
{
DisplayAtPoint();
CameraPathSpeedList pointList = _cameraPath.speedList;
Camera sceneCamera = Camera.current;
int pointCount = pointList.realNumberOfPoints;
for (int i = 0; i < pointCount; i++)
{
CameraPathSpeed point = pointList[i];
if (_cameraPath.enableUndo) Undo.RecordObject(point, "Modifying Speed Point");
if (Vector3.Dot(sceneCamera.transform.forward, point.worldPosition - sceneCamera.transform.position) < 0)
continue;
string pointLabel = point.displayName;
pointLabel += "\nvalue: " + point.speed + " m/s";
pointLabel += "\npercent: " + point.percent;
pointLabel += "\na percent: " + _cameraPath.DeNormalisePercentage(point.percent);
Handles.Label(point.worldPosition, pointLabel);
float pointHandleSize = HandleUtility.GetHandleSize(point.worldPosition) * HANDLE_SCALE;
Handles.color = (i == selectedPointIndex) ? _cameraPath.selectedPointColour : _cameraPath.unselectedPointColour;
if (Handles.Button(point.worldPosition, Quaternion.identity, pointHandleSize, pointHandleSize, Handles.DotCap))
{
ChangeSelectedPointIndex(i);
GUI.changed = true;
}
if (i == selectedPointIndex)
{
CPPSlider(point);
}
}
}
private static void SceneGUITiltBased()
{
DisplayAtPoint();
CameraPathTiltList pointList = _cameraPath.tiltList;
Camera sceneCamera = Camera.current;
int pointCount = pointList.realNumberOfPoints;
for (int i = 0; i < pointCount; i++)
{
CameraPathTilt point = pointList[i];
if (_cameraPath.enableUndo) Undo.RecordObject(point, "Modifying Tilt Point");
if (Vector3.Dot(sceneCamera.transform.forward, point.worldPosition - sceneCamera.transform.position) < 0)
continue;
string pointLabel = point.displayName;
pointLabel += "\nvalue: " + point.tilt.ToString("F1") + "\u00B0";
Handles.Label(point.worldPosition, pointLabel);
float pointHandleSize = HandleUtility.GetHandleSize(point.worldPosition) * HANDLE_SCALE;
bool pointIsSelected = i == selectedPointIndex;
Handles.color = (pointIsSelected) ? _cameraPath.selectedPointColour : _cameraPath.unselectedPointColour;
float tiltSize = 2.0f;
Vector3 pointForwardDirection = _cameraPath.GetPathDirection(point.percent, false);
Quaternion qTilt = Quaternion.AngleAxis(-point.tilt, pointForwardDirection);
Quaternion pointForward = Quaternion.LookRotation(pointForwardDirection);
Handles.CircleCap(0, point.worldPosition, pointForward, tiltSize);
Vector3 horizontalLineDirection = ((qTilt * Quaternion.AngleAxis(-90, Vector3.up)) * pointForwardDirection).normalized * tiltSize;
Vector3 horizontalLineStart = point.worldPosition + horizontalLineDirection;
Vector3 horizontalLineEnd = point.worldPosition - horizontalLineDirection;
Handles.DrawLine(horizontalLineStart, horizontalLineEnd);
Vector3 verticalLineDirection = (Quaternion.AngleAxis(-90, pointForwardDirection) * horizontalLineDirection).normalized * tiltSize;
Vector3 verticalLineStart = point.worldPosition + verticalLineDirection;
Vector3 verticalLineEnd = point.worldPosition;
Handles.DrawLine(verticalLineStart, verticalLineEnd);
if (Handles.Button(point.worldPosition, Quaternion.identity, pointHandleSize, pointHandleSize, Handles.DotCap))
{
ChangeSelectedPointIndex(i);
GUI.changed = true;
}
if (i == selectedPointIndex)
{
CPPSlider(point);
}
}
}
private static void SceneGUIDelayBased()
{
DisplayAtPoint();
CameraPathDelayList pointList = _cameraPath.delayList;
Camera sceneCamera = Camera.current;
int pointCount = pointList.realNumberOfPoints;
for (int i = 0; i < pointCount; i++)
{
CameraPathDelay point = pointList[i];
if (_cameraPath.enableUndo) Undo.RecordObject(point, "Modifying Delay Point");
if (Vector3.Dot(sceneCamera.transform.forward, point.worldPosition - sceneCamera.transform.position) < 0)
continue;
string pointLabel = "";
if(point == pointList.introPoint)
{
pointLabel += "start point";
if (point.time > 0)
pointLabel += "\ndelay: " + point.time.ToString("F2") + " sec";
else
pointLabel += "\nNo delay";
}
else if (point == pointList.outroPoint)
pointLabel += "end point";
else
{
pointLabel += point.displayName;
if (point.time > 0)
pointLabel += "\ndelay: " + point.time.ToString("F2") + " sec";
else
pointLabel += "\ndelay indefinitely";
}
Handles.Label(point.worldPosition, pointLabel);
float pointHandleSize = HandleUtility.GetHandleSize(point.worldPosition) * HANDLE_SCALE;
Handles.color = (i == selectedPointIndex) ? _cameraPath.selectedPointColour : _cameraPath.unselectedPointColour;
if (Handles.Button(point.worldPosition, Quaternion.identity, pointHandleSize, pointHandleSize, Handles.DotCap))
{
ChangeSelectedPointIndex(i);
GUI.changed = true;
}
if (i == selectedPointIndex)
{
CPPSlider(point);
}
}
}
private static void SceneGUIEaseBased()
{
CameraPathDelayList pointList = _cameraPath.delayList;
Camera sceneCamera = Camera.current;
int pointCount = pointList.realNumberOfPoints;
for (int i = 0; i < pointCount; i++)
{
CameraPathDelay point = pointList[i];
if (_cameraPath.enableUndo) Undo.RecordObject(point, "Modifying Ease Curves");
if (Vector3.Dot(sceneCamera.transform.forward, point.worldPosition - sceneCamera.transform.position) < 0)
continue;
string pointLabel = "";
if (point == pointList.introPoint)
pointLabel += "start point";
else if (point == pointList.outroPoint)
pointLabel += "end point";
else
{
pointLabel += point.displayName;
if (point.time > 0)
pointLabel += "\ndelay: " + point.time.ToString("F2") + " sec";
else
pointLabel += "\ndelay indefinitely";
}
Handles.Label(point.worldPosition, pointLabel);
float pointHandleSize = HandleUtility.GetHandleSize(point.worldPosition) * HANDLE_SCALE;
Handles.color = (i == selectedPointIndex) ? _cameraPath.selectedPointColour : _cameraPath.unselectedPointColour;
if (Handles.Button(point.worldPosition, Quaternion.identity, pointHandleSize, pointHandleSize, Handles.DotCap))
{
ChangeSelectedPointIndex(i);
GUI.changed = true;
}
// float unitPercent = 0.5f;
Vector3 easeUp = Vector3.up * _cameraPath.pathLength * 0.1f;
Handles.color = CameraPathColours.RED;
if (point != pointList.outroPoint)
{
float outroEasePointPercent = _cameraPath.GetOutroEasePercentage(point);
Vector3 outroEasePoint = _cameraPath.GetPathPosition(outroEasePointPercent, true);
Vector3 outroeaseDirection = _cameraPath.GetPathDirection(outroEasePointPercent, false);
Handles.Label(outroEasePoint, "Ease Out\n" + point.displayName);
Vector3 newPosition = Handles.Slider(outroEasePoint, outroeaseDirection);
float movement = Vector3.Distance(outroEasePoint, newPosition);
if (movement > Mathf.Epsilon)
{
float newPercent = NearestmMousePercentage();
float curvePercent = _cameraPath.GetCurvePercentage(_cameraPath.delayList.GetPoint(point.index), _cameraPath.delayList.GetPoint(point.index + 1), newPercent);
point.outroEndEasePercentage = curvePercent;
}
float percentWidth = (outroEasePointPercent - point.percent);
// float easeSpace = _cameraPath.pathLength * percentWidth;
// float easeLength = unitPercent / percentWidth;
float percentMovement = percentWidth / 10.0f;
for (float e = point.percent; e < outroEasePointPercent; e += percentMovement)
{
float eB = e + percentMovement;
Vector3 lineStart = _cameraPath.GetPathPosition(e, true);
Vector3 lineEnd = _cameraPath.GetPathPosition(eB, true);
Handles.DrawLine(lineStart,lineEnd);
float animCurvePercentA = (e - point.percent) / percentWidth;
float animCurvePercentB = (eB - point.percent) / percentWidth;
Vector3 lineEaseUpA = easeUp * point.outroCurve.Evaluate(animCurvePercentA);
Vector3 lineEaseUpB = easeUp * point.outroCurve.Evaluate(animCurvePercentB);
Handles.DrawLine(lineStart + lineEaseUpA, lineEnd + lineEaseUpB);
}
}
if (point != pointList.introPoint)
{
float introEasePointPercent = _cameraPath.GetIntroEasePercentage(point);
Vector3 introEasePoint = _cameraPath.GetPathPosition(introEasePointPercent, true);
Vector3 introEaseDirection = _cameraPath.GetPathDirection(introEasePointPercent, false);
Handles.color = CameraPathColours.RED;
Handles.Label(introEasePoint, "Ease In\n" + point.displayName);
Vector3 newPosition = Handles.Slider(introEasePoint, -introEaseDirection);
float movement = Vector3.Distance(introEasePoint, newPosition);
if (movement > Mathf.Epsilon)
{
float newPercent = NearestmMousePercentage();
float curvePercent = 1-_cameraPath.GetCurvePercentage(_cameraPath.delayList.GetPoint(point.index-1), _cameraPath.delayList.GetPoint(point.index), newPercent);
point.introStartEasePercentage = curvePercent;
}
float percentWidth = (point.percent - introEasePointPercent);
// float easeSpace = _cameraPath.pathLength * percentWidth;
// float easeLength = unitPercent / percentWidth;
float percentMovement = percentWidth / 10.0f;
for (float e = introEasePointPercent; e < point.percent; e += percentMovement)
{
float eB = e + percentMovement;
Vector3 lineStart = _cameraPath.GetPathPosition(e, true);
Vector3 lineEnd = _cameraPath.GetPathPosition(eB, true);
Handles.DrawLine(lineStart, lineEnd);
float animCurvePercentA = (e - introEasePointPercent) / percentWidth;
float animCurvePercentB = (eB - introEasePointPercent) / percentWidth;
Vector3 lineEaseUpA = easeUp * point.introCurve.Evaluate(animCurvePercentA);
Vector3 lineEaseUpB = easeUp * point.introCurve.Evaluate(animCurvePercentB);
Handles.DrawLine(lineStart + lineEaseUpA, lineEnd + lineEaseUpB);
}
}
}
}
private static void DisplayAtPoint()
{
float atPercent = _cameraPath.addPointAtPercent;
Vector3 atPointVector = _cameraPath.GetPathPosition(atPercent,true);
float handleSize = HandleUtility.GetHandleSize(atPointVector);
Handles.color = Color.black;
Handles.DotCap(0, atPointVector, Quaternion.identity, handleSize*0.05f);
Handles.Label(atPointVector, "Add Point Here\nfrom Inspector");
}
private static void AddPathPoints()
{
if (SceneView.focusedWindow != null)
SceneView.focusedWindow.wantsMouseMove = true;
Handles.color = _cameraPath.unselectedPointColour;
int numberOfPoints = _cameraPath.realNumberOfPoints;
for (int i = 0; i < numberOfPoints; i++)
{
CameraPathControlPoint point = _cameraPath[i];
float pointHandleSize = HandleUtility.GetHandleSize(point.worldPosition) * HANDLE_SCALE * 0.4f;
Handles.DotCap(0, point.worldPosition, Quaternion.identity, pointHandleSize);
}
float mousePercentage = NearestmMousePercentage();// _track.GetNearestPoint(mousePlanePoint);
Vector3 mouseTrackPoint = _cameraPath.GetPathPosition(mousePercentage, true);
Handles.Label(mouseTrackPoint, "Add New Path Point");
float newPointHandleSize = HandleUtility.GetHandleSize(mouseTrackPoint) * HANDLE_SCALE;
Quaternion lookDirection = Quaternion.LookRotation(Camera.current.transform.forward);
if (Handles.Button(mouseTrackPoint, lookDirection, newPointHandleSize, newPointHandleSize, Handles.DotCap))
{
int newPointIndex = _cameraPath.GetNextPointIndex(mousePercentage,false);
CameraPathControlPoint newPoint = _cameraPath.gameObject.AddComponent<CameraPathControlPoint>();//ScriptableObject.CreateInstance<CameraPathControlPoint>();
newPoint.worldPosition = mouseTrackPoint;
_cameraPath.InsertPoint(newPoint, newPointIndex);
ChangeSelectedPointIndex(newPointIndex);
GUI.changed = true;
}
}
private static void RemovePathPoints()
{
if (SceneView.focusedWindow != null)
SceneView.focusedWindow.wantsMouseMove = true;
int numberOfPoints = _cameraPath.realNumberOfPoints;
Handles.color = _cameraPath.selectedPointColour;
Ray mouseRay = Camera.current.ScreenPointToRay(new Vector3(Event.current.mousePosition.x, Screen.height - Event.current.mousePosition.y - 30, 0));
Quaternion mouseLookDirection = Quaternion.LookRotation(-mouseRay.direction);
for (int i = 0; i < numberOfPoints; i++)
{
CameraPathControlPoint point = _cameraPath[i];
float pointHandleSize = HandleUtility.GetHandleSize(point.worldPosition) * HANDLE_SCALE;
Handles.Label(point.worldPosition, "Remove Point: "+point.displayName);
if (Handles.Button(point.worldPosition, mouseLookDirection, pointHandleSize, pointHandleSize, Handles.DotCap))
{
_cameraPath.RemovePoint(point);
GUI.changed = true;
return;
}
}
}
private static void AddCPathPoints()
{
if (SceneView.focusedWindow != null)
SceneView.focusedWindow.wantsMouseMove = true;
Handles.color = _cameraPath.selectedPointColour;
CameraPathPointList pointList = null;
switch(_pointMode)
{
case CameraPath.PointModes.AddOrientations:
pointList = _cameraPath.orientationList;
break;
case CameraPath.PointModes.AddFovs:
pointList = _cameraPath.fovList;
break;
case CameraPath.PointModes.AddTilts:
pointList = _cameraPath.tiltList;
break;
case CameraPath.PointModes.AddEvents:
pointList = _cameraPath.eventList;
break;
case CameraPath.PointModes.AddSpeeds:
pointList = _cameraPath.speedList;
break;
case CameraPath.PointModes.AddDelays:
pointList = _cameraPath.delayList;
break;
}
int numberOfPoints = pointList.realNumberOfPoints;
for (int i = 0; i < numberOfPoints; i++)
{
CameraPathPoint point = pointList[i];
float pointHandleSize = HandleUtility.GetHandleSize(point.worldPosition) * HANDLE_SCALE * 0.4f;
Handles.DotCap(0, point.worldPosition, Quaternion.identity, pointHandleSize);
}
float mousePercentage = NearestmMousePercentage();// _track.GetNearestPoint(mousePlanePoint);
Vector3 mouseTrackPoint = _cameraPath.GetPathPosition(mousePercentage, true);
Handles.Label(mouseTrackPoint, "Add New Point");
float newPointHandleSize = HandleUtility.GetHandleSize(mouseTrackPoint) * HANDLE_SCALE;
Ray mouseRay = Camera.current.ScreenPointToRay(new Vector3(Event.current.mousePosition.x, Screen.height - Event.current.mousePosition.y - 30, 0));
Quaternion mouseLookDirection = Quaternion.LookRotation(-mouseRay.direction);
if (Handles.Button(mouseTrackPoint, mouseLookDirection, newPointHandleSize, newPointHandleSize, Handles.DotCap))
{
CameraPathControlPoint curvePointA = _cameraPath[_cameraPath.GetLastPointIndex(mousePercentage,false)];
CameraPathControlPoint curvePointB = _cameraPath[_cameraPath.GetNextPointIndex(mousePercentage,false)];
float curvePercentage = _cameraPath.GetCurvePercentage(curvePointA, curvePointB, mousePercentage);
switch(_pointMode)
{
case CameraPath.PointModes.AddOrientations:
Quaternion pointRotation = Quaternion.LookRotation(_cameraPath.GetPathDirection(mousePercentage));
CameraPathOrientation newOrientation = ((CameraPathOrientationList)pointList).AddOrientation(curvePointA, curvePointB, curvePercentage, pointRotation);
ChangeSelectedPointIndex(pointList.IndexOf(newOrientation));
break;
case CameraPath.PointModes.AddFovs:
float pointFOV = _cameraPath.fovList.GetValue(mousePercentage, CameraPathFOVList.ProjectionType.FOV);
float pointSize = _cameraPath.fovList.GetValue(mousePercentage, CameraPathFOVList.ProjectionType.Orthographic);
CameraPathFOV newFOVPoint = ((CameraPathFOVList)pointList).AddFOV(curvePointA, curvePointB, curvePercentage, pointFOV, pointSize);
ChangeSelectedPointIndex(pointList.IndexOf(newFOVPoint));
break;
case CameraPath.PointModes.AddTilts:
float pointTilt = _cameraPath.GetPathTilt(mousePercentage);
CameraPathTilt newTiltPoint = ((CameraPathTiltList)pointList).AddTilt(curvePointA, curvePointB, curvePercentage, pointTilt);
ChangeSelectedPointIndex(pointList.IndexOf(newTiltPoint));
break;
case CameraPath.PointModes.AddEvents:
CameraPathEvent newEventPoint = ((CameraPathEventList)pointList).AddEvent(curvePointA, curvePointB, curvePercentage);
ChangeSelectedPointIndex(pointList.IndexOf(newEventPoint));
break;
case CameraPath.PointModes.AddSpeeds:
_cameraPath.speedList.listEnabled = true;//if we're adding speeds then we probable want to enable it
CameraPathSpeed newSpeedPoint = ((CameraPathSpeedList)pointList).AddSpeedPoint(curvePointA, curvePointB, curvePercentage);
newSpeedPoint.speed = _animator.pathSpeed;
ChangeSelectedPointIndex(pointList.IndexOf(newSpeedPoint));
break;
case CameraPath.PointModes.AddDelays:
CameraPathDelay newDelayPoint = ((CameraPathDelayList)pointList).AddDelayPoint(curvePointA, curvePointB, curvePercentage);
ChangeSelectedPointIndex(pointList.IndexOf(newDelayPoint));
break;
}
GUI.changed = true;
}
}
private static void RemoveCPathPoints()
{
if (SceneView.focusedWindow != null)
SceneView.focusedWindow.wantsMouseMove = true;
CameraPathPointList pointList = null;
switch (_pointMode)
{
case CameraPath.PointModes.RemoveOrientations:
pointList = _cameraPath.orientationList;
break;
case CameraPath.PointModes.RemoveFovs:
pointList = _cameraPath.fovList;
break;
case CameraPath.PointModes.RemoveTilts:
pointList = _cameraPath.tiltList;
break;
case CameraPath.PointModes.RemoveEvents:
pointList = _cameraPath.eventList;
break;
case CameraPath.PointModes.RemoveSpeeds:
pointList = _cameraPath.speedList;
break;
case CameraPath.PointModes.RemoveDelays:
pointList = _cameraPath.delayList;
break;
}
int numberOfPoints = pointList.realNumberOfPoints;
Handles.color = _cameraPath.selectedPointColour;
Quaternion mouseLookDirection = Quaternion.LookRotation(Camera.current.transform.forward);
for (int i = 0; i < numberOfPoints; i++)
{
CameraPathPoint point = pointList[i];
float pointHandleSize = HandleUtility.GetHandleSize(point.worldPosition) * HANDLE_SCALE;
Handles.Label(point.worldPosition, "Remove Point " + i);
if (Handles.Button(point.worldPosition, mouseLookDirection, pointHandleSize, pointHandleSize, Handles.DotCap))
{
pointList.RemovePoint(point);
GUI.changed = true;
return;
}
}
}
private static void CPPSlider(CameraPathPoint point)
{
if(point.positionModes == CameraPathPoint.PositionModes.FixedToPercent)
return;//can't move fixed points
Vector3 pointPathDirection = _cameraPath.GetPathDirection(point.percent, false);
Handles.color = CameraPathColours.BLUE;
Vector3 newPosition = Handles.Slider(point.worldPosition, pointPathDirection);
newPosition = Handles.Slider(newPosition, -pointPathDirection);
float movement = Vector3.Distance(point.worldPosition, newPosition);
if (movement > Mathf.Epsilon)
{
//float newPercent = _cameraPath.GetNearestPoint(newPosition, false);
float newPercent = NearestmMousePercentage();
switch(point.positionModes)
{
case CameraPathPoint.PositionModes.Free:
CameraPathControlPoint curvePointA = _cameraPath[_cameraPath.GetLastPointIndex(newPercent, false)];
CameraPathControlPoint curvePointB = _cameraPath[_cameraPath.GetNextPointIndex(newPercent, false)];
point.cpointA = curvePointA;
point.cpointB = curvePointB;
point.curvePercentage = _cameraPath.GetCurvePercentage(curvePointA, curvePointB, newPercent);
break;
case CameraPathPoint.PositionModes.FixedToPoint:
point.positionModes = CameraPathPoint.PositionModes.Free;
CameraPathControlPoint newCurvePointA = _cameraPath[_cameraPath.GetLastPointIndex(newPercent, false)];
CameraPathControlPoint newCurvePointB = _cameraPath[_cameraPath.GetNextPointIndex(newPercent, false)];
if(newCurvePointA == newCurvePointB)
newCurvePointB = _cameraPath[_cameraPath.GetPointIndex(newCurvePointB.index- 1)];
point.cpointA = newCurvePointA;
point.cpointB = newCurvePointB;
point.curvePercentage = _cameraPath.GetCurvePercentage(newCurvePointA, newCurvePointB, newPercent);
break;
}
point.worldPosition = _cameraPath.GetPathPosition(point.percent, false);
_cameraPath.RecalculateStoredValues();
selectedPointIndex = point.index;
}
}
/// <summary>
/// Get the nearest point on the track curve to the mouse position
/// We essentailly project the track onto a 2D plane that is the editor camera and then find a point on that
/// </summary>
/// <returns>A percentage of the nearest point on the track curve to the nerest metre</returns>
private static float NearestmMousePercentage()
{
Camera cam = Camera.current;
float screenHeight = cam.pixelHeight;
Vector2 mousePos = Event.current.mousePosition;
mousePos.y = screenHeight - mousePos.y;
int numberOfSearchPoints = _cameraPath.storedValueArraySize;
Vector2 zeropoint = cam.WorldToScreenPoint(_cameraPath.GetPathPosition(0, true));
float nearestPointSqrMag = Vector2.SqrMagnitude(zeropoint - mousePos);
float nearestT = 0;
float nearestPointSqrMagB = Vector2.SqrMagnitude(zeropoint - mousePos);
float nearestTb = 0;
for (int i = 1; i < numberOfSearchPoints; i++)
{
float t = i / (float)numberOfSearchPoints;
Vector2 point = cam.WorldToScreenPoint(_cameraPath.GetPathPosition(t, true));
float thisPointMag = Vector2.SqrMagnitude(point - mousePos);
if (thisPointMag < nearestPointSqrMag)
{
nearestPointSqrMagB = nearestPointSqrMag;
nearestTb = nearestT;
nearestT = t;
nearestPointSqrMag = thisPointMag;
}
else
{
if (thisPointMag < nearestPointSqrMagB)
{
nearestTb = t;
nearestPointSqrMagB = thisPointMag;
}
}
}
float pointADist = Mathf.Sqrt(nearestPointSqrMag);
float pointBDist = Mathf.Sqrt(nearestPointSqrMagB);
float lerpvalue = pointADist / (pointADist + pointBDist);
return Mathf.Lerp(nearestT, nearestTb, lerpvalue);
}
private static void ChangeSelectedPointIndex(int newPointSelected)
{
selectedPointIndex = newPointSelected;
}
}
| |
#region license
// Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Reflection;
using Boo.Lang.Runtime;
namespace Boo.Lang
{
/// <summary>
/// boo language builtin functions.
/// </summary>
public class Builtins
{
public class duck
{
}
public static System.Version BooVersion
{
get
{
return new System.Version("0.8.2.3032");
}
}
public static void print(object o)
{
Console.WriteLine(o);
}
public static string gets()
{
return Console.ReadLine();
}
public static string prompt(string message)
{
Console.Write(message);
return Console.ReadLine();
}
public static string join(IEnumerable enumerable, string separator)
{
StringBuilder sb = new StringBuilder();
IEnumerator enumerator = enumerable.GetEnumerator();
using (enumerator as IDisposable)
{
if (enumerator.MoveNext())
{
sb.Append(enumerator.Current);
while (enumerator.MoveNext())
{
sb.Append(separator);
sb.Append(enumerator.Current);
}
}
}
return sb.ToString();
}
public static string join(IEnumerable enumerable, char separator)
{
StringBuilder sb = new StringBuilder();
IEnumerator enumerator = enumerable.GetEnumerator();
using (enumerator as IDisposable)
{
if (enumerator.MoveNext())
{
sb.Append(enumerator.Current);
while (enumerator.MoveNext())
{
sb.Append(separator);
sb.Append(enumerator.Current);
}
}
}
return sb.ToString();
}
public static string join(IEnumerable enumerable)
{
return join(enumerable, ' ');
}
public static IEnumerable map(object enumerable, ICallable function)
{
if (null == enumerable) throw new ArgumentNullException("enumerable");
if (null == function) throw new ArgumentNullException("function");
object[] args = new object[1];
foreach (object item in iterator(enumerable))
{
args[0] = item;
yield return function.Call(args);
}
}
public static object[] array(IEnumerable enumerable)
{
return new List(enumerable).ToArray();
}
public static Array array(Type elementType, ICollection collection)
{
if (null == collection)
{
throw new ArgumentNullException("collection");
}
if (null == elementType)
{
throw new ArgumentNullException("elementType");
}
Array array = Array.CreateInstance(elementType, collection.Count);
if (RuntimeServices.IsPromotableNumeric(Type.GetTypeCode(elementType)))
{
int i=0;
foreach (object item in collection)
{
object value = RuntimeServices.CheckNumericPromotion(item).ToType(elementType, null);
array.SetValue(value, i);
++i;
}
}
else
{
collection.CopyTo(array, 0);
}
return array;
}
public static Array array(Type elementType, IEnumerable enumerable)
{
if (null == enumerable)
{
throw new ArgumentNullException("enumerable");
}
if (null == elementType)
{
throw new ArgumentNullException("elementType");
}
// future optimization, check EnumeratorItemType of enumerable
// and get the fast path whenever possible
List l = null;
if (RuntimeServices.IsPromotableNumeric(Type.GetTypeCode(elementType)))
{
l = new List();
foreach (object item in enumerable)
{
object value = RuntimeServices.CheckNumericPromotion(item).ToType(elementType, null);
l.Add(value);
}
}
else
{
l = new List(enumerable);
}
return l.ToArray(elementType);
}
public static Array array(Type elementType, int length)
{
return matrix(elementType, length);
}
public static Array matrix(Type elementType, params int[] lengths)
{
if (null == elementType)
{
throw new ArgumentNullException("elementType");
}
return Array.CreateInstance(elementType, lengths);
}
public static IEnumerable iterator(object enumerable)
{
return RuntimeServices.GetEnumerable(enumerable);
}
#if !NO_SYSTEM_DLL
public static System.Diagnostics.Process shellp(string filename, string arguments)
{
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.Arguments = arguments;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.FileName = filename;
p.Start();
return p;
}
public static string shell(string filename, string arguments)
{
System.Diagnostics.Process p = shellp(filename, arguments);
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
return output;
}
#endif
internal class AssemblyExecutor : MarshalByRefObject
{
string _filename;
string[] _arguments;
string _capturedOutput = "";
public AssemblyExecutor(string filename, string[] arguments)
{
_filename = filename;
_arguments = arguments;
}
public string CapturedOutput
{
get
{
return _capturedOutput;
}
}
public void Execute()
{
StringWriter output = new System.IO.StringWriter();
TextWriter saved = Console.Out;
try
{
Console.SetOut(output);
//AppDomain.CurrentDomain.ExecuteAssembly(_filename, null, _arguments);
Assembly.LoadFrom(_filename).EntryPoint.Invoke(null, new object[1] { _arguments });
}
finally
{
Console.SetOut(saved);
_capturedOutput = output.ToString();
}
}
}
/// <summary>
/// Execute the specified MANAGED application in a new AppDomain.
///
/// The base directory for the new application domain will be set to
/// directory containing filename (Path.GetDirectoryName(Path.GetFullPath(filename))).
/// </summary>
public static string shellm(string filename, params string[] arguments)
{
AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationBase = Path.GetDirectoryName(Path.GetFullPath(filename));
AppDomain domain = AppDomain.CreateDomain("shellm", null, setup);
try
{
AssemblyExecutor executor = new AssemblyExecutor(filename, arguments);
domain.DoCallBack(new CrossAppDomainDelegate(executor.Execute));
return executor.CapturedOutput;
}
finally
{
AppDomain.Unload(domain);
}
}
public static IEnumerable<object[]> enumerate(object enumerable)
{
int i = 0;
foreach (object item in iterator(enumerable))
{
yield return new object[] { i++, item };
}
}
public static IEnumerable<int> range(int max)
{
if (max < 0) /* added for coherence with behavior of compiler-optimized
* for-in-range() loops, should compiler loops automatically
* inverse iteration in this case? */
{
throw new ArgumentOutOfRangeException("max < 0");
}
return range(0, max);
}
public static IEnumerable<int> range(int begin, int end)
{
if (begin < end)
{
for (int i = begin; i < end; ++i) yield return i;
}
else if (begin > end)
{
for (int i = begin; i > end; --i) yield return i;
}
}
public static IEnumerable<int> range(int begin, int end, int step)
{
if (0 ==step)
{
throw new ArgumentOutOfRangeException("step == 0");
}
if (step < 0)
{
if (begin < end)
{
throw new ArgumentOutOfRangeException("begin < end && step < 0");
}
for (int i = begin; i > end; i += step) yield return i;
}
else
{
if (begin > end)
{
throw new ArgumentOutOfRangeException("begin > end && step > 0");
}
for (int i = begin; i < end; i += step) yield return i;
}
}
public static IEnumerable reversed(object enumerable)
{
return new List(iterator(enumerable)).Reversed;
}
public static ZipEnumerator zip(params object[] enumerables)
{
IEnumerator[] enumerators = new IEnumerator[enumerables.Length];
for (int i=0; i<enumerables.Length; ++i)
{
enumerators[i] = GetEnumerator(enumerables[i]);
}
return new ZipEnumerator(enumerators);
}
public static IEnumerable<object> cat(params object[] args)
{
foreach (object e in args)
{
foreach (object item in iterator(e))
{
yield return item;
}
}
}
[EnumeratorItemType(typeof(object[]))]
public class ZipEnumerator : IEnumerator, IEnumerable, IDisposable
{
IEnumerator[] _enumerators;
internal ZipEnumerator(params IEnumerator[] enumerators)
{
_enumerators = enumerators;
}
public void Dispose()
{
for (int i=0; i<_enumerators.Length; ++i)
{
IDisposable d = _enumerators[i] as IDisposable;
if (d != null)
d.Dispose();
}
}
public void Reset()
{
for (int i=0; i<_enumerators.Length; ++i)
{
_enumerators[i].Reset();
}
}
public bool MoveNext()
{
for (int i=0; i<_enumerators.Length; ++i)
{
if (!_enumerators[i].MoveNext())
{
return false;
}
}
return true;
}
public object Current
{
get
{
object[] current = new object[_enumerators.Length];
for (int i=0; i<current.Length; ++i)
{
current[i] = _enumerators[i].Current;
}
return current;
}
}
public IEnumerator GetEnumerator()
{
return this;
}
}
private static IEnumerator GetEnumerator(object enumerable)
{
return RuntimeServices.GetEnumerable(enumerable).GetEnumerator();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;
namespace System.Net.Http
{
internal sealed partial class Http2Connection
{
private sealed class Http2Stream : IValueTaskSource, IHttpTrace, IHttpHeadersHandler
{
private const int InitialStreamBufferSize =
#if DEBUG
10;
#else
1024;
#endif
private static readonly byte[] s_statusHeaderName = Encoding.ASCII.GetBytes(":status");
private readonly Http2Connection _connection;
private readonly int _streamId;
private readonly CreditManager _streamWindow;
private readonly HttpRequestMessage _request;
private HttpResponseMessage _response;
/// <summary>Stores any trailers received after returning the response content to the caller.</summary>
private List<KeyValuePair<HeaderDescriptor, string>> _trailers;
private ArrayBuffer _responseBuffer; // mutable struct, do not make this readonly
private int _pendingWindowUpdate;
private StreamCompletionState _requestCompletionState;
private StreamCompletionState _responseCompletionState;
private ResponseProtocolState _responseProtocolState;
// If this is not null, then we have received a reset from the server
// (i.e. RST_STREAM or general IO error processing the connection)
private Exception _resetException;
private bool _canRetry; // if _resetException != null, this indicates the stream was refused and so the request is retryable
// This flag indicates that, per section 8.1 of the RFC, the server completed the response and then sent a RST_STREAM with error = NO_ERROR.
// This is a signal to stop sending the request body, but the request is still considered successful.
private bool _requestBodyAbandoned;
/// <summary>
/// The core logic for the IValueTaskSource implementation.
///
/// Thread-safety:
/// _waitSource is used to coordinate between a producer indicating that something is available to process (either the connection's event loop
/// or a cancellation request) and a consumer doing that processing. There must only ever be a single consumer, namely this stream reading
/// data associated with the response. Because there is only ever at most one consumer, producers can trust that if _hasWaiter is true,
/// until the _waitSource is then set, no consumer will attempt to reset the _waitSource. A producer must still take SyncObj in order to
/// coordinate with other producers (e.g. a race between data arriving from the event loop and cancellation being requested), but while holding
/// the lock it can check whether _hasWaiter is true, and if it is, set _hasWaiter to false, exit the lock, and then set the _waitSource. Another
/// producer coming along will then see _hasWaiter as false and will not attempt to concurrently set _waitSource (which would violate _waitSource's
/// thread-safety), and no other consumer could come along in the interim, because _hasWaiter being true means that a consumer is already waiting
/// for _waitSource to be set, and legally there can only be one consumer. Once this producer sets _waitSource, the consumer could quickly loop
/// around to wait again, but invariants have all been maintained in the interim, and the consumer would need to take the SyncObj lock in order to
/// Reset _waitSource.
/// </summary>
private ManualResetValueTaskSourceCore<bool> _waitSource = new ManualResetValueTaskSourceCore<bool> { RunContinuationsAsynchronously = true }; // mutable struct, do not make this readonly
/// <summary>
/// Whether code has requested or is about to request a wait be performed and thus requires a call to SetResult to complete it.
/// This is read and written while holding the lock so that most operations on _waitSource don't need to be.
/// </summary>
private bool _hasWaiter;
private readonly CancellationTokenSource _requestBodyCancellationSource;
// This is a linked token combining the above source and the user-supplied token to SendRequestBodyAsync
private CancellationToken _requestBodyCancellationToken;
private readonly TaskCompletionSource<bool> _expect100ContinueWaiter;
private int _headerBudgetRemaining;
private const int StreamWindowSize = DefaultInitialWindowSize;
// See comment on ConnectionWindowThreshold.
private const int StreamWindowThreshold = StreamWindowSize / 8;
public Http2Stream(HttpRequestMessage request, Http2Connection connection, int streamId, int initialWindowSize)
{
_request = request;
_connection = connection;
_streamId = streamId;
_requestCompletionState = StreamCompletionState.InProgress;
_responseCompletionState = StreamCompletionState.InProgress;
_responseProtocolState = ResponseProtocolState.ExpectingStatus;
_responseBuffer = new ArrayBuffer(InitialStreamBufferSize, usePool: true);
_pendingWindowUpdate = 0;
_streamWindow = new CreditManager(this, nameof(_streamWindow), initialWindowSize);
_headerBudgetRemaining = connection._pool.Settings._maxResponseHeadersLength * 1024;
if (_request.Content == null)
{
_requestCompletionState = StreamCompletionState.Completed;
}
else
{
// Create this here because it can be canceled before SendRequestBodyAsync is even called.
// To avoid race conditions that can result in this being disposed in response to a server reset
// and then used to issue cancellation, we simply avoid disposing it; that's fine as long as we don't
// construct this via CreateLinkedTokenSource, in which case disposal is necessary to avoid a potential
// leak. If how this is constructed ever changes, we need to revisit disposing it, such as by
// using synchronization (e.g. using an Interlocked.Exchange to "consume" the _requestBodyCancellationSource
// for either disposal or issuing cancellation).
_requestBodyCancellationSource = new CancellationTokenSource();
if (_request.HasHeaders && _request.Headers.ExpectContinue == true)
{
// Create a TCS for handling Expect: 100-continue semantics. See WaitFor100ContinueAsync.
// Note we need to create this in the constructor, because we can receive a 100 Continue response at any time after the constructor finishes.
_expect100ContinueWaiter = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
}
}
if (NetEventSource.IsEnabled) Trace($"{request}, {nameof(initialWindowSize)}={initialWindowSize}");
}
private object SyncObject => _streamWindow;
public int StreamId => _streamId;
public HttpResponseMessage GetAndClearResponse()
{
// Once SendAsync completes, the Http2Stream should no longer hold onto the response message.
// Since the Http2Stream is rooted by the Http2Connection dictionary, doing so would prevent
// the response stream from being collected and finalized if it were to be dropped without
// being disposed first.
HttpResponseMessage r = _response;
_response = null;
return r;
}
public async Task SendRequestBodyAsync(CancellationToken cancellationToken)
{
if (_request.Content == null)
{
Debug.Assert(_requestCompletionState == StreamCompletionState.Completed);
return;
}
if (NetEventSource.IsEnabled) Trace($"{_request.Content}");
Debug.Assert(_requestBodyCancellationSource != null);
// Create a linked cancellation token source so that we can cancel the request in the event of receiving RST_STREAM
// and similiar situations where we need to cancel the request body (see Cancel method).
_requestBodyCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _requestBodyCancellationSource.Token).Token;
try
{
bool sendRequestContent = true;
if (_expect100ContinueWaiter != null)
{
sendRequestContent = await WaitFor100ContinueAsync(_requestBodyCancellationToken).ConfigureAwait(false);
}
if (sendRequestContent)
{
using (Http2WriteStream writeStream = new Http2WriteStream(this))
{
await _request.Content.CopyToAsync(writeStream, null, _requestBodyCancellationToken).ConfigureAwait(false);
}
}
if (NetEventSource.IsEnabled) Trace($"Finished sending request body.");
}
catch (Exception e)
{
if (NetEventSource.IsEnabled) Trace($"Failed to send request body: {e}");
bool signalWaiter = false;
bool sendReset = false;
Debug.Assert(!Monitor.IsEntered(SyncObject));
lock (SyncObject)
{
Debug.Assert(_requestCompletionState == StreamCompletionState.InProgress, $"Request already completed with state={_requestCompletionState}");
if (_requestBodyAbandoned)
{
// See comments on _requestBodyAbandoned.
// In this case, the request is still considered successful and we do not want to send a RST_STREAM,
// and we also don't want to propagate any error to the caller, in particular for non-duplex scenarios.
Debug.Assert(_responseCompletionState == StreamCompletionState.Completed);
_requestCompletionState = StreamCompletionState.Completed;
Complete();
return;
}
// This should not cause RST_STREAM to be sent because the request is still marked as in progress.
(signalWaiter, sendReset) = CancelResponseBody();
Debug.Assert(!sendReset);
_requestCompletionState = StreamCompletionState.Failed;
sendReset = true;
Complete();
}
if (sendReset)
{
SendReset();
}
if (signalWaiter)
{
_waitSource.SetResult(true);
}
throw;
}
// New scope here to avoid variable name conflict on "sendReset"
{
Debug.Assert(!Monitor.IsEntered(SyncObject));
bool sendReset = false;
lock (SyncObject)
{
Debug.Assert(_requestCompletionState == StreamCompletionState.InProgress, $"Request already completed with state={_requestCompletionState}");
_requestCompletionState = StreamCompletionState.Completed;
if (_responseCompletionState == StreamCompletionState.Failed)
{
// Note, we can reach this point if the response stream failed but cancellation didn't propagate before we finished.
sendReset = true;
Complete();
}
else
{
if (_responseCompletionState == StreamCompletionState.Completed)
{
Complete();
}
}
}
if (sendReset)
{
SendReset();
}
else
{
// Send EndStream asynchronously and without cancellation.
// If this fails, it means that the connection is aborting and we will be reset.
_connection.LogExceptions(_connection.SendEndStreamAsync(_streamId));
}
}
}
// Delay sending request body if we sent Expect: 100-continue.
// We can either get 100 response from server and send body
// or we may exceed timeout and send request body anyway.
// If we get response status >= 300, we will not send the request body.
public async ValueTask<bool> WaitFor100ContinueAsync(CancellationToken cancellationToken)
{
Debug.Assert(_request.Content != null);
if (NetEventSource.IsEnabled) Trace($"Waiting to send request body content for 100-Continue.");
// use TCS created in constructor. It will complete when one of two things occurs:
// 1. if a timer fires before we receive the relevant response from the server.
// 2. if we receive the relevant response from the server before a timer fires.
// In the first case, we could run this continuation synchronously, but in the latter, we shouldn't,
// as we could end up starting the body copy operation on the main event loop thread, which could
// then starve the processing of other requests. So, we make the TCS RunContinuationsAsynchronously.
bool sendRequestContent;
TaskCompletionSource<bool> waiter = _expect100ContinueWaiter;
using (var expect100Timer = new Timer(s =>
{
var thisRef = (Http2Stream)s;
if (NetEventSource.IsEnabled) thisRef.Trace($"100-Continue timer expired.");
thisRef._expect100ContinueWaiter?.TrySetResult(true);
}, this, _connection._pool.Settings._expect100ContinueTimeout, Timeout.InfiniteTimeSpan))
{
sendRequestContent = await waiter.Task.ConfigureAwait(false);
// By now, either we got a response from the server or the timer expired.
}
return sendRequestContent;
}
private void SendReset()
{
Debug.Assert(!Monitor.IsEntered(SyncObject));
Debug.Assert(_requestCompletionState != StreamCompletionState.InProgress);
Debug.Assert(_responseCompletionState != StreamCompletionState.InProgress);
Debug.Assert(_requestCompletionState == StreamCompletionState.Failed || _responseCompletionState == StreamCompletionState.Failed,
"Reset called but neither request nor response is failed");
if (NetEventSource.IsEnabled) Trace($"Stream reset. Request={_requestCompletionState}, Response={_responseCompletionState}.");
// Don't send a RST_STREAM if we've already received one from the server.
if (_resetException == null)
{
_connection.LogExceptions(_connection.SendRstStreamAsync(_streamId, Http2ProtocolErrorCode.Cancel));
}
}
private void Complete()
{
Debug.Assert(Monitor.IsEntered(SyncObject));
Debug.Assert(_requestCompletionState != StreamCompletionState.InProgress);
Debug.Assert(_responseCompletionState != StreamCompletionState.InProgress);
if (NetEventSource.IsEnabled) Trace($"Stream complete. Request={_requestCompletionState}, Response={_responseCompletionState}.");
_connection.RemoveStream(this);
_streamWindow.Dispose();
}
private void Cancel()
{
if (NetEventSource.IsEnabled) Trace("");
CancellationTokenSource requestBodyCancellationSource = null;
bool signalWaiter = false;
bool sendReset = false;
Debug.Assert(!Monitor.IsEntered(SyncObject));
lock (SyncObject)
{
if (_requestCompletionState == StreamCompletionState.InProgress)
{
requestBodyCancellationSource = _requestBodyCancellationSource;
Debug.Assert(requestBodyCancellationSource != null);
}
(signalWaiter, sendReset) = CancelResponseBody();
}
if (requestBodyCancellationSource != null)
{
// When cancellation propagates, SendRequestBodyAsync will set _requestCompletionState to Failed
requestBodyCancellationSource.Cancel();
}
if (sendReset)
{
SendReset();
}
if (signalWaiter)
{
_waitSource.SetResult(true);
}
}
// Returns whether the waiter should be signalled or not.
private (bool signalWaiter, bool sendReset) CancelResponseBody()
{
Debug.Assert(Monitor.IsEntered(SyncObject));
bool sendReset = false;
if (_responseCompletionState == StreamCompletionState.InProgress)
{
_responseCompletionState = StreamCompletionState.Failed;
if (_requestCompletionState != StreamCompletionState.InProgress)
{
sendReset = true;
Complete();
}
}
// Discard any remaining buffered response data
if (_responseBuffer.ActiveLength != 0)
{
_responseBuffer.Discard(_responseBuffer.ActiveLength);
}
_responseProtocolState = ResponseProtocolState.Aborted;
bool signalWaiter = _hasWaiter;
_hasWaiter = false;
return (signalWaiter, sendReset);
}
public void OnWindowUpdate(int amount) => _streamWindow.AdjustCredit(amount);
public void OnHeader(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value)
{
if (NetEventSource.IsEnabled) Trace($"{Encoding.ASCII.GetString(name)}: {Encoding.ASCII.GetString(value)}");
Debug.Assert(name != null && name.Length > 0);
_headerBudgetRemaining -= name.Length + value.Length;
if (_headerBudgetRemaining < 0)
{
throw new HttpRequestException(SR.Format(SR.net_http_response_headers_exceeded_length, _connection._pool.Settings._maxResponseHeadersLength * 1024L));
}
// TODO: ISSUE 31309: Optimize HPACK static table decoding
Debug.Assert(!Monitor.IsEntered(SyncObject));
lock (SyncObject)
{
if (_responseProtocolState == ResponseProtocolState.Aborted)
{
// We could have aborted while processing the header block.
return;
}
if (name[0] == (byte)':')
{
if (_responseProtocolState != ResponseProtocolState.ExpectingHeaders && _responseProtocolState != ResponseProtocolState.ExpectingStatus)
{
// Pseudo-headers are allowed only in header block
if (NetEventSource.IsEnabled) Trace($"Pseudo-header received in {_responseProtocolState} state.");
throw new HttpRequestException(SR.net_http_invalid_response_pseudo_header_in_trailer);
}
if (name.SequenceEqual(s_statusHeaderName))
{
if (_responseProtocolState != ResponseProtocolState.ExpectingStatus)
{
if (NetEventSource.IsEnabled) Trace("Received extra status header.");
throw new HttpRequestException(SR.Format(SR.net_http_invalid_response_status_code, "duplicate status"));
}
byte status1, status2, status3;
if (value.Length != 3 ||
!IsDigit(status1 = value[0]) ||
!IsDigit(status2 = value[1]) ||
!IsDigit(status3 = value[2]))
{
throw new HttpRequestException(SR.Format(SR.net_http_invalid_response_status_code, Encoding.ASCII.GetString(value)));
}
int statusValue = (100 * (status1 - '0') + 10 * (status2 - '0') + (status3 - '0'));
_response = new HttpResponseMessage()
{
Version = HttpVersion.Version20,
RequestMessage = _request,
Content = new HttpConnectionResponseContent(),
StatusCode = (HttpStatusCode)statusValue
};
if (statusValue < 200)
{
// We do not process headers from 1xx responses.
_responseProtocolState = ResponseProtocolState.ExpectingIgnoredHeaders;
if (_response.StatusCode == HttpStatusCode.Continue && _expect100ContinueWaiter != null)
{
if (NetEventSource.IsEnabled) Trace("Received 100-Continue status.");
_expect100ContinueWaiter.TrySetResult(true);
}
}
else
{
_responseProtocolState = ResponseProtocolState.ExpectingHeaders;
// If we are waiting for a 100-continue response, signal the waiter now.
if (_expect100ContinueWaiter != null)
{
// If the final status code is >= 300, skip sending the body.
bool shouldSendBody = (statusValue < 300);
if (NetEventSource.IsEnabled) Trace($"Expecting 100 Continue but received final status {statusValue}.");
_expect100ContinueWaiter.TrySetResult(shouldSendBody);
}
}
}
else
{
if (NetEventSource.IsEnabled) Trace($"Invalid response pseudo-header '{Encoding.ASCII.GetString(name)}'.");
throw new HttpRequestException(SR.net_http_invalid_response);
}
}
else
{
if (_responseProtocolState == ResponseProtocolState.ExpectingIgnoredHeaders)
{
// for 1xx response we ignore all headers.
return;
}
if (_responseProtocolState != ResponseProtocolState.ExpectingHeaders && _responseProtocolState != ResponseProtocolState.ExpectingTrailingHeaders)
{
if (NetEventSource.IsEnabled) Trace("Received header before status.");
throw new HttpRequestException(SR.net_http_invalid_response);
}
if (!HeaderDescriptor.TryGet(name, out HeaderDescriptor descriptor))
{
// Invalid header name
throw new HttpRequestException(SR.Format(SR.net_http_invalid_response_header_name, Encoding.ASCII.GetString(name)));
}
string headerValue = descriptor.GetHeaderValue(value);
// Note we ignore the return value from TryAddWithoutValidation;
// if the header can't be added, we silently drop it.
if (_responseProtocolState == ResponseProtocolState.ExpectingTrailingHeaders)
{
Debug.Assert(_trailers != null);
_trailers.Add(KeyValuePair.Create(descriptor.HeaderType == HttpHeaderType.Request ? descriptor.AsCustomHeader() : descriptor, headerValue));
}
else if (descriptor.HeaderType == HttpHeaderType.Content)
{
Debug.Assert(_response != null);
_response.Content.Headers.TryAddWithoutValidation(descriptor, headerValue);
}
else
{
Debug.Assert(_response != null);
_response.Headers.TryAddWithoutValidation(descriptor.HeaderType == HttpHeaderType.Request ? descriptor.AsCustomHeader() : descriptor, headerValue);
}
}
}
}
public void OnHeadersStart()
{
Debug.Assert(!Monitor.IsEntered(SyncObject));
lock (SyncObject)
{
if (_responseProtocolState == ResponseProtocolState.Aborted)
{
return;
}
if (_responseProtocolState != ResponseProtocolState.ExpectingStatus && _responseProtocolState != ResponseProtocolState.ExpectingData)
{
throw new Http2ConnectionException(Http2ProtocolErrorCode.ProtocolError);
}
if (_responseProtocolState == ResponseProtocolState.ExpectingData)
{
_responseProtocolState = ResponseProtocolState.ExpectingTrailingHeaders;
_trailers ??= new List<KeyValuePair<HeaderDescriptor, string>>();
}
}
}
public void OnHeadersComplete(bool endStream)
{
Debug.Assert(!Monitor.IsEntered(SyncObject));
bool signalWaiter;
lock (SyncObject)
{
if (_responseProtocolState == ResponseProtocolState.Aborted)
{
return;
}
if (_responseProtocolState != ResponseProtocolState.ExpectingHeaders && _responseProtocolState != ResponseProtocolState.ExpectingTrailingHeaders && _responseProtocolState != ResponseProtocolState.ExpectingIgnoredHeaders)
{
throw new Http2ConnectionException(Http2ProtocolErrorCode.ProtocolError);
}
if (_responseProtocolState == ResponseProtocolState.ExpectingHeaders)
{
_responseProtocolState = endStream ? ResponseProtocolState.Complete : ResponseProtocolState.ExpectingData;
}
else if (_responseProtocolState == ResponseProtocolState.ExpectingTrailingHeaders)
{
if (!endStream)
{
if (NetEventSource.IsEnabled) Trace("Trailing headers received without endStream");
throw new Http2ConnectionException(Http2ProtocolErrorCode.ProtocolError);
}
_responseProtocolState = ResponseProtocolState.Complete;
}
else if (_responseProtocolState == ResponseProtocolState.ExpectingIgnoredHeaders)
{
if (endStream)
{
// we should not get endStream while processing 1xx response.
throw new Http2ConnectionException(Http2ProtocolErrorCode.ProtocolError);
}
_responseProtocolState = ResponseProtocolState.ExpectingStatus;
// We should wait for final response before signaling to waiter.
return;
}
else
{
_responseProtocolState = ResponseProtocolState.ExpectingData;
}
if (endStream)
{
Debug.Assert(_responseCompletionState == StreamCompletionState.InProgress, $"Response already completed with state={_responseCompletionState}");
_responseCompletionState = StreamCompletionState.Completed;
if (_requestCompletionState == StreamCompletionState.Completed)
{
Complete();
}
// We should never reach here with the request failed. It's only set to Failed in SendRequestBodyAsync after we've called Cancel,
// which will set the _responseCompletionState to Failed, meaning we'll never get here.
Debug.Assert(_requestCompletionState != StreamCompletionState.Failed);
}
signalWaiter = _hasWaiter;
_hasWaiter = false;
}
if (signalWaiter)
{
_waitSource.SetResult(true);
}
}
public void OnResponseData(ReadOnlySpan<byte> buffer, bool endStream)
{
Debug.Assert(!Monitor.IsEntered(SyncObject));
bool signalWaiter;
lock (SyncObject)
{
if (_responseProtocolState == ResponseProtocolState.Aborted)
{
return;
}
if (_responseProtocolState != ResponseProtocolState.ExpectingData)
{
// Flow control messages are not valid in this state.
throw new Http2ConnectionException(Http2ProtocolErrorCode.ProtocolError);
}
if (_responseBuffer.ActiveLength + buffer.Length > StreamWindowSize)
{
// Window size exceeded.
throw new Http2ConnectionException(Http2ProtocolErrorCode.FlowControlError);
}
_responseBuffer.EnsureAvailableSpace(buffer.Length);
buffer.CopyTo(_responseBuffer.AvailableSpan);
_responseBuffer.Commit(buffer.Length);
if (endStream)
{
_responseProtocolState = ResponseProtocolState.Complete;
Debug.Assert(_responseCompletionState == StreamCompletionState.InProgress, $"Response already completed with state={_responseCompletionState}");
_responseCompletionState = StreamCompletionState.Completed;
if (_requestCompletionState == StreamCompletionState.Completed)
{
Complete();
}
// We should never reach here with the request failed. It's only set to Failed in SendRequestBodyAsync after we've called Cancel,
// which will set the _responseCompletionState to Failed, meaning we'll never get here.
Debug.Assert(_requestCompletionState != StreamCompletionState.Failed);
}
signalWaiter = _hasWaiter;
_hasWaiter = false;
}
if (signalWaiter)
{
_waitSource.SetResult(true);
}
}
// This is called in several different cases:
// (1) Receiving RST_STREAM on this stream. If so, the resetStreamErrorCode will be non-null, and canRetry will be true only if the error code was REFUSED_STREAM.
// (2) Receiving GOAWAY that indicates this stream has not been processed. If so, canRetry will be true.
// (3) Connection IO failure or protocol violation. If so, resetException will contain the relevant exception and canRetry will be false.
// (4) Receiving EOF from the server. If so, resetException will contain an exception like "expected 9 bytes of data", and canRetry will be false.
public void OnReset(Exception resetException, Http2ProtocolErrorCode? resetStreamErrorCode = null, bool canRetry = false)
{
if (NetEventSource.IsEnabled) Trace($"{nameof(resetException)}={resetException}, {nameof(resetStreamErrorCode)}={resetStreamErrorCode}");
bool cancel = false;
CancellationTokenSource requestBodyCancellationSource = null;
Debug.Assert(!Monitor.IsEntered(SyncObject));
lock (SyncObject)
{
// If we've already finished, don't actually reset the stream.
// Otherwise, any waiters that haven't executed yet will see the _resetException and throw.
// This can happen, for example, when the server finishes the request and then closes the connection,
// but the waiter hasn't woken up yet.
if (_requestCompletionState == StreamCompletionState.Completed && _responseCompletionState == StreamCompletionState.Completed)
{
return;
}
// It's possible we could be called twice, e.g. we receive a RST_STREAM and then the whole connection dies
// before we have a chance to process cancellation and tear everything down. Just ignore this.
if (_resetException != null)
{
return;
}
// If the server told us the request has not been processed (via Last-Stream-ID on GOAWAY),
// but we've already received some response data from the server, then the server lied to us.
// In this case, don't allow the request to be retried.
if (canRetry && _responseProtocolState != ResponseProtocolState.ExpectingStatus)
{
canRetry = false;
}
// Per section 8.1 in the RFC:
// If the server has completed the response body (i.e. we've received EndStream)
// but the request body is still sending, and we then receive a RST_STREAM with errorCode = NO_ERROR,
// we treat this specially and simply cancel sending the request body, rather than treating
// the entire request as failed.
if (resetStreamErrorCode == Http2ProtocolErrorCode.NoError &&
_responseCompletionState == StreamCompletionState.Completed)
{
if (_requestCompletionState == StreamCompletionState.InProgress)
{
_requestBodyAbandoned = true;
requestBodyCancellationSource = _requestBodyCancellationSource;
Debug.Assert(requestBodyCancellationSource != null);
}
}
else
{
_resetException = resetException;
_canRetry = canRetry;
cancel = true;
}
}
if (requestBodyCancellationSource != null)
{
Debug.Assert(_requestBodyAbandoned);
Debug.Assert(!cancel);
requestBodyCancellationSource.Cancel();
}
else
{
Cancel();
}
}
private void CheckResponseBodyState()
{
Debug.Assert(Monitor.IsEntered(SyncObject));
if (_resetException != null)
{
if (_canRetry)
{
throw new HttpRequestException(SR.net_http_request_aborted, _resetException, allowRetry: RequestRetryType.RetryOnSameOrNextProxy);
}
throw new IOException(SR.net_http_request_aborted, _resetException);
}
if (_responseProtocolState == ResponseProtocolState.Aborted)
{
throw new IOException(SR.net_http_request_aborted);
}
}
// Determine if we have enough data to process up to complete final response headers.
private (bool wait, bool isEmptyResponse) TryEnsureHeaders()
{
Debug.Assert(!Monitor.IsEntered(SyncObject));
lock (SyncObject)
{
CheckResponseBodyState();
if (_responseProtocolState == ResponseProtocolState.ExpectingHeaders || _responseProtocolState == ResponseProtocolState.ExpectingIgnoredHeaders || _responseProtocolState == ResponseProtocolState.ExpectingStatus)
{
Debug.Assert(!_hasWaiter);
_hasWaiter = true;
_waitSource.Reset();
return (true, false);
}
else if (_responseProtocolState == ResponseProtocolState.ExpectingData || _responseProtocolState == ResponseProtocolState.ExpectingTrailingHeaders)
{
return (false, false);
}
else
{
Debug.Assert(_responseProtocolState == ResponseProtocolState.Complete);
return (false, _responseBuffer.ActiveLength == 0);
}
}
}
public async Task ReadResponseHeadersAsync(CancellationToken cancellationToken)
{
bool emptyResponse;
try
{
// Wait for response headers to be read.
bool wait;
// Process all informational responses if any and wait for final status.
(wait, emptyResponse) = TryEnsureHeaders();
if (wait)
{
await GetWaiterTask(cancellationToken).ConfigureAwait(false);
(wait, emptyResponse) = TryEnsureHeaders();
Debug.Assert(!wait);
}
}
catch
{
Cancel();
throw;
}
// Start to process the response body.
var responseContent = (HttpConnectionResponseContent)_response.Content;
if (emptyResponse)
{
// If there are any trailers, copy them over to the response. Normally this would be handled by
// the response stream hitting EOF, but if there is no response body, we do it here.
CopyTrailersToResponseMessage(_response);
responseContent.SetStream(EmptyReadStream.Instance);
}
else
{
responseContent.SetStream(new Http2ReadStream(this));
}
// Process Set-Cookie headers.
if (_connection._pool.Settings._useCookies)
{
CookieHelper.ProcessReceivedCookies(_response, _connection._pool.Settings._cookieContainer);
}
}
private void ExtendWindow(int amount)
{
Debug.Assert(amount > 0);
Debug.Assert(_pendingWindowUpdate < StreamWindowThreshold);
if (_responseProtocolState != ResponseProtocolState.ExpectingData)
{
// We are not expecting any more data (because we've either completed or aborted).
// So no need to send any more WINDOW_UPDATEs.
return;
}
_pendingWindowUpdate += amount;
if (_pendingWindowUpdate < StreamWindowThreshold)
{
return;
}
int windowUpdateSize = _pendingWindowUpdate;
_pendingWindowUpdate = 0;
_connection.LogExceptions(_connection.SendWindowUpdateAsync(_streamId, windowUpdateSize));
}
private (bool wait, int bytesRead) TryReadFromBuffer(Span<byte> buffer)
{
Debug.Assert(buffer.Length > 0);
Debug.Assert(!Monitor.IsEntered(SyncObject));
lock (SyncObject)
{
CheckResponseBodyState();
if (_responseBuffer.ActiveLength > 0)
{
int bytesRead = Math.Min(buffer.Length, _responseBuffer.ActiveLength);
_responseBuffer.ActiveSpan.Slice(0, bytesRead).CopyTo(buffer);
_responseBuffer.Discard(bytesRead);
return (false, bytesRead);
}
else if (_responseProtocolState == ResponseProtocolState.Complete)
{
return (false, 0);
}
Debug.Assert(_responseProtocolState == ResponseProtocolState.ExpectingData || _responseProtocolState == ResponseProtocolState.ExpectingTrailingHeaders);
Debug.Assert(!_hasWaiter);
_hasWaiter = true;
_waitSource.Reset();
return (true, 0);
}
}
public int ReadData(Span<byte> buffer, HttpResponseMessage responseMessage)
{
if (buffer.Length == 0)
{
return 0;
}
(bool wait, int bytesRead) = TryReadFromBuffer(buffer);
if (wait)
{
// Synchronously block waiting for data to be produced.
Debug.Assert(bytesRead == 0);
GetWaiterTask(default).AsTask().GetAwaiter().GetResult();
(wait, bytesRead) = TryReadFromBuffer(buffer);
Debug.Assert(!wait);
}
if (bytesRead != 0)
{
ExtendWindow(bytesRead);
}
else
{
// We've hit EOF. Pull in from the Http2Stream any trailers that were temporarily stored there.
CopyTrailersToResponseMessage(responseMessage);
}
return bytesRead;
}
public async ValueTask<int> ReadDataAsync(Memory<byte> buffer, HttpResponseMessage responseMessage, CancellationToken cancellationToken)
{
if (buffer.Length == 0)
{
return 0;
}
(bool wait, int bytesRead) = TryReadFromBuffer(buffer.Span);
if (wait)
{
Debug.Assert(bytesRead == 0);
await GetWaiterTask(cancellationToken).ConfigureAwait(false);
(wait, bytesRead) = TryReadFromBuffer(buffer.Span);
Debug.Assert(!wait);
}
if (bytesRead != 0)
{
ExtendWindow(bytesRead);
}
else
{
// We've hit EOF. Pull in from the Http2Stream any trailers that were temporarily stored there.
CopyTrailersToResponseMessage(responseMessage);
}
return bytesRead;
}
private void CopyTrailersToResponseMessage(HttpResponseMessage responseMessage)
{
if (_trailers != null && _trailers.Count > 0)
{
foreach (KeyValuePair<HeaderDescriptor, string> trailer in _trailers)
{
responseMessage.TrailingHeaders.TryAddWithoutValidation(trailer.Key, trailer.Value);
}
_trailers.Clear();
}
}
private async ValueTask SendDataAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken)
{
ReadOnlyMemory<byte> remaining = buffer;
// Deal with ActiveIssue #9071:
// Custom HttpContent classes do not get passed the cancellationToken.
// So, inject the expected CancellationToken here, to ensure we can cancel the request body send if needed.
CancellationTokenSource customCancellationSource = null;
if (!cancellationToken.CanBeCanceled)
{
cancellationToken = _requestBodyCancellationToken;
}
else if (cancellationToken != _requestBodyCancellationToken)
{
// User passed a custom CancellationToken.
// We can't tell if it includes our Token or not, so assume it doesn't.
customCancellationSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _requestBodyCancellationSource.Token);
cancellationToken = customCancellationSource.Token;
}
using (customCancellationSource)
{
while (remaining.Length > 0)
{
int sendSize = await _streamWindow.RequestCreditAsync(remaining.Length, cancellationToken).ConfigureAwait(false);
ReadOnlyMemory<byte> current;
(current, remaining) = SplitBuffer(remaining, sendSize);
await _connection.SendStreamDataAsync(_streamId, current, cancellationToken).ConfigureAwait(false);
}
}
}
private void CloseResponseBody()
{
// Check if the response body has been fully consumed.
bool fullyConsumed = false;
Debug.Assert(!Monitor.IsEntered(SyncObject));
lock (SyncObject)
{
if (_responseBuffer.ActiveLength == 0 && _responseProtocolState == ResponseProtocolState.Complete)
{
fullyConsumed = true;
}
}
// If the response body isn't completed, cancel it now.
if (!fullyConsumed)
{
Cancel();
}
_responseBuffer.Dispose();
}
// This object is itself usable as a backing source for ValueTask. Since there's only ever one awaiter
// for this object's state transitions at a time, we allow the object to be awaited directly. All functionality
// associated with the implementation is just delegated to the ManualResetValueTaskSourceCore.
ValueTaskSourceStatus IValueTaskSource.GetStatus(short token) => _waitSource.GetStatus(token);
void IValueTaskSource.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) => _waitSource.OnCompleted(continuation, state, token, flags);
void IValueTaskSource.GetResult(short token) => _waitSource.GetResult(token);
private ValueTask GetWaiterTask(CancellationToken cancellationToken)
{
// No locking is required here to access _waitSource. To be here, we've already updated _hasWaiter (while holding the lock)
// to indicate that we would be creating this waiter, and at that point the only code that could be await'ing _waitSource or
// Reset'ing it is this code here. It's possible for this to race with the _waitSource being completed, but that's ok and is
// handled by _waitSource as one of its primary purposes. We can't assert _hasWaiter here, though, as once we released the
// lock, a producer could have seen _hasWaiter as true and both set it to false and signaled _waitSource.
// With HttpClient, the supplied cancellation token will always be cancelable, as HttpClient supplies a token that
// will have cancellation requested if CancelPendingRequests is called (or when a non-infinite Timeout expires).
// However, this could still be non-cancelable if HttpMessageInvoker was used, at which point this will only be
// cancelable if the caller's token was cancelable. To avoid the extra allocation here in such a case, we make
// this pay-for-play: if the token isn't cancelable, return a ValueTask wrapping this object directly, and only
// if it is cancelable, then register for the cancellation callback, allocate a task for the asynchronously
// completing case, etc.
return cancellationToken.CanBeCanceled ?
GetCancelableWaiterTask(cancellationToken) :
new ValueTask(this, _waitSource.Version);
}
private async ValueTask GetCancelableWaiterTask(CancellationToken cancellationToken)
{
using (cancellationToken.UnsafeRegister(s =>
{
var thisRef = (Http2Stream)s;
bool signalWaiter;
Debug.Assert(!Monitor.IsEntered(thisRef.SyncObject));
lock (thisRef.SyncObject)
{
signalWaiter = thisRef._hasWaiter;
thisRef._hasWaiter = false;
}
if (signalWaiter)
{
// Wake up the wait. It will then immediately check whether cancellation was requested and throw if it was.
thisRef._waitSource.SetResult(true);
}
}, this))
{
await new ValueTask(this, _waitSource.Version).ConfigureAwait(false);
}
CancellationHelper.ThrowIfCancellationRequested(cancellationToken);
}
public void Trace(string message, [CallerMemberName] string memberName = null) =>
_connection.Trace(_streamId, message, memberName);
private enum ResponseProtocolState : byte
{
ExpectingStatus,
ExpectingIgnoredHeaders,
ExpectingHeaders,
ExpectingData,
ExpectingTrailingHeaders,
Complete,
Aborted
}
private enum StreamCompletionState : byte
{
InProgress,
Completed,
Failed
}
private sealed class Http2ReadStream : HttpBaseStream
{
private Http2Stream _http2Stream;
private readonly HttpResponseMessage _responseMessage;
public Http2ReadStream(Http2Stream http2Stream)
{
Debug.Assert(http2Stream != null);
Debug.Assert(http2Stream._response != null);
_http2Stream = http2Stream;
_responseMessage = _http2Stream._response;
}
~Http2ReadStream()
{
if (NetEventSource.IsEnabled) _http2Stream?.Trace("");
try
{
Dispose(disposing: false);
}
catch (Exception e)
{
if (NetEventSource.IsEnabled) _http2Stream?.Trace($"Error: {e}");
}
}
protected override void Dispose(bool disposing)
{
Http2Stream http2Stream = Interlocked.Exchange(ref _http2Stream, null);
if (http2Stream == null)
{
return;
}
// Technically we shouldn't be doing the following work when disposing == false,
// as the following work relies on other finalizable objects. But given the HTTP/2
// protocol, we have little choice: if someone drops the Http2ReadStream without
// disposing of it, we need to a) signal to the server that the stream is being
// canceled, and b) clean up the associated state in the Http2Connection.
http2Stream.CloseResponseBody();
base.Dispose(disposing);
}
public override bool CanRead => true;
public override bool CanWrite => false;
public override int Read(Span<byte> destination)
{
Http2Stream http2Stream = _http2Stream ?? throw new ObjectDisposedException(nameof(Http2ReadStream));
return http2Stream.ReadData(destination, _responseMessage);
}
public override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken)
{
Http2Stream http2Stream = _http2Stream;
if (http2Stream == null)
{
return new ValueTask<int>(Task.FromException<int>(ExceptionDispatchInfo.SetCurrentStackTrace(new ObjectDisposedException(nameof(Http2ReadStream)))));
}
if (cancellationToken.IsCancellationRequested)
{
return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken));
}
return http2Stream.ReadDataAsync(destination, _responseMessage, cancellationToken);
}
public override void Write(ReadOnlySpan<byte> buffer) => throw new NotSupportedException(SR.net_http_content_readonly_stream);
public override ValueTask WriteAsync(ReadOnlyMemory<byte> destination, CancellationToken cancellationToken) => throw new NotSupportedException();
}
private sealed class Http2WriteStream : HttpBaseStream
{
private Http2Stream _http2Stream;
public Http2WriteStream(Http2Stream http2Stream)
{
Debug.Assert(http2Stream != null);
_http2Stream = http2Stream;
}
protected override void Dispose(bool disposing)
{
Http2Stream http2Stream = Interlocked.Exchange(ref _http2Stream, null);
if (http2Stream == null)
{
return;
}
base.Dispose(disposing);
}
public override bool CanRead => false;
public override bool CanWrite => true;
public override int Read(Span<byte> buffer) => throw new NotSupportedException();
public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken) => throw new NotSupportedException();
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken)
{
Http2Stream http2Stream = _http2Stream;
if (http2Stream == null)
{
return new ValueTask(Task.FromException(new ObjectDisposedException(nameof(Http2WriteStream))));
}
return http2Stream.SendDataAsync(buffer, cancellationToken);
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled(cancellationToken);
}
Http2Stream http2Stream = _http2Stream;
if (http2Stream == null)
{
return Task.CompletedTask;
}
// In order to flush this stream's previous writes, we need to flush the connection. We
// really only need to do any work here if the connection's buffer has any pending writes
// from this stream, but we currently lack a good/efficient/safe way of doing that.
return http2Stream._connection.FlushAsync(cancellationToken);
}
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;
using System.Text;
using System.Collections.Generic;
using log4net;
using Nini.Config;
using OpenSim.Framework;
using OpenMetaverse;
using Mono.Addins;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Framework.Servers;
[assembly:AddinRoot("Robust", OpenSim.VersionInfo.VersionNumber)]
namespace OpenSim.Server.Base
{
[TypeExtensionPoint(Path="/Robust/Connector", Name="RobustConnector")]
public interface IRobustConnector
{
string ConfigName
{
get;
}
bool Enabled
{
get;
}
string PluginPath
{
get;
set;
}
uint Configure(IConfigSource config);
void Initialize(IHttpServer server);
void Unload();
}
public class PluginLoader
{
static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public AddinRegistry Registry
{
get;
private set;
}
public IConfigSource Config
{
get;
private set;
}
public PluginLoader(IConfigSource config, string registryPath)
{
Config = config;
Registry = new AddinRegistry(registryPath, ".");
//suppress_console_output_(true);
AddinManager.Initialize(registryPath);
//suppress_console_output_(false);
AddinManager.Registry.Update();
CommandManager commandmanager = new CommandManager(Registry);
AddinManager.AddExtensionNodeHandler("/Robust/Connector", OnExtensionChanged);
}
private static TextWriter prev_console_;
// Temporarily masking the errors reported on start
// This is caused by a non-managed dll in the ./bin dir
// when the registry is initialized. The dll belongs to
// libomv, which has a hard-coded path to "." for pinvoke
// to load the openjpeg dll
//
// Will look for a way to fix, but for now this keeps the
// confusion to a minimum. this was copied from our region
// plugin loader, we have been doing this in there for a long time.
//
public void suppress_console_output_(bool save)
{
if (save)
{
prev_console_ = System.Console.Out;
System.Console.SetOut(new StreamWriter(Stream.Null));
}
else
{
if (prev_console_ != null)
System.Console.SetOut(prev_console_);
}
}
private void OnExtensionChanged(object s, ExtensionNodeEventArgs args)
{
IRobustConnector connector = (IRobustConnector)args.ExtensionObject;
Addin a = Registry.GetAddin(args.ExtensionNode.Addin.Id);
if(a == null)
{
Registry.Rebuild(null);
a = Registry.GetAddin(args.ExtensionNode.Addin.Id);
}
switch(args.Change)
{
case ExtensionChange.Add:
if (a.AddinFile.Contains(Registry.DefaultAddinsFolder))
{
m_log.InfoFormat("[SERVER UTILS]: Adding {0} from registry", a.Name);
connector.PluginPath = System.IO.Path.Combine(Registry.DefaultAddinsFolder,a.Name.Replace(',', '.')); }
else
{
m_log.InfoFormat("[SERVER UTILS]: Adding {0} from ./bin", a.Name);
connector.PluginPath = a.AddinFile;
}
LoadPlugin(connector);
break;
case ExtensionChange.Remove:
m_log.InfoFormat("[SERVER UTILS]: Removing {0}", a.Name);
UnloadPlugin(connector);
break;
}
}
private void LoadPlugin(IRobustConnector connector)
{
IHttpServer server = null;
uint port = connector.Configure(Config);
if(connector.Enabled)
{
server = GetServer(connector, port);
connector.Initialize(server);
}
else
{
m_log.InfoFormat("[SERVER UTILS]: {0} Disabled.", connector.ConfigName);
}
}
private void UnloadPlugin(IRobustConnector connector)
{
m_log.InfoFormat("[SERVER UTILS]: Unloading {0}", connector.ConfigName);
connector.Unload();
}
private IHttpServer GetServer(IRobustConnector connector, uint port)
{
IHttpServer server;
if(port != 0)
server = MainServer.GetHttpServer(port);
else
server = MainServer.Instance;
return server;
}
}
public static class ServerUtils
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public static byte[] SerializeResult(XmlSerializer xs, object data)
{
using (MemoryStream ms = new MemoryStream())
using (XmlTextWriter xw = new XmlTextWriter(ms, Util.UTF8))
{
xw.Formatting = Formatting.Indented;
xs.Serialize(xw, data);
xw.Flush();
ms.Seek(0, SeekOrigin.Begin);
byte[] ret = ms.GetBuffer();
Array.Resize(ref ret, (int)ms.Length);
return ret;
}
}
/// <summary>
/// Load a plugin from a dll with the given class or interface
/// </summary>
/// <param name="dllName"></param>
/// <param name="args">The arguments which control which constructor is invoked on the plugin</param>
/// <returns></returns>
public static T LoadPlugin<T> (string dllName, Object[] args) where T:class
{
// This is good to debug configuration problems
//if (dllName == string.Empty)
// Util.PrintCallStack();
string className = String.Empty;
// The path for a dynamic plugin will contain ":" on Windows
string[] parts = dllName.Split (new char[] {':'});
if (parts [0].Length > 1)
{
dllName = parts [0];
if (parts.Length > 1)
className = parts[1];
}
else
{
// This is Windows - we must replace the ":" in the path
dllName = String.Format ("{0}:{1}", parts [0], parts [1]);
if (parts.Length > 2)
className = parts[2];
}
return LoadPlugin<T>(dllName, className, args);
}
/// <summary>
/// Load a plugin from a dll with the given class or interface
/// </summary>
/// <param name="dllName"></param>
/// <param name="className"></param>
/// <param name="args">The arguments which control which constructor is invoked on the plugin</param>
/// <returns></returns>
public static T LoadPlugin<T>(string dllName, string className, Object[] args) where T:class
{
string interfaceName = typeof(T).ToString();
try
{
Assembly pluginAssembly = Assembly.LoadFrom(dllName);
foreach (Type pluginType in pluginAssembly.GetTypes())
{
if (pluginType.IsPublic)
{
if (className != String.Empty
&& pluginType.ToString() != pluginType.Namespace + "." + className)
continue;
Type typeInterface = pluginType.GetInterface(interfaceName);
if (typeInterface != null)
{
T plug = null;
try
{
plug = (T)Activator.CreateInstance(pluginType,
args);
}
catch (Exception e)
{
if (!(e is System.MissingMethodException))
{
m_log.Error(string.Format("[SERVER UTILS]: Error loading plugin {0} from {1}. Exception: {2}",
interfaceName,
dllName,
e.InnerException == null ? e.Message : e.InnerException.Message),
e);
}
m_log.ErrorFormat("[SERVER UTILS]: Error loading plugin {0}: {1} args.Length {2}", dllName, e.Message, args.Length);
return null;
}
return plug;
}
}
}
return null;
}
catch (ReflectionTypeLoadException rtle)
{
m_log.Error(string.Format("[SERVER UTILS]: Error loading plugin from {0}:\n{1}", dllName,
String.Join("\n", Array.ConvertAll(rtle.LoaderExceptions, e => e.ToString()))),
rtle);
return null;
}
catch (Exception e)
{
m_log.Error(string.Format("[SERVER UTILS]: Error loading plugin from {0}", dllName), e);
return null;
}
}
public static Dictionary<string, object> ParseQueryString(string query)
{
Dictionary<string, object> result = new Dictionary<string, object>();
string[] terms = query.Split(new char[] {'&'});
if (terms.Length == 0)
return result;
foreach (string t in terms)
{
string[] elems = t.Split(new char[] {'='});
if (elems.Length == 0)
continue;
string name = System.Web.HttpUtility.UrlDecode(elems[0]);
string value = String.Empty;
if (elems.Length > 1)
value = System.Web.HttpUtility.UrlDecode(elems[1]);
if (name.EndsWith("[]"))
{
string cleanName = name.Substring(0, name.Length - 2);
if (result.ContainsKey(cleanName))
{
if (!(result[cleanName] is List<string>))
continue;
List<string> l = (List<string>)result[cleanName];
l.Add(value);
}
else
{
List<string> newList = new List<string>();
newList.Add(value);
result[cleanName] = newList;
}
}
else
{
if (!result.ContainsKey(name))
result[name] = value;
}
}
return result;
}
public static string BuildQueryString(Dictionary<string, object> data)
{
string qstring = String.Empty;
string part;
foreach (KeyValuePair<string, object> kvp in data)
{
if (kvp.Value is List<string>)
{
List<string> l = (List<String>)kvp.Value;
foreach (string s in l)
{
part = System.Web.HttpUtility.UrlEncode(kvp.Key) +
"[]=" + System.Web.HttpUtility.UrlEncode(s);
if (qstring != String.Empty)
qstring += "&";
qstring += part;
}
}
else
{
if (kvp.Value.ToString() != String.Empty)
{
part = System.Web.HttpUtility.UrlEncode(kvp.Key) +
"=" + System.Web.HttpUtility.UrlEncode(kvp.Value.ToString());
}
else
{
part = System.Web.HttpUtility.UrlEncode(kvp.Key);
}
if (qstring != String.Empty)
qstring += "&";
qstring += part;
}
}
return qstring;
}
public static string BuildXmlResponse(Dictionary<string, object> data)
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
BuildXmlData(rootElement, data);
return doc.InnerXml;
}
private static void BuildXmlData(XmlElement parent, Dictionary<string, object> data)
{
foreach (KeyValuePair<string, object> kvp in data)
{
if (kvp.Value == null)
continue;
XmlElement elem = parent.OwnerDocument.CreateElement("",
XmlConvert.EncodeLocalName(kvp.Key), "");
if (kvp.Value is Dictionary<string, object>)
{
XmlAttribute type = parent.OwnerDocument.CreateAttribute("",
"type", "");
type.Value = "List";
elem.Attributes.Append(type);
BuildXmlData(elem, (Dictionary<string, object>)kvp.Value);
}
else
{
elem.AppendChild(parent.OwnerDocument.CreateTextNode(
kvp.Value.ToString()));
}
parent.AppendChild(elem);
}
}
public static Dictionary<string, object> ParseXmlResponse(string data)
{
//m_log.DebugFormat("[XXX]: received xml string: {0}", data);
Dictionary<string, object> ret = new Dictionary<string, object>();
XmlDocument doc = new XmlDocument();
doc.LoadXml(data);
XmlNodeList rootL = doc.GetElementsByTagName("ServerResponse");
if (rootL.Count != 1)
return ret;
XmlNode rootNode = rootL[0];
ret = ParseElement(rootNode);
return ret;
}
private static Dictionary<string, object> ParseElement(XmlNode element)
{
Dictionary<string, object> ret = new Dictionary<string, object>();
XmlNodeList partL = element.ChildNodes;
foreach (XmlNode part in partL)
{
XmlNode type = part.Attributes.GetNamedItem("type");
if (type == null || type.Value != "List")
{
ret[XmlConvert.DecodeName(part.Name)] = part.InnerText;
}
else
{
ret[XmlConvert.DecodeName(part.Name)] = ParseElement(part);
}
}
return ret;
}
public static IConfig GetConfig(string configFile, string configName)
{
IConfig config;
if (File.Exists(configFile))
{
IConfigSource configsource = new IniConfigSource(configFile);
config = configsource.Configs[configName];
}
else
config = null;
return config;
}
public static IConfigSource LoadInitialConfig(string url)
{
IConfigSource source = new XmlConfigSource();
m_log.InfoFormat("[SERVER UTILS]: {0} is a http:// URI, fetching ...", url);
// The ini file path is a http URI
// Try to read it
try
{
XmlReader r = XmlReader.Create(url);
IConfigSource cs = new XmlConfigSource(r);
source.Merge(cs);
}
catch (Exception e)
{
m_log.FatalFormat("[SERVER UTILS]: Exception reading config from URI {0}\n" + e.ToString(), url);
Environment.Exit(1);
}
return source;
}
}
}
| |
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD.
// All rights reserved. Licensed under the BSD 3-Clause License; see License.txt.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Moq.Language;
using Moq.Language.Flow;
using Moq.Properties;
namespace Moq.Protected
{
internal class ProtectedMock<T> : IProtectedMock<T>
where T : class
{
private Mock<T> mock;
public ProtectedMock(Mock<T> mock)
{
this.mock = mock;
}
public IProtectedAsMock<T, TAnalog> As<TAnalog>()
where TAnalog : class
{
return new ProtectedAsMock<T, TAnalog>(this.mock);
}
#region Setup
public ISetup<T> Setup(string methodName, params object[] args)
{
Guard.NotNullOrEmpty(methodName, nameof(methodName));
return this.Setup(methodName, false, args);
}
public ISetup<T> Setup(string methodName, bool exactParameterMatch, params object[] args)
{
Guard.NotNullOrEmpty(methodName, nameof(methodName));
var method = GetMethod(methodName, exactParameterMatch, args);
ThrowIfMemberMissing(methodName, method);
ThrowIfPublicMethod(method, typeof(T).Name);
var setup = Mock.Setup(mock, GetMethodCall(method, args), null);
return new VoidSetupPhrase<T>(setup);
}
public ISetup<T, TResult> Setup<TResult>(string methodName, params object[] args)
{
Guard.NotNullOrEmpty(methodName, nameof(methodName));
return Setup<TResult>(methodName, false, args);
}
public ISetup<T, TResult> Setup<TResult>(string methodName, bool exactParameterMatch, params object[] args)
{
Guard.NotNullOrEmpty(methodName, nameof(methodName));
var property = GetProperty(methodName);
if (property != null)
{
ThrowIfPublicGetter(property, typeof(T).Name);
// TODO should consider property indexers
var getterSetup = Mock.SetupGet(mock, GetMemberAccess<TResult>(property), null);
return new NonVoidSetupPhrase<T, TResult>(getterSetup);
}
var method = GetMethod(methodName, exactParameterMatch, args);
ThrowIfMemberMissing(methodName, method);
ThrowIfVoidMethod(method);
ThrowIfPublicMethod(method, typeof(T).Name);
var setup = Mock.Setup(mock, GetMethodCall<TResult>(method, args), null);
return new NonVoidSetupPhrase<T, TResult>(setup);
}
public ISetupGetter<T, TProperty> SetupGet<TProperty>(string propertyName)
{
Guard.NotNullOrEmpty(propertyName, nameof(propertyName));
var property = GetProperty(propertyName);
ThrowIfMemberMissing(propertyName, property);
ThrowIfPublicGetter(property, typeof(T).Name);
Guard.CanRead(property);
var setup = Mock.SetupGet(mock, GetMemberAccess<TProperty>(property), null);
return new NonVoidSetupPhrase<T, TProperty>(setup);
}
public ISetupSetter<T, TProperty> SetupSet<TProperty>(string propertyName, object value)
{
Guard.NotNullOrEmpty(propertyName, nameof(propertyName));
var property = GetProperty(propertyName);
ThrowIfMemberMissing(propertyName, property);
ThrowIfPublicSetter(property, typeof(T).Name);
Guard.CanWrite(property);
var expression = GetSetterExpression(property, ItExpr.IsAny<TProperty>());
var setup = Mock.SetupSet(mock, expression, condition: null);
return new SetterSetupPhrase<T, TProperty>(setup);
}
public ISetupSequentialAction SetupSequence(string methodOrPropertyName, params object[] args)
{
return this.SetupSequence(methodOrPropertyName, false, args);
}
public ISetupSequentialAction SetupSequence(string methodOrPropertyName, bool exactParameterMatch, params object[] args)
{
Guard.NotNullOrEmpty(methodOrPropertyName, nameof(methodOrPropertyName));
var method = GetMethod(methodOrPropertyName, exactParameterMatch, args);
ThrowIfMemberMissing(methodOrPropertyName, method);
ThrowIfPublicMethod(method, typeof(T).Name);
var setup = Mock.SetupSequence(mock, GetMethodCall(method, args));
return new SetupSequencePhrase(setup);
}
public ISetupSequentialResult<TResult> SetupSequence<TResult>(string methodOrPropertyName, params object[] args)
{
return this.SetupSequence<TResult>(methodOrPropertyName, false, args);
}
public ISetupSequentialResult<TResult> SetupSequence<TResult>(string methodOrPropertyName, bool exactParameterMatch, params object[] args)
{
Guard.NotNullOrEmpty(methodOrPropertyName, nameof(methodOrPropertyName));
var property = GetProperty(methodOrPropertyName);
if (property != null)
{
ThrowIfPublicGetter(property, typeof(T).Name);
// TODO should consider property indexers
var getterSetup = Mock.SetupSequence(mock, GetMemberAccess<TResult>(property));
return new SetupSequencePhrase<TResult>(getterSetup);
}
var method = GetMethod(methodOrPropertyName, exactParameterMatch, args);
ThrowIfMemberMissing(methodOrPropertyName, method);
ThrowIfVoidMethod(method);
ThrowIfPublicMethod(method, typeof(T).Name);
var setup = Mock.SetupSequence(mock, GetMethodCall<TResult>(method, args));
return new SetupSequencePhrase<TResult>(setup);
}
#endregion
#region Verify
public void Verify(string methodName, Times times, object[] args)
{
this.Verify(methodName, times, false, args);
}
public void Verify(string methodName, Times times, bool exactParameterMatch, object[] args)
{
Guard.NotNullOrEmpty(methodName, nameof(methodName));
var method = GetMethod(methodName, exactParameterMatch, args);
ThrowIfMemberMissing(methodName, method);
ThrowIfPublicMethod(method, typeof(T).Name);
Mock.Verify(mock, GetMethodCall(method, args), times, null);
}
public void Verify<TResult>(string methodName, Times times, object[] args)
{
this.Verify<TResult>(methodName, times, false, args);
}
public void Verify<TResult>(string methodName, Times times, bool exactParameterMatch, object[] args)
{
Guard.NotNullOrEmpty(methodName, nameof(methodName));
var property = GetProperty(methodName);
if (property != null)
{
ThrowIfPublicGetter(property, typeof(T).Name);
// TODO should consider property indexers
Mock.VerifyGet(mock, GetMemberAccess<TResult>(property), times, null);
return;
}
var method = GetMethod(methodName, exactParameterMatch, args);
ThrowIfMemberMissing(methodName, method);
ThrowIfPublicMethod(method, typeof(T).Name);
Mock.Verify(mock, GetMethodCall<TResult>(method, args), times, null);
}
// TODO should receive args to support indexers
public void VerifyGet<TProperty>(string propertyName, Times times)
{
Guard.NotNullOrEmpty(propertyName, nameof(propertyName));
var property = GetProperty(propertyName);
ThrowIfMemberMissing(propertyName, property);
ThrowIfPublicGetter(property, typeof(T).Name);
Guard.CanRead(property);
// TODO should consider property indexers
Mock.VerifyGet(mock, GetMemberAccess<TProperty>(property), times, null);
}
// TODO should receive args to support indexers
public void VerifySet<TProperty>(string propertyName, Times times, object value)
{
Guard.NotNullOrEmpty(propertyName, nameof(propertyName));
var property = GetProperty(propertyName);
ThrowIfMemberMissing(propertyName, property);
ThrowIfPublicSetter(property, typeof(T).Name);
Guard.CanWrite(property);
var expression = GetSetterExpression(property, ItExpr.IsAny<TProperty>());
// TODO should consider property indexers
// TODO should receive the parameter here
Mock.VerifySet(mock, expression, times, null);
}
#endregion
private static Expression<Func<T, TResult>> GetMemberAccess<TResult>(PropertyInfo property)
{
var param = Expression.Parameter(typeof(T), "mock");
return Expression.Lambda<Func<T, TResult>>(Expression.MakeMemberAccess(param, property), param);
}
private static MethodInfo GetMethod(string methodName, params object[] args)
{
return GetMethod(methodName, false, args);
}
private static MethodInfo GetMethod(string methodName, bool exact, params object[] args)
{
var argTypes = ToArgTypes(args);
return typeof(T).GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
.SingleOrDefault(m => m.Name == methodName && m.GetParameterTypes().CompareTo(argTypes, exact));
}
private static Expression<Func<T, TResult>> GetMethodCall<TResult>(MethodInfo method, object[] args)
{
var param = Expression.Parameter(typeof(T), "mock");
return Expression.Lambda<Func<T, TResult>>(Expression.Call(param, method, ToExpressionArgs(method, args)), param);
}
private static Expression<Action<T>> GetMethodCall(MethodInfo method, object[] args)
{
var param = Expression.Parameter(typeof(T), "mock");
return Expression.Lambda<Action<T>>(Expression.Call(param, method, ToExpressionArgs(method, args)), param);
}
// TODO should support arguments for property indexers
private static PropertyInfo GetProperty(string propertyName)
{
return typeof(T).GetProperty(
propertyName,
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
}
private static Expression<Action<T>> GetSetterExpression(PropertyInfo property, Expression value)
{
var param = Expression.Parameter(typeof(T), "mock");
return Expression.Lambda<Action<T>>(
Expression.Call(param, property.GetSetMethod(true), value),
param);
}
private static void ThrowIfMemberMissing(string memberName, MemberInfo member)
{
if (member == null)
{
throw new ArgumentException(string.Format(
CultureInfo.CurrentCulture,
Resources.MemberMissing,
typeof(T).Name,
memberName));
}
}
private static void ThrowIfPublicMethod(MethodInfo method, string reflectedTypeName)
{
if (method.IsPublic)
{
throw new ArgumentException(string.Format(
CultureInfo.CurrentCulture,
Resources.MethodIsPublic,
reflectedTypeName,
method.Name));
}
}
private static void ThrowIfPublicGetter(PropertyInfo property, string reflectedTypeName)
{
if (property.CanRead && property.GetGetMethod() != null)
{
throw new ArgumentException(string.Format(
CultureInfo.CurrentCulture,
Resources.UnexpectedPublicProperty,
reflectedTypeName,
property.Name));
}
}
private static void ThrowIfPublicSetter(PropertyInfo property, string reflectedTypeName)
{
if (property.CanWrite && property.GetSetMethod() != null)
{
throw new ArgumentException(string.Format(
CultureInfo.CurrentCulture,
Resources.UnexpectedPublicProperty,
reflectedTypeName,
property.Name));
}
}
private static void ThrowIfVoidMethod(MethodInfo method)
{
if (method.ReturnType == typeof(void))
{
throw new ArgumentException(Resources.CantSetReturnValueForVoid);
}
}
private static Type[] ToArgTypes(object[] args)
{
if (args == null)
{
throw new ArgumentException(Resources.UseItExprIsNullRatherThanNullArgumentValue);
}
var types = new Type[args.Length];
for (int index = 0; index < args.Length; index++)
{
if (args[index] == null)
{
throw new ArgumentException(Resources.UseItExprIsNullRatherThanNullArgumentValue);
}
var expr = args[index] as Expression;
if (expr == null)
{
types[index] = args[index].GetType();
}
else if (expr.NodeType == ExpressionType.Call)
{
types[index] = ((MethodCallExpression)expr).Method.ReturnType;
}
else if (expr.NodeType == ExpressionType.MemberAccess)
{
var member = (MemberExpression)expr;
if (member.Member is FieldInfo field)
{
// Test for special case: `It.Ref<TValue>.IsAny`
if (field.Name == nameof(It.Ref<object>.IsAny))
{
var fieldDeclaringType = field.DeclaringType;
if (fieldDeclaringType.IsGenericType)
{
var fieldDeclaringTypeDefinition = fieldDeclaringType.GetGenericTypeDefinition();
if (fieldDeclaringTypeDefinition == typeof(It.Ref<>))
{
types[index] = field.FieldType.MakeByRefType();
continue;
}
}
}
types[index] = field.FieldType;
}
else if (member.Member is PropertyInfo property)
{
types[index] = property.PropertyType;
}
else
{
throw new NotSupportedException(string.Format(
Resources.Culture,
Resources.UnsupportedMember,
member.Member.Name));
}
}
else
{
types[index] = (expr.PartialEval() as ConstantExpression)?.Type;
}
}
return types;
}
private static Expression ToExpressionArg(ParameterInfo paramInfo, object arg)
{
if (arg is LambdaExpression lambda)
{
return lambda.Body;
}
if (arg is Expression expression)
{
return expression;
}
return Expression.Constant(arg, paramInfo.ParameterType);
}
private static IEnumerable<Expression> ToExpressionArgs(MethodInfo method, object[] args)
{
ParameterInfo[] methodParams = method.GetParameters();
for (int i = 0; i < args.Length; i++)
{
yield return ToExpressionArg(methodParams[i], args[i]);
}
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// GraphicsDeviceControl.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.Xna.Framework.Graphics;
#endregion
namespace WinFormsContentLoading
{
// System.Drawing and the XNA Framework both define Color and Rectangle
// types. To avoid conflicts, we specify exactly which ones to use.
using Color = System.Drawing.Color;
using Rectangle = Microsoft.Xna.Framework.Rectangle;
/// <summary>
/// Custom control uses the XNA Framework GraphicsDevice to render onto
/// a Windows Form. Derived classes can override the Initialize and Draw
/// methods to add their own drawing code.
/// </summary>
abstract public class GraphicsDeviceControl : Control
{
#region Fields
// However many GraphicsDeviceControl instances you have, they all share
// the same underlying GraphicsDevice, managed by this helper service.
GraphicsDeviceService graphicsDeviceService;
#endregion
#region Properties
/// <summary>
/// Gets a GraphicsDevice that can be used to draw onto this control.
/// </summary>
public GraphicsDevice GraphicsDevice
{
get { return graphicsDeviceService.GraphicsDevice; }
}
/// <summary>
/// Gets an IServiceProvider containing our IGraphicsDeviceService.
/// This can be used with components such as the ContentManager,
/// which use this service to look up the GraphicsDevice.
/// </summary>
public ServiceContainer Services
{
get { return services; }
}
ServiceContainer services = new ServiceContainer();
#endregion
#region Initialization
/// <summary>
/// Initializes the control.
/// </summary>
protected override void OnCreateControl()
{
// Don't initialize the graphics device if we are running in the designer.
if (!DesignMode)
{
graphicsDeviceService = GraphicsDeviceService.AddRef(Handle,
ClientSize.Width,
ClientSize.Height);
// Register the service, so components like ContentManager can find it.
services.AddService<IGraphicsDeviceService>(graphicsDeviceService);
// Give derived classes a chance to initialize themselves.
Initialize();
}
base.OnCreateControl();
}
/// <summary>
/// Disposes the control.
/// </summary>
protected override void Dispose(bool disposing)
{
if (graphicsDeviceService != null)
{
graphicsDeviceService.Release(disposing);
graphicsDeviceService = null;
}
base.Dispose(disposing);
}
#endregion
#region Paint
/// <summary>
/// Redraws the control in response to a WinForms paint message.
/// </summary>
protected override void OnPaint(PaintEventArgs e)
{
string beginDrawError = BeginDraw();
if (string.IsNullOrEmpty(beginDrawError))
{
// Draw the control using the GraphicsDevice.
Draw();
EndDraw();
}
else
{
// If BeginDraw failed, show an error message using System.Drawing.
PaintUsingSystemDrawing(e.Graphics, beginDrawError);
}
}
/// <summary>
/// Attempts to begin drawing the control. Returns an error message string
/// if this was not possible, which can happen if the graphics device is
/// lost, or if we are running inside the Form designer.
/// </summary>
string BeginDraw()
{
// If we have no graphics device, we must be running in the designer.
if (graphicsDeviceService == null)
{
return Text + "\n\n" + GetType();
}
// Make sure the graphics device is big enough, and is not lost.
string deviceResetError = HandleDeviceReset();
if (!string.IsNullOrEmpty(deviceResetError))
{
return deviceResetError;
}
// Many GraphicsDeviceControl instances can be sharing the same
// GraphicsDevice. The device backbuffer will be resized to fit the
// largest of these controls. But what if we are currently drawing
// a smaller control? To avoid unwanted stretching, we set the
// viewport to only use the top left portion of the full backbuffer.
Viewport viewport = new Viewport();
viewport.X = 0;
viewport.Y = 0;
viewport.Width = ClientSize.Width;
viewport.Height = ClientSize.Height;
viewport.MinDepth = 0;
viewport.MaxDepth = 1;
GraphicsDevice.Viewport = viewport;
return null;
}
/// <summary>
/// Ends drawing the control. This is called after derived classes
/// have finished their Draw method, and is responsible for presenting
/// the finished image onto the screen, using the appropriate WinForms
/// control handle to make sure it shows up in the right place.
/// </summary>
void EndDraw()
{
try
{
Rectangle sourceRectangle = new Rectangle(0, 0, ClientSize.Width,
ClientSize.Height);
GraphicsDevice.Present(sourceRectangle, null, this.Handle);
}
catch
{
// Present might throw if the device became lost while we were
// drawing. The lost device will be handled by the next BeginDraw,
// so we just swallow the exception.
}
}
/// <summary>
/// Helper used by BeginDraw. This checks the graphics device status,
/// making sure it is big enough for drawing the current control, and
/// that the device is not lost. Returns an error string if the device
/// could not be reset.
/// </summary>
string HandleDeviceReset()
{
bool deviceNeedsReset = false;
switch (GraphicsDevice.GraphicsDeviceStatus)
{
case GraphicsDeviceStatus.Lost:
// If the graphics device is lost, we cannot use it at all.
return "Graphics device lost";
case GraphicsDeviceStatus.NotReset:
// If device is in the not-reset state, we should try to reset it.
deviceNeedsReset = true;
break;
default:
// If the device state is ok, check whether it is big enough.
PresentationParameters pp = GraphicsDevice.PresentationParameters;
deviceNeedsReset = (ClientSize.Width > pp.BackBufferWidth) ||
(ClientSize.Height > pp.BackBufferHeight);
break;
}
// Do we need to reset the device?
if (deviceNeedsReset)
{
try
{
graphicsDeviceService.ResetDevice(ClientSize.Width,
ClientSize.Height);
}
catch (Exception e)
{
return "Graphics device reset failed\n\n" + e;
}
}
return null;
}
/// <summary>
/// If we do not have a valid graphics device (for instance if the device
/// is lost, or if we are running inside the Form designer), we must use
/// regular System.Drawing method to display a status message.
/// </summary>
protected virtual void PaintUsingSystemDrawing(Graphics graphics, string text)
{
graphics.Clear(Color.CornflowerBlue);
using (Brush brush = new SolidBrush(Color.Black))
{
using (StringFormat format = new StringFormat())
{
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
graphics.DrawString(text, Font, brush, ClientRectangle, format);
}
}
}
/// <summary>
/// Ignores WinForms paint-background messages. The default implementation
/// would clear the control to the current background color, causing
/// flickering when our OnPaint implementation then immediately draws some
/// other color over the top using the XNA Framework GraphicsDevice.
/// </summary>
protected override void OnPaintBackground(PaintEventArgs pevent)
{
}
#endregion
#region Abstract Methods
/// <summary>
/// Derived classes override this to initialize their drawing code.
/// </summary>
protected abstract void Initialize();
/// <summary>
/// Derived classes override this to draw themselves using the GraphicsDevice.
/// </summary>
protected abstract void Draw();
#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.Collections.ObjectModel;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Reflection;
using System.Reflection.Emit;
namespace System.Linq.Expressions.Compiler
{
internal partial class LambdaCompiler
{
[Flags]
internal enum CompilationFlags
{
EmitExpressionStart = 0x0001,
EmitNoExpressionStart = 0x0002,
EmitAsDefaultType = 0x0010,
EmitAsVoidType = 0x0020,
EmitAsTail = 0x0100, // at the tail position of a lambda, tail call can be safely emitted
EmitAsMiddle = 0x0200, // in the middle of a lambda, tail call can be emitted if it is in a return
EmitAsNoTail = 0x0400, // neither at the tail or in a return, or tail call is not turned on, no tail call is emitted
EmitExpressionStartMask = 0x000f,
EmitAsTypeMask = 0x00f0,
EmitAsTailCallMask = 0x0f00
}
/// <summary>
/// Update the flag with a new EmitAsTailCall flag
/// </summary>
private static CompilationFlags UpdateEmitAsTailCallFlag(CompilationFlags flags, CompilationFlags newValue)
{
Debug.Assert(newValue == CompilationFlags.EmitAsTail || newValue == CompilationFlags.EmitAsMiddle || newValue == CompilationFlags.EmitAsNoTail);
CompilationFlags oldValue = flags & CompilationFlags.EmitAsTailCallMask;
return flags ^ oldValue | newValue;
}
/// <summary>
/// Update the flag with a new EmitExpressionStart flag
/// </summary>
private static CompilationFlags UpdateEmitExpressionStartFlag(CompilationFlags flags, CompilationFlags newValue)
{
Debug.Assert(newValue == CompilationFlags.EmitExpressionStart || newValue == CompilationFlags.EmitNoExpressionStart);
CompilationFlags oldValue = flags & CompilationFlags.EmitExpressionStartMask;
return flags ^ oldValue | newValue;
}
/// <summary>
/// Update the flag with a new EmitAsType flag
/// </summary>
private static CompilationFlags UpdateEmitAsTypeFlag(CompilationFlags flags, CompilationFlags newValue)
{
Debug.Assert(newValue == CompilationFlags.EmitAsDefaultType || newValue == CompilationFlags.EmitAsVoidType);
CompilationFlags oldValue = flags & CompilationFlags.EmitAsTypeMask;
return flags ^ oldValue | newValue;
}
/// <summary>
/// Generates code for this expression in a value position.
/// This method will leave the value of the expression
/// on the top of the stack typed as Type.
/// </summary>
internal void EmitExpression(Expression node)
{
EmitExpression(node, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitExpressionStart);
}
/// <summary>
/// Emits an expression and discards the result. For some nodes this emits
/// more optimal code then EmitExpression/Pop
/// </summary>
private void EmitExpressionAsVoid(Expression node)
{
EmitExpressionAsVoid(node, CompilationFlags.EmitAsNoTail);
}
private void EmitExpressionAsVoid(Expression node, CompilationFlags flags)
{
Debug.Assert(node != null);
CompilationFlags startEmitted = EmitExpressionStart(node);
switch (node.NodeType)
{
case ExpressionType.Assign:
EmitAssign((AssignBinaryExpression)node, CompilationFlags.EmitAsVoidType);
break;
case ExpressionType.Block:
Emit((BlockExpression)node, UpdateEmitAsTypeFlag(flags, CompilationFlags.EmitAsVoidType));
break;
case ExpressionType.Throw:
EmitThrow((UnaryExpression)node, CompilationFlags.EmitAsVoidType);
break;
case ExpressionType.Goto:
EmitGotoExpression(node, UpdateEmitAsTypeFlag(flags, CompilationFlags.EmitAsVoidType));
break;
case ExpressionType.Constant:
case ExpressionType.Default:
case ExpressionType.Parameter:
// no-op
break;
default:
if (node.Type == typeof(void))
{
EmitExpression(node, UpdateEmitExpressionStartFlag(flags, CompilationFlags.EmitNoExpressionStart));
}
else
{
EmitExpression(node, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitNoExpressionStart);
_ilg.Emit(OpCodes.Pop);
}
break;
}
EmitExpressionEnd(startEmitted);
}
private void EmitExpressionAsType(Expression node, Type type, CompilationFlags flags)
{
if (type == typeof(void))
{
EmitExpressionAsVoid(node, flags);
}
else
{
// if the node is emitted as a different type, CastClass IL is emitted at the end,
// should not emit with tail calls.
if (!TypeUtils.AreEquivalent(node.Type, type))
{
EmitExpression(node);
Debug.Assert(TypeUtils.AreReferenceAssignable(type, node.Type));
_ilg.Emit(OpCodes.Castclass, type);
}
else
{
// emit the node with the flags and emit expression start
EmitExpression(node, UpdateEmitExpressionStartFlag(flags, CompilationFlags.EmitExpressionStart));
}
}
}
#region label block tracking
private CompilationFlags EmitExpressionStart(Expression node)
{
if (TryPushLabelBlock(node))
{
return CompilationFlags.EmitExpressionStart;
}
return CompilationFlags.EmitNoExpressionStart;
}
private void EmitExpressionEnd(CompilationFlags flags)
{
if ((flags & CompilationFlags.EmitExpressionStartMask) == CompilationFlags.EmitExpressionStart)
{
PopLabelBlock(_labelBlock.Kind);
}
}
#endregion
#region InvocationExpression
private void EmitInvocationExpression(Expression expr, CompilationFlags flags)
{
InvocationExpression node = (InvocationExpression)expr;
// Optimization: inline code for literal lambda's directly
//
// This is worth it because otherwise we end up with an extra call
// to DynamicMethod.CreateDelegate, which is expensive.
//
if (node.LambdaOperand != null)
{
EmitInlinedInvoke(node, flags);
return;
}
expr = node.Expression;
if (typeof(LambdaExpression).IsAssignableFrom(expr.Type))
{
// if the invoke target is a lambda expression tree, first compile it into a delegate
expr = Expression.Call(expr, expr.Type.GetMethod("Compile", Array.Empty<Type>()));
}
EmitMethodCall(expr, expr.Type.GetInvokeMethod(), node, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitExpressionStart);
}
private void EmitInlinedInvoke(InvocationExpression invoke, CompilationFlags flags)
{
LambdaExpression lambda = invoke.LambdaOperand;
// This is tricky: we need to emit the arguments outside of the
// scope, but set them inside the scope. Fortunately, using the IL
// stack it is entirely doable.
// 1. Emit invoke arguments
List<WriteBack> wb = EmitArguments(lambda.Type.GetInvokeMethod(), invoke);
// 2. Create the nested LambdaCompiler
var inner = new LambdaCompiler(this, lambda, invoke);
// 3. Emit the body
// if the inlined lambda is the last expression of the whole lambda,
// tail call can be applied.
if (wb != null)
{
Debug.Assert(wb.Count > 0);
flags = UpdateEmitAsTailCallFlag(flags, CompilationFlags.EmitAsNoTail);
}
inner.EmitLambdaBody(_scope, true, flags);
// 4. Emit write-backs if needed
EmitWriteBack(wb);
}
#endregion
#region IndexExpression
private void EmitIndexExpression(Expression expr)
{
var node = (IndexExpression)expr;
// Emit instance, if calling an instance method
Type objectType = null;
if (node.Object != null)
{
EmitInstance(node.Object, out objectType);
}
// Emit indexes. We don't allow byref args, so no need to worry
// about write-backs or EmitAddress
for (int i = 0, n = node.ArgumentCount; i < n; i++)
{
Expression arg = node.GetArgument(i);
EmitExpression(arg);
}
EmitGetIndexCall(node, objectType);
}
private void EmitIndexAssignment(AssignBinaryExpression node, CompilationFlags flags)
{
Debug.Assert(!node.IsByRef);
var index = (IndexExpression)node.Left;
CompilationFlags emitAs = flags & CompilationFlags.EmitAsTypeMask;
// Emit instance, if calling an instance method
Type objectType = null;
if (index.Object != null)
{
EmitInstance(index.Object, out objectType);
}
// Emit indexes. We don't allow byref args, so no need to worry
// about write-backs or EmitAddress
for (int i = 0, n = index.ArgumentCount; i < n; i++)
{
Expression arg = index.GetArgument(i);
EmitExpression(arg);
}
// Emit value
EmitExpression(node.Right);
// Save the expression value, if needed
LocalBuilder temp = null;
if (emitAs != CompilationFlags.EmitAsVoidType)
{
_ilg.Emit(OpCodes.Dup);
_ilg.Emit(OpCodes.Stloc, temp = GetLocal(node.Type));
}
EmitSetIndexCall(index, objectType);
// Restore the value
if (emitAs != CompilationFlags.EmitAsVoidType)
{
_ilg.Emit(OpCodes.Ldloc, temp);
FreeLocal(temp);
}
}
private void EmitGetIndexCall(IndexExpression node, Type objectType)
{
if (node.Indexer != null)
{
// For indexed properties, just call the getter
MethodInfo method = node.Indexer.GetGetMethod(nonPublic: true);
EmitCall(objectType, method);
}
else
{
EmitGetArrayElement(objectType);
}
}
private void EmitGetArrayElement(Type arrayType)
{
if (arrayType.IsSZArray)
{
// For one dimensional arrays, emit load
_ilg.EmitLoadElement(arrayType.GetElementType());
}
else
{
// Multidimensional arrays, call get
_ilg.Emit(OpCodes.Call, arrayType.GetMethod("Get", BindingFlags.Public | BindingFlags.Instance));
}
}
private void EmitSetIndexCall(IndexExpression node, Type objectType)
{
if (node.Indexer != null)
{
// For indexed properties, just call the setter
MethodInfo method = node.Indexer.GetSetMethod(nonPublic: true);
EmitCall(objectType, method);
}
else
{
EmitSetArrayElement(objectType);
}
}
private void EmitSetArrayElement(Type arrayType)
{
if (arrayType.IsSZArray)
{
// For one dimensional arrays, emit store
_ilg.EmitStoreElement(arrayType.GetElementType());
}
else
{
// Multidimensional arrays, call set
_ilg.Emit(OpCodes.Call, arrayType.GetMethod("Set", BindingFlags.Public | BindingFlags.Instance));
}
}
#endregion
#region MethodCallExpression
private void EmitMethodCallExpression(Expression expr, CompilationFlags flags)
{
MethodCallExpression node = (MethodCallExpression)expr;
EmitMethodCall(node.Object, node.Method, node, flags);
}
private void EmitMethodCallExpression(Expression expr)
{
EmitMethodCallExpression(expr, CompilationFlags.EmitAsNoTail);
}
private void EmitMethodCall(Expression obj, MethodInfo method, IArgumentProvider methodCallExpr)
{
EmitMethodCall(obj, method, methodCallExpr, CompilationFlags.EmitAsNoTail);
}
private void EmitMethodCall(Expression obj, MethodInfo method, IArgumentProvider methodCallExpr, CompilationFlags flags)
{
// Emit instance, if calling an instance method
Type objectType = null;
if (!method.IsStatic)
{
Debug.Assert(obj != null);
EmitInstance(obj, out objectType);
}
// if the obj has a value type, its address is passed to the method call so we cannot destroy the
// stack by emitting a tail call
if (obj != null && obj.Type.IsValueType)
{
EmitMethodCall(method, methodCallExpr, objectType);
}
else
{
EmitMethodCall(method, methodCallExpr, objectType, flags);
}
}
// assumes 'object' of non-static call is already on stack
private void EmitMethodCall(MethodInfo mi, IArgumentProvider args, Type objectType)
{
EmitMethodCall(mi, args, objectType, CompilationFlags.EmitAsNoTail);
}
// assumes 'object' of non-static call is already on stack
private void EmitMethodCall(MethodInfo mi, IArgumentProvider args, Type objectType, CompilationFlags flags)
{
// Emit arguments
List<WriteBack> wb = EmitArguments(mi, args);
// Emit the actual call
OpCode callOp = UseVirtual(mi) ? OpCodes.Callvirt : OpCodes.Call;
if (callOp == OpCodes.Callvirt && objectType.IsValueType)
{
// This automatically boxes value types if necessary.
_ilg.Emit(OpCodes.Constrained, objectType);
}
// The method call can be a tail call if
// 1) the method call is the last instruction before Ret
// 2) the method does not have any ByRef parameters, refer to ECMA-335 Partition III Section 2.4.
// "Verification requires that no managed pointers are passed to the method being called, since
// it does not track pointers into the current frame."
if ((flags & CompilationFlags.EmitAsTailCallMask) == CompilationFlags.EmitAsTail && !MethodHasByRefParameter(mi))
{
_ilg.Emit(OpCodes.Tailcall);
}
if (mi.CallingConvention == CallingConventions.VarArgs)
{
int count = args.ArgumentCount;
Type[] types = new Type[count];
for (int i = 0; i < count; i++)
{
types[i] = args.GetArgument(i).Type;
}
_ilg.EmitCall(callOp, mi, types);
}
else
{
_ilg.Emit(callOp, mi);
}
// Emit write-backs for properties passed as "ref" arguments
EmitWriteBack(wb);
}
private static bool MethodHasByRefParameter(MethodInfo mi)
{
foreach (ParameterInfo pi in mi.GetParametersCached())
{
if (pi.IsByRefParameter())
{
return true;
}
}
return false;
}
private void EmitCall(Type objectType, MethodInfo method)
{
if (method.CallingConvention == CallingConventions.VarArgs)
{
throw Error.UnexpectedVarArgsCall(method);
}
OpCode callOp = UseVirtual(method) ? OpCodes.Callvirt : OpCodes.Call;
if (callOp == OpCodes.Callvirt && objectType.IsValueType)
{
_ilg.Emit(OpCodes.Constrained, objectType);
}
_ilg.Emit(callOp, method);
}
private static bool UseVirtual(MethodInfo mi)
{
// There are two factors: is the method static, virtual or non-virtual instance?
// And is the object ref or value?
// The cases are:
//
// static, ref: call
// static, value: call
// virtual, ref: callvirt
// virtual, value: call -- e.g. double.ToString must be a non-virtual call to be verifiable.
// instance, ref: callvirt -- this looks wrong, but is verifiable and gives us a free null check.
// instance, value: call
//
// We never need to generate a non-virtual call to a virtual method on a reference type because
// expression trees do not support "base.Foo()" style calling.
//
// We could do an optimization here for the case where we know that the object is a non-null
// reference type and the method is a non-virtual instance method. For example, if we had
// (new Foo()).Bar() for instance method Bar we don't need the null check so we could do a
// call rather than a callvirt. However that seems like it would not be a very big win for
// most dynamically generated code scenarios, so let's not do that for now.
if (mi.IsStatic)
{
return false;
}
if (mi.DeclaringType.IsValueType)
{
return false;
}
return true;
}
/// <summary>
/// Emits arguments to a call, and returns an array of write-backs that
/// should happen after the call.
/// </summary>
private List<WriteBack> EmitArguments(MethodBase method, IArgumentProvider args)
{
return EmitArguments(method, args, 0);
}
/// <summary>
/// Emits arguments to a call, and returns an array of write-backs that
/// should happen after the call. For emitting dynamic expressions, we
/// need to skip the first parameter of the method (the call site).
/// </summary>
private List<WriteBack> EmitArguments(MethodBase method, IArgumentProvider args, int skipParameters)
{
ParameterInfo[] pis = method.GetParametersCached();
Debug.Assert(args.ArgumentCount + skipParameters == pis.Length);
List<WriteBack> writeBacks = null;
for (int i = skipParameters, n = pis.Length; i < n; i++)
{
ParameterInfo parameter = pis[i];
Expression argument = args.GetArgument(i - skipParameters);
Type type = parameter.ParameterType;
if (type.IsByRef)
{
type = type.GetElementType();
WriteBack wb = EmitAddressWriteBack(argument, type);
if (wb != null)
{
if (writeBacks == null)
{
writeBacks = new List<WriteBack>();
}
writeBacks.Add(wb);
}
}
else
{
EmitExpression(argument);
}
}
return writeBacks;
}
private void EmitWriteBack(List<WriteBack> writeBacks)
{
if (writeBacks != null)
{
foreach (WriteBack wb in writeBacks)
{
wb(this);
}
}
}
#endregion
private void EmitConstantExpression(Expression expr)
{
ConstantExpression node = (ConstantExpression)expr;
EmitConstant(node.Value, node.Type);
}
private void EmitConstant(object value)
{
Debug.Assert(value != null);
EmitConstant(value, value.GetType());
}
private void EmitConstant(object value, Type type)
{
// Try to emit the constant directly into IL
if (!_ilg.TryEmitConstant(value, type, this))
{
_boundConstants.EmitConstant(this, value, type);
}
}
private void EmitDynamicExpression(Expression expr)
{
#if FEATURE_COMPILE_TO_METHODBUILDER
if (!(_method is DynamicMethod))
{
throw Error.CannotCompileDynamic();
}
#else
Debug.Assert(_method is DynamicMethod);
#endif
var node = (IDynamicExpression)expr;
object site = node.CreateCallSite();
Type siteType = site.GetType();
MethodInfo invoke = node.DelegateType.GetInvokeMethod();
// site.Target.Invoke(site, args)
EmitConstant(site, siteType);
// Emit the temp as type CallSite so we get more reuse
_ilg.Emit(OpCodes.Dup);
LocalBuilder siteTemp = GetLocal(siteType);
_ilg.Emit(OpCodes.Stloc, siteTemp);
_ilg.Emit(OpCodes.Ldfld, siteType.GetField("Target"));
_ilg.Emit(OpCodes.Ldloc, siteTemp);
FreeLocal(siteTemp);
List<WriteBack> wb = EmitArguments(invoke, node, 1);
_ilg.Emit(OpCodes.Callvirt, invoke);
EmitWriteBack(wb);
}
private void EmitNewExpression(Expression expr)
{
NewExpression node = (NewExpression)expr;
if (node.Constructor != null)
{
if (node.Constructor.DeclaringType.IsAbstract)
throw Error.NonAbstractConstructorRequired();
List<WriteBack> wb = EmitArguments(node.Constructor, node);
_ilg.Emit(OpCodes.Newobj, node.Constructor);
EmitWriteBack(wb);
}
else
{
Debug.Assert(node.ArgumentCount == 0, "Node with arguments must have a constructor.");
Debug.Assert(node.Type.IsValueType, "Only value type may have constructor not set.");
LocalBuilder temp = GetLocal(node.Type);
_ilg.Emit(OpCodes.Ldloca, temp);
_ilg.Emit(OpCodes.Initobj, node.Type);
_ilg.Emit(OpCodes.Ldloc, temp);
FreeLocal(temp);
}
}
private void EmitTypeBinaryExpression(Expression expr)
{
TypeBinaryExpression node = (TypeBinaryExpression)expr;
if (node.NodeType == ExpressionType.TypeEqual)
{
EmitExpression(node.ReduceTypeEqual());
return;
}
Type type = node.Expression.Type;
// Try to determine the result statically
AnalyzeTypeIsResult result = ConstantCheck.AnalyzeTypeIs(node);
if (result == AnalyzeTypeIsResult.KnownTrue ||
result == AnalyzeTypeIsResult.KnownFalse)
{
// Result is known statically, so just emit the expression for
// its side effects and return the result
EmitExpressionAsVoid(node.Expression);
_ilg.EmitPrimitive(result == AnalyzeTypeIsResult.KnownTrue);
return;
}
if (result == AnalyzeTypeIsResult.KnownAssignable)
{
// We know the type can be assigned, but still need to check
// for null at runtime
if (type.IsNullableType())
{
EmitAddress(node.Expression, type);
_ilg.EmitHasValue(type);
return;
}
Debug.Assert(!type.IsValueType);
EmitExpression(node.Expression);
_ilg.Emit(OpCodes.Ldnull);
_ilg.Emit(OpCodes.Cgt_Un);
return;
}
Debug.Assert(result == AnalyzeTypeIsResult.Unknown);
// Emit a full runtime "isinst" check
EmitExpression(node.Expression);
if (type.IsValueType)
{
_ilg.Emit(OpCodes.Box, type);
}
_ilg.Emit(OpCodes.Isinst, node.TypeOperand);
_ilg.Emit(OpCodes.Ldnull);
_ilg.Emit(OpCodes.Cgt_Un);
}
private void EmitVariableAssignment(AssignBinaryExpression node, CompilationFlags flags)
{
var variable = (ParameterExpression)node.Left;
CompilationFlags emitAs = flags & CompilationFlags.EmitAsTypeMask;
if (node.IsByRef)
{
EmitAddress(node.Right, node.Right.Type);
}
else
{
EmitExpression(node.Right);
}
if (emitAs != CompilationFlags.EmitAsVoidType)
{
_ilg.Emit(OpCodes.Dup);
}
if (variable.IsByRef)
{
// Note: the stloc/ldloc pattern is a bit suboptimal, but it
// saves us from having to spill stack when assigning to a
// byref parameter. We already make this same trade-off for
// hoisted variables, see ElementStorage.EmitStore
LocalBuilder value = GetLocal(variable.Type);
_ilg.Emit(OpCodes.Stloc, value);
_scope.EmitGet(variable);
_ilg.Emit(OpCodes.Ldloc, value);
FreeLocal(value);
_ilg.EmitStoreValueIndirect(variable.Type);
}
else
{
_scope.EmitSet(variable);
}
}
private void EmitAssignBinaryExpression(Expression expr)
{
EmitAssign((AssignBinaryExpression)expr, CompilationFlags.EmitAsDefaultType);
}
private void EmitAssign(AssignBinaryExpression node, CompilationFlags emitAs)
{
switch (node.Left.NodeType)
{
case ExpressionType.Index:
EmitIndexAssignment(node, emitAs);
return;
case ExpressionType.MemberAccess:
EmitMemberAssignment(node, emitAs);
return;
case ExpressionType.Parameter:
EmitVariableAssignment(node, emitAs);
return;
default:
throw ContractUtils.Unreachable;
}
}
private void EmitParameterExpression(Expression expr)
{
ParameterExpression node = (ParameterExpression)expr;
_scope.EmitGet(node);
if (node.IsByRef)
{
_ilg.EmitLoadValueIndirect(node.Type);
}
}
private void EmitLambdaExpression(Expression expr)
{
LambdaExpression node = (LambdaExpression)expr;
EmitDelegateConstruction(node);
}
private void EmitRuntimeVariablesExpression(Expression expr)
{
RuntimeVariablesExpression node = (RuntimeVariablesExpression)expr;
_scope.EmitVariableAccess(this, node.Variables);
}
private void EmitMemberAssignment(AssignBinaryExpression node, CompilationFlags flags)
{
Debug.Assert(!node.IsByRef);
MemberExpression lvalue = (MemberExpression)node.Left;
MemberInfo member = lvalue.Member;
// emit "this", if any
Type objectType = null;
if (lvalue.Expression != null)
{
EmitInstance(lvalue.Expression, out objectType);
}
// emit value
EmitExpression(node.Right);
LocalBuilder temp = null;
CompilationFlags emitAs = flags & CompilationFlags.EmitAsTypeMask;
if (emitAs != CompilationFlags.EmitAsVoidType)
{
// save the value so we can return it
_ilg.Emit(OpCodes.Dup);
_ilg.Emit(OpCodes.Stloc, temp = GetLocal(node.Type));
}
var fld = member as FieldInfo;
if ((object)fld != null)
{
_ilg.EmitFieldSet((FieldInfo)member);
}
else
{
// MemberExpression.Member can only be a FieldInfo or a PropertyInfo
Debug.Assert(member is PropertyInfo);
var prop = (PropertyInfo)member;
EmitCall(objectType, prop.GetSetMethod(nonPublic: true));
}
if (emitAs != CompilationFlags.EmitAsVoidType)
{
_ilg.Emit(OpCodes.Ldloc, temp);
FreeLocal(temp);
}
}
private void EmitMemberExpression(Expression expr)
{
MemberExpression node = (MemberExpression)expr;
// emit "this", if any
Type instanceType = null;
if (node.Expression != null)
{
EmitInstance(node.Expression, out instanceType);
}
EmitMemberGet(node.Member, instanceType);
}
// assumes instance is already on the stack
private void EmitMemberGet(MemberInfo member, Type objectType)
{
var fi = member as FieldInfo;
if ((object)fi != null)
{
if (fi.IsLiteral)
{
EmitConstant(fi.GetRawConstantValue(), fi.FieldType);
}
else
{
_ilg.EmitFieldGet(fi);
}
}
else
{
// MemberExpression.Member or MemberBinding.Member can only be a FieldInfo or a PropertyInfo
Debug.Assert(member is PropertyInfo);
var prop = (PropertyInfo)member;
EmitCall(objectType, prop.GetGetMethod(nonPublic: true));
}
}
private void EmitInstance(Expression instance, out Type type)
{
type = instance.Type;
// NB: Instance can be a ByRef type due to stack spilling introducing ref locals for
// accessing an instance of a value type. In that case, we don't have to take the
// address of the instance anymore; we just load the ref local.
if (type.IsByRef)
{
type = type.GetElementType();
Debug.Assert(instance.NodeType == ExpressionType.Parameter);
Debug.Assert(type.IsValueType);
EmitExpression(instance);
}
else if (type.IsValueType)
{
EmitAddress(instance, type);
}
else
{
EmitExpression(instance);
}
}
private void EmitNewArrayExpression(Expression expr)
{
NewArrayExpression node = (NewArrayExpression)expr;
ReadOnlyCollection<Expression> expressions = node.Expressions;
int n = expressions.Count;
if (node.NodeType == ExpressionType.NewArrayInit)
{
Type elementType = node.Type.GetElementType();
_ilg.EmitArray(elementType, n);
for (int i = 0; i < n; i++)
{
_ilg.Emit(OpCodes.Dup);
_ilg.EmitPrimitive(i);
EmitExpression(expressions[i]);
_ilg.EmitStoreElement(elementType);
}
}
else
{
for (int i = 0; i < n; i++)
{
Expression x = expressions[i];
EmitExpression(x);
_ilg.EmitConvertToType(x.Type, typeof(int), isChecked: true, locals: this);
}
_ilg.EmitArray(node.Type);
}
}
private void EmitDebugInfoExpression(Expression expr)
{
return;
}
#region ListInit, MemberInit
private void EmitListInitExpression(Expression expr)
{
EmitListInit((ListInitExpression)expr);
}
private void EmitMemberInitExpression(Expression expr)
{
EmitMemberInit((MemberInitExpression)expr);
}
private void EmitBinding(MemberBinding binding, Type objectType)
{
switch (binding.BindingType)
{
case MemberBindingType.Assignment:
EmitMemberAssignment((MemberAssignment)binding, objectType);
break;
case MemberBindingType.ListBinding:
EmitMemberListBinding((MemberListBinding)binding);
break;
case MemberBindingType.MemberBinding:
EmitMemberMemberBinding((MemberMemberBinding)binding);
break;
}
}
private void EmitMemberAssignment(MemberAssignment binding, Type objectType)
{
EmitExpression(binding.Expression);
if (binding.Member is FieldInfo fi)
{
_ilg.Emit(OpCodes.Stfld, fi);
}
else
{
Debug.Assert(binding.Member is PropertyInfo);
EmitCall(objectType, (binding.Member as PropertyInfo).GetSetMethod(nonPublic: true));
}
}
private void EmitMemberMemberBinding(MemberMemberBinding binding)
{
Type type = GetMemberType(binding.Member);
if (binding.Member is PropertyInfo && type.IsValueType)
{
throw Error.CannotAutoInitializeValueTypeMemberThroughProperty(binding.Member);
}
if (type.IsValueType)
{
EmitMemberAddress(binding.Member, binding.Member.DeclaringType);
}
else
{
EmitMemberGet(binding.Member, binding.Member.DeclaringType);
}
EmitMemberInit(binding.Bindings, false, type);
}
private void EmitMemberListBinding(MemberListBinding binding)
{
Type type = GetMemberType(binding.Member);
if (binding.Member is PropertyInfo && type.IsValueType)
{
throw Error.CannotAutoInitializeValueTypeElementThroughProperty(binding.Member);
}
if (type.IsValueType)
{
EmitMemberAddress(binding.Member, binding.Member.DeclaringType);
}
else
{
EmitMemberGet(binding.Member, binding.Member.DeclaringType);
}
EmitListInit(binding.Initializers, false, type);
}
private void EmitMemberInit(MemberInitExpression init)
{
EmitExpression(init.NewExpression);
LocalBuilder loc = null;
if (init.NewExpression.Type.IsValueType && init.Bindings.Count > 0)
{
loc = GetLocal(init.NewExpression.Type);
_ilg.Emit(OpCodes.Stloc, loc);
_ilg.Emit(OpCodes.Ldloca, loc);
}
EmitMemberInit(init.Bindings, loc == null, init.NewExpression.Type);
if (loc != null)
{
_ilg.Emit(OpCodes.Ldloc, loc);
FreeLocal(loc);
}
}
// This method assumes that the instance is on the stack and is expected, based on "keepOnStack" flag
// to either leave the instance on the stack, or pop it.
private void EmitMemberInit(ReadOnlyCollection<MemberBinding> bindings, bool keepOnStack, Type objectType)
{
int n = bindings.Count;
if (n == 0)
{
// If there are no initializers and instance is not to be kept on the stack, we must pop explicitly.
if (!keepOnStack)
{
_ilg.Emit(OpCodes.Pop);
}
}
else
{
for (int i = 0; i < n; i++)
{
if (keepOnStack || i < n - 1)
{
_ilg.Emit(OpCodes.Dup);
}
EmitBinding(bindings[i], objectType);
}
}
}
private void EmitListInit(ListInitExpression init)
{
EmitExpression(init.NewExpression);
LocalBuilder loc = null;
if (init.NewExpression.Type.IsValueType)
{
loc = GetLocal(init.NewExpression.Type);
_ilg.Emit(OpCodes.Stloc, loc);
_ilg.Emit(OpCodes.Ldloca, loc);
}
EmitListInit(init.Initializers, loc == null, init.NewExpression.Type);
if (loc != null)
{
_ilg.Emit(OpCodes.Ldloc, loc);
FreeLocal(loc);
}
}
// This method assumes that the list instance is on the stack and is expected, based on "keepOnStack" flag
// to either leave the list instance on the stack, or pop it.
private void EmitListInit(ReadOnlyCollection<ElementInit> initializers, bool keepOnStack, Type objectType)
{
int n = initializers.Count;
if (n == 0)
{
// If there are no initializers and instance is not to be kept on the stack, we must pop explicitly.
if (!keepOnStack)
{
_ilg.Emit(OpCodes.Pop);
}
}
else
{
for (int i = 0; i < n; i++)
{
if (keepOnStack || i < n - 1)
{
_ilg.Emit(OpCodes.Dup);
}
EmitMethodCall(initializers[i].AddMethod, initializers[i], objectType);
// Some add methods, ArrayList.Add for example, return non-void
if (initializers[i].AddMethod.ReturnType != typeof(void))
{
_ilg.Emit(OpCodes.Pop);
}
}
}
}
private static Type GetMemberType(MemberInfo member)
{
Debug.Assert(member is FieldInfo || member is PropertyInfo);
return member is FieldInfo fi ? fi.FieldType : (member as PropertyInfo).PropertyType;
}
#endregion
#region Expression helpers
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private void EmitLift(ExpressionType nodeType, Type resultType, MethodCallExpression mc, ParameterExpression[] paramList, Expression[] argList)
{
Debug.Assert(TypeUtils.AreEquivalent(resultType.GetNonNullableType(), mc.Type.GetNonNullableType()));
switch (nodeType)
{
default:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
{
Label exit = _ilg.DefineLabel();
Label exitNull = _ilg.DefineLabel();
LocalBuilder anyNull = GetLocal(typeof(bool));
for (int i = 0, n = paramList.Length; i < n; i++)
{
ParameterExpression v = paramList[i];
Expression arg = argList[i];
if (arg.Type.IsNullableType())
{
_scope.AddLocal(this, v);
EmitAddress(arg, arg.Type);
_ilg.Emit(OpCodes.Dup);
_ilg.EmitHasValue(arg.Type);
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Ceq);
_ilg.Emit(OpCodes.Stloc, anyNull);
_ilg.EmitGetValueOrDefault(arg.Type);
_scope.EmitSet(v);
}
else
{
_scope.AddLocal(this, v);
EmitExpression(arg);
if (!arg.Type.IsValueType)
{
_ilg.Emit(OpCodes.Dup);
_ilg.Emit(OpCodes.Ldnull);
_ilg.Emit(OpCodes.Ceq);
_ilg.Emit(OpCodes.Stloc, anyNull);
}
_scope.EmitSet(v);
}
_ilg.Emit(OpCodes.Ldloc, anyNull);
_ilg.Emit(OpCodes.Brtrue, exitNull);
}
EmitMethodCallExpression(mc);
if (resultType.IsNullableType() && !TypeUtils.AreEquivalent(resultType, mc.Type))
{
ConstructorInfo ci = resultType.GetConstructor(new Type[] { mc.Type });
_ilg.Emit(OpCodes.Newobj, ci);
}
_ilg.Emit(OpCodes.Br_S, exit);
_ilg.MarkLabel(exitNull);
if (TypeUtils.AreEquivalent(resultType, mc.Type.GetNullableType()))
{
if (resultType.IsValueType)
{
LocalBuilder result = GetLocal(resultType);
_ilg.Emit(OpCodes.Ldloca, result);
_ilg.Emit(OpCodes.Initobj, resultType);
_ilg.Emit(OpCodes.Ldloc, result);
FreeLocal(result);
}
else
{
_ilg.Emit(OpCodes.Ldnull);
}
}
else
{
Debug.Assert(nodeType == ExpressionType.LessThan
|| nodeType == ExpressionType.LessThanOrEqual
|| nodeType == ExpressionType.GreaterThan
|| nodeType == ExpressionType.GreaterThanOrEqual);
_ilg.Emit(OpCodes.Ldc_I4_0);
}
_ilg.MarkLabel(exit);
FreeLocal(anyNull);
return;
}
case ExpressionType.Equal:
case ExpressionType.NotEqual:
{
if (TypeUtils.AreEquivalent(resultType, mc.Type.GetNullableType()))
{
goto default;
}
Label exit = _ilg.DefineLabel();
Label exitAllNull = _ilg.DefineLabel();
Label exitAnyNull = _ilg.DefineLabel();
LocalBuilder anyNull = GetLocal(typeof(bool));
LocalBuilder allNull = GetLocal(typeof(bool));
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Stloc, anyNull);
_ilg.Emit(OpCodes.Ldc_I4_1);
_ilg.Emit(OpCodes.Stloc, allNull);
for (int i = 0, n = paramList.Length; i < n; i++)
{
ParameterExpression v = paramList[i];
Expression arg = argList[i];
_scope.AddLocal(this, v);
if (arg.Type.IsNullableType())
{
EmitAddress(arg, arg.Type);
_ilg.Emit(OpCodes.Dup);
_ilg.EmitHasValue(arg.Type);
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Ceq);
_ilg.Emit(OpCodes.Dup);
_ilg.Emit(OpCodes.Ldloc, anyNull);
_ilg.Emit(OpCodes.Or);
_ilg.Emit(OpCodes.Stloc, anyNull);
_ilg.Emit(OpCodes.Ldloc, allNull);
_ilg.Emit(OpCodes.And);
_ilg.Emit(OpCodes.Stloc, allNull);
_ilg.EmitGetValueOrDefault(arg.Type);
}
else
{
EmitExpression(arg);
if (!arg.Type.IsValueType)
{
_ilg.Emit(OpCodes.Dup);
_ilg.Emit(OpCodes.Ldnull);
_ilg.Emit(OpCodes.Ceq);
_ilg.Emit(OpCodes.Dup);
_ilg.Emit(OpCodes.Ldloc, anyNull);
_ilg.Emit(OpCodes.Or);
_ilg.Emit(OpCodes.Stloc, anyNull);
_ilg.Emit(OpCodes.Ldloc, allNull);
_ilg.Emit(OpCodes.And);
_ilg.Emit(OpCodes.Stloc, allNull);
}
else
{
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Stloc, allNull);
}
}
_scope.EmitSet(v);
}
_ilg.Emit(OpCodes.Ldloc, allNull);
_ilg.Emit(OpCodes.Brtrue, exitAllNull);
_ilg.Emit(OpCodes.Ldloc, anyNull);
_ilg.Emit(OpCodes.Brtrue, exitAnyNull);
EmitMethodCallExpression(mc);
if (resultType.IsNullableType() && !TypeUtils.AreEquivalent(resultType, mc.Type))
{
ConstructorInfo ci = resultType.GetConstructor(new Type[] { mc.Type });
_ilg.Emit(OpCodes.Newobj, ci);
}
_ilg.Emit(OpCodes.Br_S, exit);
_ilg.MarkLabel(exitAllNull);
_ilg.EmitPrimitive(nodeType == ExpressionType.Equal);
_ilg.Emit(OpCodes.Br_S, exit);
_ilg.MarkLabel(exitAnyNull);
_ilg.EmitPrimitive(nodeType == ExpressionType.NotEqual);
_ilg.MarkLabel(exit);
FreeLocal(anyNull);
FreeLocal(allNull);
return;
}
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility001.accessibility001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility001.accessibility001;
public class Test
{
public void Method()
{
}
protected void Method(int x, object o)
{
s_status = 1;
}
internal protected void Method(long x, object o)
{
s_status = 2;
}
internal void Method(short x, object o)
{
s_status = 3;
}
private static int s_status = -1;
[Fact(Skip = "875112")]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Test b = new Test();
dynamic x = 1;
dynamic y = null;
b.Method(x, y);
return s_status == 1 ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility002.accessibility002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility002.accessibility002;
public class Test
{
public void Method()
{
}
protected void Method(int x, object o)
{
s_status = 1;
}
internal protected void Method(long x, object o)
{
s_status = 2;
}
internal void Method(short x, object o)
{
s_status = 3;
}
private static int s_status = -1;
[Fact(Skip = "875112")]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
var b = new Test();
b.Method();
dynamic x = short.MinValue;
dynamic y = null;
b.Method(x, y);
return s_status == 3 ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.errorverifier.errorverifier
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.errorverifier.errorverifier;
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility003.accessibility003;
using System;
using System.Collections;
using System.IO;
using System.Globalization;
using System.Reflection;
using System.Resources;
using Microsoft.CSharp.RuntimeBinder;
public enum ErrorElementId
{
None,
SK_METHOD, // method
SK_CLASS, // type
SK_NAMESPACE, // namespace
SK_FIELD, // field
SK_PROPERTY, // property
SK_UNKNOWN, // element
SK_VARIABLE, // variable
SK_EVENT, // event
SK_TYVAR, // type parameter
SK_ALIAS, // using alias
ERRORSYM, // <error>
NULL, // <null>
GlobalNamespace, // <global namespace>
MethodGroup, // method group
AnonMethod, // anonymous method
Lambda, // lambda expression
AnonymousType, // anonymous type
}
public enum ErrorMessageId
{
None,
BadBinaryOps, // Operator '{0}' cannot be applied to operands of type '{1}' and '{2}'
IntDivByZero, // Division by constant zero
BadIndexLHS, // Cannot apply indexing with [] to an expression of type '{0}'
BadIndexCount, // Wrong number of indices inside []; expected '{0}'
BadUnaryOp, // Operator '{0}' cannot be applied to operand of type '{1}'
NoImplicitConv, // Cannot implicitly convert type '{0}' to '{1}'
NoExplicitConv, // Cannot convert type '{0}' to '{1}'
ConstOutOfRange, // Constant value '{0}' cannot be converted to a '{1}'
AmbigBinaryOps, // Operator '{0}' is ambiguous on operands of type '{1}' and '{2}'
AmbigUnaryOp, // Operator '{0}' is ambiguous on an operand of type '{1}'
ValueCantBeNull, // Cannot convert null to '{0}' because it is a non-nullable value type
WrongNestedThis, // Cannot access a non-static member of outer type '{0}' via nested type '{1}'
NoSuchMember, // '{0}' does not contain a definition for '{1}'
ObjectRequired, // An object reference is required for the non-static field, method, or property '{0}'
AmbigCall, // The call is ambiguous between the following methods or properties: '{0}' and '{1}'
BadAccess, // '{0}' is inaccessible due to its protection level
MethDelegateMismatch, // No overload for '{0}' matches delegate '{1}'
AssgLvalueExpected, // The left-hand side of an assignment must be a variable, property or indexer
NoConstructors, // The type '{0}' has no constructors defined
BadDelegateConstructor, // The delegate '{0}' does not have a valid constructor
PropertyLacksGet, // The property or indexer '{0}' cannot be used in this context because it lacks the get accessor
ObjectProhibited, // Member '{0}' cannot be accessed with an instance reference; qualify it with a type name instead
AssgReadonly, // A readonly field cannot be assigned to (except in a constructor or a variable initializer)
RefReadonly, // A readonly field cannot be passed ref or out (except in a constructor)
AssgReadonlyStatic, // A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)
RefReadonlyStatic, // A static readonly field cannot be passed ref or out (except in a static constructor)
AssgReadonlyProp, // Property or indexer '{0}' cannot be assigned to -- it is read only
AbstractBaseCall, // Cannot call an abstract base member: '{0}'
RefProperty, // A property or indexer may not be passed as an out or ref parameter
ManagedAddr, // Cannot take the address of, get the size of, or declare a pointer to a managed type ('{0}')
FixedNotNeeded, // You cannot use the fixed statement to take the address of an already fixed expression
UnsafeNeeded, // Dynamic calls cannot be used in conjunction with pointers
BadBoolOp, // In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') must have the same return type as the type of its 2 parameters
MustHaveOpTF, // The type ('{0}') must contain declarations of operator true and operator false
CheckedOverflow, // The operation overflows at compile time in checked mode
ConstOutOfRangeChecked, // Constant value '{0}' cannot be converted to a '{1}' (use 'unchecked' syntax to override)
AmbigMember, // Ambiguity between '{0}' and '{1}'
SizeofUnsafe, // '{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)
FieldInitRefNonstatic, // A field initializer cannot reference the non-static field, method, or property '{0}'
CallingFinalizeDepracated, // Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available.
CallingBaseFinalizeDeprecated, // Do not directly call your base class Finalize method. It is called automatically from your destructor.
BadCastInFixed, // The right hand side of a fixed statement assignment may not be a cast expression
NoImplicitConvCast, // Cannot implicitly convert type '{0}' to '{1}'. An explicit conversion exists (are you missing a cast?)
InaccessibleGetter, // The property or indexer '{0}' cannot be used in this context because the get accessor is inaccessible
InaccessibleSetter, // The property or indexer '{0}' cannot be used in this context because the set accessor is inaccessible
BadArity, // Using the generic {1} '{0}' requires '{2}' type arguments
BadTypeArgument, // The type '{0}' may not be used as a type argument
TypeArgsNotAllowed, // The {1} '{0}' cannot be used with type arguments
HasNoTypeVars, // The non-generic {1} '{0}' cannot be used with type arguments
NewConstraintNotSatisfied, // '{2}' must be a non-abstract type with a public parameterless constructor in order to use it as parameter '{1}' in the generic type or method '{0}'
GenericConstraintNotSatisfiedRefType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no implicit reference conversion from '{3}' to '{1}'.
GenericConstraintNotSatisfiedNullableEnum, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'.
GenericConstraintNotSatisfiedNullableInterface, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'. Nullable types can not satisfy any interface constraints.
GenericConstraintNotSatisfiedTyVar, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion or type parameter conversion from '{3}' to '{1}'.
GenericConstraintNotSatisfiedValType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion from '{3}' to '{1}'.
TypeVarCantBeNull, // Cannot convert null to type parameter '{0}' because it could be a non-nullable value type. Consider using 'default({0})' instead.
BadRetType, // '{1} {0}' has the wrong return type
CantInferMethTypeArgs, // The type arguments for method '{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly.
MethGrpToNonDel, // Cannot convert method group '{0}' to non-delegate type '{1}'. Did you intend to invoke the method?
RefConstraintNotSatisfied, // The type '{2}' must be a reference type in order to use it as parameter '{1}' in the generic type or method '{0}'
ValConstraintNotSatisfied, // The type '{2}' must be a non-nullable value type in order to use it as parameter '{1}' in the generic type or method '{0}'
CircularConstraint, // Circular constraint dependency involving '{0}' and '{1}'
BaseConstraintConflict, // Type parameter '{0}' inherits conflicting constraints '{1}' and '{2}'
ConWithValCon, // Type parameter '{1}' has the 'struct' constraint so '{1}' cannot be used as a constraint for '{0}'
AmbigUDConv, // Ambiguous user defined conversions '{0}' and '{1}' when converting from '{2}' to '{3}'
PredefinedTypeNotFound, // Predefined type '{0}' is not defined or imported
PredefinedTypeBadType, // Predefined type '{0}' is declared incorrectly
BindToBogus, // '{0}' is not supported by the language
CantCallSpecialMethod, // '{0}': cannot explicitly call operator or accessor
BogusType, // '{0}' is a type not supported by the language
MissingPredefinedMember, // Missing compiler required member '{0}.{1}'
LiteralDoubleCast, // Literal of type double cannot be implicitly converted to type '{1}'; use an '{0}' suffix to create a literal of this type
UnifyingInterfaceInstantiations, // '{0}' cannot implement both '{1}' and '{2}' because they may unify for some type parameter substitutions
ConvertToStaticClass, // Cannot convert to static type '{0}'
GenericArgIsStaticClass, // '{0}': static types cannot be used as type arguments
PartialMethodToDelegate, // Cannot create delegate from method '{0}' because it is a partial method without an implementing declaration
IncrementLvalueExpected, // The operand of an increment or decrement operator must be a variable, property or indexer
NoSuchMemberOrExtension, // '{0}' does not contain a definition for '{1}' and no extension method '{1}' accepting a first argument of type '{0}' could be found (are you missing a using directive or an assembly reference?)
ValueTypeExtDelegate, // Extension methods '{0}' defined on value type '{1}' cannot be used to create delegates
BadArgCount, // No overload for method '{0}' takes '{1}' arguments
BadArgTypes, // The best overloaded method match for '{0}' has some invalid arguments
BadArgType, // Argument '{0}': cannot convert from '{1}' to '{2}'
RefLvalueExpected, // A ref or out argument must be an assignable variable
BadProtectedAccess, // Cannot access protected member '{0}' via a qualifier of type '{1}'; the qualifier must be of type '{2}' (or derived from it)
BindToBogusProp2, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor methods '{1}' or '{2}'
BindToBogusProp1, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor method '{1}'
BadDelArgCount, // Delegate '{0}' does not take '{1}' arguments
BadDelArgTypes, // Delegate '{0}' has some invalid arguments
AssgReadonlyLocal, // Cannot assign to '{0}' because it is read-only
RefReadonlyLocal, // Cannot pass '{0}' as a ref or out argument because it is read-only
ReturnNotLValue, // Cannot modify the return value of '{0}' because it is not a variable
BadArgExtraRef, // Argument '{0}' should not be passed with the '{1}' keyword
// DelegateOnConditional, // Cannot create delegate with '{0}' because it has a Conditional attribute (REMOVED)
BadArgRef, // Argument '{0}' must be passed with the '{1}' keyword
AssgReadonly2, // Members of readonly field '{0}' cannot be modified (except in a constructor or a variable initializer)
RefReadonly2, // Members of readonly field '{0}' cannot be passed ref or out (except in a constructor)
AssgReadonlyStatic2, // Fields of static readonly field '{0}' cannot be assigned to (except in a static constructor or a variable initializer)
RefReadonlyStatic2, // Fields of static readonly field '{0}' cannot be passed ref or out (except in a static constructor)
AssgReadonlyLocalCause, // Cannot assign to '{0}' because it is a '{1}'
RefReadonlyLocalCause, // Cannot pass '{0}' as a ref or out argument because it is a '{1}'
ThisStructNotInAnonMeth, // Anonymous methods, lambda expressions, and query expressions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression or query expression and using the local instead.
DelegateOnNullable, // Cannot bind delegate to '{0}' because it is a member of 'System.Nullable<T>'
BadCtorArgCount, // '{0}' does not contain a constructor that takes '{1}' arguments
BadExtensionArgTypes, // '{0}' does not contain a definition for '{1}' and the best extension method overload '{2}' has some invalid arguments
BadInstanceArgType, // Instance argument: cannot convert from '{0}' to '{1}'
BadArgTypesForCollectionAdd, // The best overloaded Add method '{0}' for the collection initializer has some invalid arguments
InitializerAddHasParamModifiers, // The best overloaded method match '{0}' for the collection initializer element cannot be used. Collection initializer 'Add' methods cannot have ref or out parameters.
NonInvocableMemberCalled, // Non-invocable member '{0}' cannot be used like a method.
NamedArgumentSpecificationBeforeFixedArgument, // Named argument specifications must appear after all fixed arguments have been specified
BadNamedArgument, // The best overload for '{0}' does not have a parameter named '{1}'
BadNamedArgumentForDelegateInvoke, // The delegate '{0}' does not have a parameter named '{1}'
DuplicateNamedArgument, // Named argument '{0}' cannot be specified multiple times
NamedArgumentUsedInPositional, // Named argument '{0}' specifies a parameter for which a positional argument has already been given
}
public enum RuntimeErrorId
{
None,
// RuntimeBinderInternalCompilerException
InternalCompilerError, // An unexpected exception occurred while binding a dynamic operation
// ArgumentException
BindRequireArguments, // Cannot bind call with no calling object
// RuntimeBinderException
BindCallFailedOverloadResolution, // Overload resolution failed
// ArgumentException
BindBinaryOperatorRequireTwoArguments, // Binary operators must be invoked with two arguments
// ArgumentException
BindUnaryOperatorRequireOneArgument, // Unary operators must be invoked with one argument
// RuntimeBinderException
BindPropertyFailedMethodGroup, // The name '{0}' is bound to a method and cannot be used like a property
// RuntimeBinderException
BindPropertyFailedEvent, // The event '{0}' can only appear on the left hand side of += or -=
// RuntimeBinderException
BindInvokeFailedNonDelegate, // Cannot invoke a non-delegate type
// ArgumentException
BindImplicitConversionRequireOneArgument, // Implicit conversion takes exactly one argument
// ArgumentException
BindExplicitConversionRequireOneArgument, // Explicit conversion takes exactly one argument
// ArgumentException
BindBinaryAssignmentRequireTwoArguments, // Binary operators cannot be invoked with one argument
// RuntimeBinderException
BindBinaryAssignmentFailedNullReference, // Cannot perform member assignment on a null reference
// RuntimeBinderException
NullReferenceOnMemberException, // Cannot perform runtime binding on a null reference
// RuntimeBinderException
BindCallToConditionalMethod, // Cannot dynamically invoke method '{0}' because it has a Conditional attribute
// RuntimeBinderException
BindToVoidMethodButExpectResult, // Cannot implicitly convert type 'void' to 'object'
// EE?
EmptyDynamicView, // No further information on this object could be discovered
// MissingMemberException
GetValueonWriteOnlyProperty, // Write Only properties are not supported
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility003.accessibility003
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.errorverifier.errorverifier;
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility003.accessibility003;
public class Test
{
private delegate void Del(long x, int y);
public void Method(long x, int y)
{
}
private void Method(int x, int y)
{
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic b = new Test();
try
{
Del ddd = new Del(b.Method);
dynamic d1 = 1;
dynamic d2 = 2;
ddd(d1, d2);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
return 0;
}
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility004.accessibility004
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility004.accessibility004;
// <Title>Accessibility</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
public struct Test
{
public void Method()
{
}
private void Method(int x, object o)
{
s_status = 1;
}
internal void Method(long x, object o)
{
s_status = 2;
}
internal void Method(short x, object o)
{
s_status = 3;
}
private static int s_status = -1;
[Fact(Skip = "875112")]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Test b = new Test();
dynamic x = -1;
dynamic y = null;
b.Method(x, y);
return s_status == 1 ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility005.accessibility005
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility005.accessibility005;
public class Test
{
private class Base
{
public void Method(int x)
{
}
}
[Fact(Skip = "875112")]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Base b = new Base();
dynamic x = int.MaxValue;
b.Method(x);
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility006.accessibility006
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility006.accessibility006;
public class Test
{
protected class Base
{
public void Method()
{
}
protected void Method(int x, object o)
{
}
internal protected void Method(long x, object o)
{
}
internal void Method(short x, object o)
{
}
public void Method(byte x, object o)
{
}
}
[Fact(Skip = "875112")]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Base b = new Base();
dynamic x = byte.MaxValue;
dynamic y = new object();
b.Method(x, y);
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility007.accessibility007
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility007.accessibility007;
public class Test
{
public void Method(int x, int y)
{
s_status = 1;
}
private void Method(long x, int y)
{
s_status = 2;
}
internal void Method1(short x, int y)
{
s_status = 3;
}
protected void Method1(long x, int y)
{
s_status = 4;
}
private static int s_status = -1;
[Fact(Skip = "875112")]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic b = new Test();
dynamic d1 = 1;
dynamic d2 = 2;
b.Method(d1, d2);
bool ret = s_status == 1;
b.Method1(d1, d2);
ret &= (s_status == 4);
return ret ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility011.accessibility011
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility011.accessibility011;
public class Test
{
public class Higher
{
private class Base
{
public void Method(int x)
{
}
}
[Fact(Skip = "875112")]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Base b = new Base();
dynamic x = int.MaxValue;
b.Method(x);
return 0;
}
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility012.accessibility012
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility012.accessibility012;
public class Test
{
internal class Base
{
public void Method(int x)
{
Test.Status = 1;
}
}
public static int Status;
[Fact(Skip = "875112")]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Base b = new Base();
dynamic x = int.MaxValue;
b.Method(x);
if (Test.Status == 1)
return 0;
return 1;
}
}
// </Code>
}
| |
using UnityEngine;
using System;
namespace RoomAliveToolkit
{
[AddComponentMenu("RoomAliveToolkit/RATDepthMesh")]
/// <summary>
/// A behavior that is used to dynamically render depth meshes in the scene. Uses custom shaders to assemble a mesh out of the depth image and texture maps it from the color image (in real time).
/// Depth and color data are presumed to be supplied from RATKinectClient.
/// </summary>
public class RATDepthMesh : MonoBehaviour
{
// ****************************
// Public Member Variables
// ****************************
/// <summary>
/// The realtime source of Kinect depth + color data
/// </summary>
public RATKinectClient kinectClient;
/// <summary>
/// Material which encapsulates the custom depth mesh shader used for rendering depth meshes.
/// </summary>
public Material surfaceMaterial;
/// <summary>
/// The depth image from Kinect.
/// </summary>
[Space(10)]
[ReadOnly]
public Texture2D depthTexture;
/// <summary>
/// The RGB color image from Kinect.
/// </summary>
[ReadOnly]
public Texture2D rgbTexture;
/// <summary>
/// Flag for forcing the shader to work with a specific "replacement" color texture instead of the real-time acquired color image from Kinect.
/// (false by default)
/// </summary>
[Space(10)]
public bool UseReplacementTexture = false;
/// <summary>
/// An image (as Texture2D) that can be used as "replacement" texture by the depth shader.
/// </summary>
public Texture2D replacementTexture;
/// <summary>
/// Used in lighting calculations on whether this mesh should receive shadows.
/// </summary>
[Space(10)]
public bool ReceiveShadows = false;
/// <summary>
/// Used in lighting calculations on whether this mesh should cast shadows.
/// </summary>
public bool CastShadows = false;
// ****************************
// Private Member Variables
// ****************************
protected Texture2D depthToCameraSpaceX, depthToCameraSpaceY;
// Unity cannot render one full mesh due to number of triangles limit, so this splits it into segments to be rendered separately.
private int depthWidth = 512;//640;
private int depthHeight = 8;//6;
private int divTilesX = 1;
private int divTilesY = 53;//80;
private int numTiles;
private bool meshActive = true; //tracks change of kinect settings
private Mesh[] meshes;
private MeshFilter[] meshFilters;
private MeshRenderer[] meshRenderers;
private GameObject[] gameObjects;
private int depthTableUpdateCount = 0;
private bool inited = false;
public void Start()
{
//do some sanity checking
if (kinectClient == null)
{
Debug.LogError("DepthMesh error: No KinectV2Client specified! Please specify the clinet in the editor!");
}
else
{
depthTexture = kinectClient.DepthTexture;
if (!UseReplacementTexture)
rgbTexture = kinectClient.RGBTexture;
}
if (surfaceMaterial == null)
{
Debug.LogError("DepthMesh error: No Surface Material specified!");
return;
}
surfaceMaterial = new Material(surfaceMaterial);
// encode the camera space table as two color textures
depthToCameraSpaceX = new Texture2D(512, 424, TextureFormat.ARGB32, false, true);
depthToCameraSpaceY = new Texture2D(512, 424, TextureFormat.ARGB32, false, true);
UpdateMaterials();
CreateResources();
inited = true;
}
private void UpdateMaterials()
{
surfaceMaterial.SetMatrix("_IRIntrinsics", kinectClient.IR_Intrinsics);
surfaceMaterial.SetMatrix("_RGBIntrinsics", kinectClient.RGB_Intrinsics);
surfaceMaterial.SetMatrix("_RGBExtrinsics", kinectClient.RGB_Extrinsics);
surfaceMaterial.SetMatrix("_CamToWorld", Matrix4x4.identity); //formerly kinectClient.localToWorld, now incorperated in transform
surfaceMaterial.SetTexture("_MainTex", rgbTexture);
surfaceMaterial.SetTexture("_KinectDepthSource", kinectClient.DepthTexture);
surfaceMaterial.SetTexture("_DepthToCameraSpaceX", depthToCameraSpaceX);
surfaceMaterial.SetTexture("_DepthToCameraSpaceY", depthToCameraSpaceY);
}
private void CreateResources()
{
int numPoints = 0;
numPoints = (depthWidth - 1) * (depthHeight) * 6;
numTiles = divTilesX * divTilesY;
var verts = new Vector3[numPoints];
for (var i = 0; i < numPoints; ++i)
verts[i] = new Vector3(0.0f, 0.0f, 0.0f);
var indices = new int[numPoints];
for (var i = 0; i < numPoints; ++i)
indices[i] = i;
var texCoords = new Vector2[numPoints];
for (var i = 0; i < numPoints; ++i)
{
texCoords[i].x = (float)(i);// + 0.001f);
}
var normals = new Vector3[numPoints];
for (var i = 0; i < numPoints; ++i)
{
normals[i] = new Vector3(0.0f, 1.0f, 0.0f);
}
meshes = new Mesh[numTiles];
meshFilters = new MeshFilter[numTiles];
meshRenderers = new MeshRenderer[numTiles];
gameObjects = new GameObject[numTiles];
for (int i = 0; i < numTiles; i++)
{
// id
for (var texIndex = 0; texIndex < numPoints; ++texIndex)
{
texCoords[texIndex].y = (float)(i);// + .001f);
}
gameObjects[i] = new GameObject("Depth SubMesh");
gameObjects[i].layer = gameObject.layer;
gameObjects[i].transform.parent = transform;
gameObjects[i].transform.localPosition = Vector3.zero;
gameObjects[i].transform.localRotation = Quaternion.identity;
gameObjects[i].transform.localScale = Vector3.one;
meshFilters[i] = (MeshFilter)gameObjects[i].AddComponent(typeof(MeshFilter));
meshRenderers[i] = (MeshRenderer)gameObjects[i].AddComponent(typeof(MeshRenderer));
meshes[i] = new Mesh();
meshes[i].vertices = verts;
meshes[i].subMeshCount = 1;
meshes[i].uv = texCoords;
meshes[i].normals = normals;
//if (isPoints)
// meshes[i].SetIndices(indices, MeshTopology.Points, 0);
//else
meshes[i].SetIndices(indices, MeshTopology.Triangles, 0);
meshes[i].bounds = new Bounds(new Vector3(0, 0, 0), new Vector3(20000, 20000, 20000));
meshFilters[i].mesh = meshes[i];
meshRenderers[i].enabled = true;
//materials get updated every frame for every mesh
meshRenderers[i].material = surfaceMaterial; //default material
meshRenderers[i].receiveShadows = ReceiveShadows;
meshRenderers[i].shadowCastingMode = CastShadows ? UnityEngine.Rendering.ShadowCastingMode.On : UnityEngine.Rendering.ShadowCastingMode.Off;
}
}
public bool LoadDepthToCameraSpaceTable()
{
if (kinectClient.depthToCameraSpaceTableUpdateCount>depthTableUpdateCount)
{
var depthToCameraSpaceXColors = new Color[512 * 424];
var depthToCameraSpaceYColors = new Color[512 * 424];
int i = 0;
for (int y = 0; y < 424; y++)
for (int x = 0; x < 512; x++)
{
var entry = kinectClient.DepthSpaceToCameraSpaceTable[x, y];
var dx = (entry.x + 1.0f) / 2.0f; // put in [0..1)
var dy = (entry.y + 1.0f) / 2.0f; // put in [0..1)
var encodedX = EncodeFloatRGBA(dx);
var encodedY = EncodeFloatRGBA(dy);
depthToCameraSpaceXColors[i] = new Color(encodedX[0], encodedX[1], encodedX[2], encodedX[3]);
depthToCameraSpaceYColors[i] = new Color(encodedY[0], encodedY[1], encodedY[2], encodedY[3]);
i++;
}
depthToCameraSpaceX.SetPixels(depthToCameraSpaceXColors);
depthToCameraSpaceX.Apply();
depthToCameraSpaceY.SetPixels(depthToCameraSpaceYColors);
depthToCameraSpaceY.Apply();
depthTableUpdateCount = kinectClient.depthToCameraSpaceTableUpdateCount;
return true;
}
return false;
}
static float[] EncodeFloatRGBA(float val)
{
float[] kEncodeMul = new float[] { 1.0f, 255.0f, 65025.0f, 160581375.0f };
float kEncodeBit = 1.0f / 255.0f;
for (int i = 0; i < kEncodeMul.Length; ++i)
{
kEncodeMul[i] *= val;
// Frac
kEncodeMul[i] = (float)(kEncodeMul[i] - Math.Truncate(kEncodeMul[i]));
}
// enc -= enc.yzww * kEncodeBit;
float[] yzww = new float[] { kEncodeMul[1], kEncodeMul[2], kEncodeMul[3], kEncodeMul[3] };
for (int i = 0; i < kEncodeMul.Length; ++i)
{
kEncodeMul[i] -= yzww[i] * kEncodeBit;
}
return kEncodeMul;
}
public void Update()
{
if (!inited)
return;
if(!meshActive)
{
return;
}
if(LoadDepthToCameraSpaceTable())
{
surfaceMaterial.SetTexture("_DepthToCameraSpaceX", depthToCameraSpaceX);
surfaceMaterial.SetTexture("_DepthToCameraSpaceY", depthToCameraSpaceY);
}
surfaceMaterial.SetMatrix("_IRIntrinsics", kinectClient.IR_Intrinsics); //these can change when the KinectV2Client updates them from default values
surfaceMaterial.SetMatrix("_RGBIntrinsics", kinectClient.RGB_Intrinsics);
surfaceMaterial.SetMatrix("_RGBExtrinsics", kinectClient.RGB_Extrinsics);
surfaceMaterial.SetVector("_RGBDistCoef", kinectClient.RGB_DistCoef);
surfaceMaterial.SetVector("_IRDistCoef", kinectClient.IR_DistCoef);
surfaceMaterial.SetFloat("_RGBImageYDirectionFlag", -1); //flip for JPEG encoded images
if (kinectClient != null) // update the Kinect textures mostly for viewing them from the editor
{
if (UseReplacementTexture) rgbTexture = replacementTexture;
else rgbTexture = kinectClient.RGBTexture;
}
if (rgbTexture != null )
{
surfaceMaterial.SetTexture("_MainTex", rgbTexture);
surfaceMaterial.GetTexture("_MainTex").wrapMode = TextureWrapMode.Clamp;
}
// surfaceMaterial.SetMatrix("_CamToWorld", kinectClient.localToWorld);
surfaceMaterial.SetMatrix("_CamToWorld", Matrix4x4.identity); //Already incorperated in transform
surfaceMaterial.SetFloat("_RealTime", Time.timeSinceLevelLoad);
}
//public void EnableRendering(bool value)
//{
// foreach (Renderer rend in meshRenderers)
// rend.enabled = value;
//}
//public void SetUserViewParameters(int userId, Vector3 userViewPos, Matrix4x4 cameraProjectionMatrix, Matrix4x4 cameraViewMatrix, Texture texture)
//{
// string userString = "_User" + (userId + 1);
//}
//public void UpdateRenderPass1()
//{
// UpdateMaterial(surfaceMaterial, true);
//}
private void UpdateMaterial(Material mat, bool updateShadowInformation)
{
foreach (Renderer rend in meshRenderers)
{
rend.material = mat;
if (updateShadowInformation)
{
rend.receiveShadows = ReceiveShadows;
rend.shadowCastingMode = CastShadows ? UnityEngine.Rendering.ShadowCastingMode.On : UnityEngine.Rendering.ShadowCastingMode.Off;
}
}
}
}
}
| |
// 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 System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Collections;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Scripting
{
/// <summary>
/// Options for creating and running scripts.
/// </summary>
public class ScriptOptions
{
private readonly ImmutableArray<MetadataReference> _references;
private readonly ImmutableArray<string> _namespaces;
private readonly AssemblyReferenceResolver _referenceResolver;
private readonly bool _isInteractive;
public ScriptOptions()
: this(ImmutableArray<MetadataReference>.Empty,
ImmutableArray<string>.Empty,
new AssemblyReferenceResolver(GacFileResolver.Default, MetadataFileReferenceProvider.Default),
isInteractive: true)
{
}
public static readonly ScriptOptions Default;
static ScriptOptions()
{
Default = new ScriptOptions()
.WithReferences(typeof(int).GetTypeInfo().Assembly);
}
private ScriptOptions(
ImmutableArray<MetadataReference> references,
ImmutableArray<string> namespaces,
AssemblyReferenceResolver referenceResolver,
bool isInteractive)
{
_references = references;
_namespaces = namespaces;
_referenceResolver = referenceResolver;
_isInteractive = isInteractive;
}
/// <summary>
/// The set of <see cref="MetadataReference"/>'s used by the script.
/// </summary>
public ImmutableArray<MetadataReference> References
{
get { return _references; }
}
/// <summary>
/// The namespaces automatically imported by the script.
/// </summary>
public ImmutableArray<string> Namespaces
{
get { return _namespaces; }
}
/// <summary>
/// The paths used when searching for references.
/// </summary>
public ImmutableArray<string> SearchPaths
{
get { return _referenceResolver.PathResolver.SearchPaths; }
}
/// <summary>
/// The base directory used when searching for references.
/// </summary>
public string BaseDirectory
{
get { return _referenceResolver.PathResolver.BaseDirectory; }
}
/// <summary>
/// The <see cref="MetadataFileReferenceProvider"/> scripts will use to translate assembly names into metadata file paths. (#r syntax)
/// </summary>
public MetadataReferenceResolver ReferenceResolver
{
get { return _referenceResolver; }
}
// TODO:
internal AssemblyReferenceResolver AssemblyResolver
{
get { return _referenceResolver; }
}
internal MetadataFileReferenceResolver FileReferenceResolver
{
get { return _referenceResolver.PathResolver; }
}
/// <summary>
/// True if the script is interactive.
/// Interactive scripts may contain a final expression whose value is returned when the script is run.
/// </summary>
public bool IsInteractive
{
get { return _isInteractive; }
}
private ScriptOptions With(
Optional<ImmutableArray<MetadataReference>> references = default(Optional<ImmutableArray<MetadataReference>>),
Optional<ImmutableArray<string>> namespaces = default(Optional<ImmutableArray<string>>),
Optional<AssemblyReferenceResolver> resolver = default(Optional<AssemblyReferenceResolver>),
Optional<bool> isInteractive = default(Optional<bool>))
{
var newReferences = references.HasValue ? references.Value : _references;
var newNamespaces = namespaces.HasValue ? namespaces.Value : _namespaces;
var newResolver = resolver.HasValue ? resolver.Value : _referenceResolver;
var newIsInteractive = isInteractive.HasValue ? isInteractive.Value : _isInteractive;
if (newReferences == _references &&
newNamespaces == _namespaces &&
newResolver == _referenceResolver &&
newIsInteractive == _isInteractive)
{
return this;
}
else
{
return new ScriptOptions(newReferences, newNamespaces, newResolver, newIsInteractive);
}
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
public ScriptOptions WithReferences(ImmutableArray<MetadataReference> references)
{
return With(references: references.IsDefault ? ImmutableArray<MetadataReference>.Empty : references);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
public ScriptOptions WithReferences(IEnumerable<MetadataReference> references)
{
return WithReferences(references != null ? references.ToImmutableArray() : ImmutableArray<MetadataReference>.Empty);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
public ScriptOptions WithReferences(params MetadataReference[] references)
{
return WithReferences((IEnumerable<MetadataReference>)references);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
public ScriptOptions AddReferences(IEnumerable<MetadataReference> references)
{
if (_references == null)
{
return this;
}
else
{
return this.WithReferences(AddMissing(this.References, references));
}
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
public ScriptOptions AddReferences(params MetadataReference[] references)
{
return AddReferences((IEnumerable<MetadataReference>)references);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
public ScriptOptions WithReferences(IEnumerable<System.Reflection.Assembly> assemblies)
{
if (assemblies == null)
{
return WithReferences((IEnumerable<MetadataReference>)null);
}
else
{
return WithReferences(assemblies.Select(MetadataReference.CreateFromAssemblyInternal));
}
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
public ScriptOptions WithReferences(params System.Reflection.Assembly[] assemblies)
{
return WithReferences((IEnumerable<System.Reflection.Assembly>)assemblies);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
public ScriptOptions AddReferences(IEnumerable<System.Reflection.Assembly> assemblies)
{
if (assemblies == null)
{
return this;
}
else
{
return AddReferences(assemblies.Select(MetadataReference.CreateFromAssemblyInternal));
}
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
public ScriptOptions AddReferences(params System.Reflection.Assembly[] assemblies)
{
return AddReferences((IEnumerable<System.Reflection.Assembly>)assemblies);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
public ScriptOptions WithReferences(IEnumerable<string> references)
{
if (references == null)
{
return WithReferences(ImmutableArray<MetadataReference>.Empty);
}
else
{
return WithReferences(references.Where(name => name != null).Select(name => ResolveReference(name)));
}
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
public ScriptOptions WithReferences(params string[] references)
{
return WithReferences((IEnumerable<string>)references);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
public ScriptOptions AddReferences(IEnumerable<string> references)
{
if (references == null)
{
return this;
}
else
{
return AddReferences(references.Where(name => name != null).Select(name => ResolveReference(name)));
}
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
public ScriptOptions AddReferences(params string[] references)
{
return AddReferences((IEnumerable<string>)references);
}
private MetadataReference ResolveReference(string assemblyDisplayNameOrPath)
{
// TODO:
string fullPath = _referenceResolver.PathResolver.ResolveReference(assemblyDisplayNameOrPath, baseFilePath: null);
if (fullPath == null)
{
throw new System.IO.FileNotFoundException(ScriptingResources.AssemblyNotFound, assemblyDisplayNameOrPath);
}
return _referenceResolver.Provider.GetReference(fullPath, MetadataReferenceProperties.Assembly);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the namespaces changed.
/// </summary>
public ScriptOptions WithNamespaces(ImmutableArray<string> namespaces)
{
return With(namespaces: namespaces.IsDefault ? ImmutableArray<string>.Empty : namespaces);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the namespaces changed.
/// </summary>
public ScriptOptions WithNamespaces(IEnumerable<string> namespaces)
{
return WithNamespaces(namespaces != null ? namespaces.ToImmutableArray() : ImmutableArray<string>.Empty);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the namespaces changed.
/// </summary>
public ScriptOptions WithNamespaces(params string[] namespaces)
{
return WithNamespaces((IEnumerable<string>)namespaces);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with namespaces added.
/// </summary>
public ScriptOptions AddNamespaces(IEnumerable<string> namespaces)
{
if (namespaces == null)
{
return this;
}
else
{
return this.WithNamespaces(AddMissing(this.Namespaces, namespaces));
}
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with namespaces added.
/// </summary>
public ScriptOptions AddNamespaces(params string[] namespaces)
{
return AddNamespaces((IEnumerable<string>)namespaces);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the search paths changed.
/// </summary>
public ScriptOptions WithSearchPaths(IEnumerable<string> searchPaths)
{
if (this.SearchPaths.SequenceEqual(searchPaths))
{
return this;
}
else
{
// TODO:
var gacResolver = _referenceResolver.PathResolver as GacFileResolver;
if (gacResolver != null)
{
return With(resolver: new AssemblyReferenceResolver(
new GacFileResolver(
searchPaths,
gacResolver.BaseDirectory,
gacResolver.Architectures,
gacResolver.PreferredCulture),
_referenceResolver.Provider));
}
else
{
return With(resolver: new AssemblyReferenceResolver(
new MetadataFileReferenceResolver(
searchPaths,
_referenceResolver.PathResolver.BaseDirectory),
_referenceResolver.Provider));
}
}
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the search paths changed.
/// </summary>
public ScriptOptions WithSearchPaths(params string[] searchPaths)
{
return WithSearchPaths((IEnumerable<string>)searchPaths);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with search paths added.
/// </summary>
public ScriptOptions AddSearchPaths(params string[] searchPaths)
{
return AddSearchPaths((IEnumerable<string>)searchPaths);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with search paths added.
/// </summary>
public ScriptOptions AddSearchPaths(IEnumerable<string> searchPaths)
{
if (searchPaths == null)
{
return this;
}
else
{
return WithSearchPaths(AddMissing(this.SearchPaths, searchPaths));
}
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the base directory changed.
/// </summary>
public ScriptOptions WithBaseDirectory(string baseDirectory)
{
if (this.BaseDirectory == baseDirectory)
{
return this;
}
else
{
// TODO:
var gacResolver = _referenceResolver.PathResolver as GacFileResolver;
if (gacResolver != null)
{
return With(resolver: new AssemblyReferenceResolver(
new GacFileResolver(
_referenceResolver.PathResolver.SearchPaths,
baseDirectory,
gacResolver.Architectures,
gacResolver.PreferredCulture),
_referenceResolver.Provider));
}
else
{
return With(resolver: new AssemblyReferenceResolver(
new MetadataFileReferenceResolver(
_referenceResolver.PathResolver.SearchPaths,
baseDirectory),
_referenceResolver.Provider));
}
}
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the reference resolver specified.
/// </summary>
internal ScriptOptions WithReferenceResolver(MetadataFileReferenceResolver resolver)
{
if (resolver == _referenceResolver.PathResolver)
{
return this;
}
return With(resolver: new AssemblyReferenceResolver(resolver, _referenceResolver.Provider));
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the reference provider specified.
/// </summary>
internal ScriptOptions WithReferenceProvider(MetadataFileReferenceProvider provider)
{
if (provider == _referenceResolver.Provider)
{
return this;
}
return With(resolver: new AssemblyReferenceResolver(_referenceResolver.PathResolver, provider));
}
/// <summary>
/// Create a new <see cref="ScriptOptions"/> with the interactive state specified.
/// Interactive scripts may contain a final expression whose value is returned when the script is run.
/// </summary>
public ScriptOptions WithIsInteractive(bool isInteractive)
{
return With(isInteractive: isInteractive);
}
private static ImmutableArray<T> AddMissing<T>(ImmutableArray<T> a, IEnumerable<T> b) where T : class
{
var builder = ArrayBuilder<T>.GetInstance();
var set = PooledHashSet<T>.GetInstance();
foreach (var i in a)
{
set.Add(i);
builder.Add(i);
}
foreach (var i in b)
{
if ((i != null) && !set.Contains(i))
{
builder.Add(i);
}
}
set.Free();
return builder.ToImmutableAndFree();
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
namespace EarLab.Viewers.Panels
{
/// <summary>
/// Summary description for PanelAxisNew.
/// </summary>
public class PanelAxisNew : System.Windows.Forms.Panel
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private Pen blackPen;
private Control topAxisControl = null;
private bool topAxisShow = false;
private Point topAxisStartPoint = Point.Empty;
private Point topAxisEndPoint = Point.Empty;
private float topAxisStartValue = 0;
private float topAxisEndValue = 0;
private int topAxisMajorTickHeight = 3;
private int topAxisMajorTickOffset = 2;
private int topAxisMajorTickNumbersSpacing = 10;
private string topAxisMajorTickNumbersFormat = "0";
private bool topAxisMajorTickNumbersShow = true;
private string topAxisLabel = "Axis Label Not Set";
private bool topAxisLabelShow = true;
private Control bottomAxisControl = null;
private bool bottomAxisShow = false;
private Point bottomAxisStartPoint = Point.Empty;
private Point bottomAxisEndPoint = Point.Empty;
private float bottomAxisStartValue = 0;
private float bottomAxisEndValue = 0;
private double[] bottomAxisValueArray = null;
private int bottomAxisMajorTickHeight = 3;
private int bottomAxisMajorTickOffset = 2;
private int bottomAxisMajorTickNumbersSpacing = 10;
private string bottomAxisMajorTickNumbersFormat = "0";
private bool bottomAxisMajorTickNumbersShow = true;
private string bottomAxisLabel = "Axis Label Not Set";
private bool bottomAxisLabelShow = true;
private Control leftAxisControl = null;
private bool leftAxisShow = false;
private Point leftAxisStartPoint = Point.Empty;
private Point leftAxisEndPoint = Point.Empty;
private float leftAxisStartValue = 0;
private float leftAxisEndValue = 0;
private double[] leftAxisValueArray = null;
private int leftAxisMajorTickHeight = 3;
private int leftAxisMajorTickOffset = 2;
private int leftAxisMajorTickNumbersSpacing = 10;
private string leftAxisMajorTickNumbersFormat = "0";
private bool leftAxisMajorTickNumbersShow = true;
private string leftAxisLabel = "Axis Label Not Set";
private bool leftAxisLabelShow = true;
private Control rightAxisControl = null;
private bool rightAxisShow = false;
private Point rightAxisStartPoint = Point.Empty;
private Point rightAxisEndPoint = Point.Empty;
private float rightAxisStartValue = 0;
private float rightAxisEndValue = 0;
private int rightAxisMajorTickHeight = 3;
private int rightAxisMajorTickOffset = 2;
private int rightAxisMajorTickNumbersSpacing = 10;
private string rightAxisMajorTickNumbersFormat = "0";
private bool rightAxisMajorTickNumbersShow = true;
private string rightAxisLabel = "Axis Label Not Set";
private bool rightAxisLabelShow = true;
private StringFormat stringFormat = new StringFormat();
SizeF measuredSize;
public PanelAxisNew()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// We set up double buffering so that there isn't too much flicker (yeah, this is brilliant)
this.SetStyle(ControlStyles.UserPaint|ControlStyles.AllPaintingInWmPaint|ControlStyles.DoubleBuffer, true);
this.UpdateStyles();
blackPen = new Pen(Color.Black, 0);
}
/// <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()
{
//
// PanelAxis
//
this.Font = new System.Drawing.Font("Arial", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((System.Byte)(0)));
}
#endregion
protected override void OnPaint(PaintEventArgs pe)
{
#region Top Axis Code
if (this.topAxisShow && this.topAxisControl != null)
{
this.topAxisStartPoint = new Point(this.topAxisControl.Left-this.Left, this.topAxisControl.Top-this.Top);
this.topAxisEndPoint = new Point(this.topAxisControl.Right-1-this.Left, this.topAxisControl.Top-this.Top);
// transform origin so we don't have to add these numbers all the time
pe.Graphics.TranslateTransform(this.topAxisStartPoint.X, this.topAxisStartPoint.Y);
int width = Math.Abs(this.topAxisEndPoint.X - this.topAxisStartPoint.X);
this.stringFormat.Alignment = StringAlignment.Center;
this.stringFormat.LineAlignment = StringAlignment.Far;
// draw the axis label
if (this.topAxisLabelShow)
pe.Graphics.DrawString(this.topAxisLabel, this.Font, Brushes.Black, width/2f, -this.topAxisMajorTickOffset-1, this.stringFormat);
// put the origin back to normal spot for other axis elements
pe.Graphics.TranslateTransform(-this.topAxisStartPoint.X, -this.topAxisStartPoint.Y);
}
#endregion
#region Bottom Axis Code
if (this.bottomAxisShow && this.bottomAxisControl != null && this.BottomAxisStartValue != this.BottomAxisEndValue)
{
this.bottomAxisStartPoint = new Point(this.bottomAxisControl.Left-this.Left, this.bottomAxisControl.Bottom-this.Top);
this.bottomAxisEndPoint = new Point(this.bottomAxisControl.Right-1-this.Left, this.bottomAxisControl.Bottom-this.Top);
// transform origin so we don't have to add these numbers all the time
pe.Graphics.TranslateTransform(this.bottomAxisStartPoint.X, this.bottomAxisStartPoint.Y);
// calculate the number of ticks to have so that the numbers don't overlap
if (this.bottomAxisValueArray == null)
this.measuredSize = pe.Graphics.MeasureString(this.bottomAxisEndValue.ToString(this.bottomAxisMajorTickNumbersFormat), this.Font);
else
this.measuredSize = pe.Graphics.MeasureString(this.bottomAxisValueArray[(int)this.bottomAxisEndValue].ToString(this.bottomAxisMajorTickNumbersFormat), this.Font);
int width = Math.Abs(this.bottomAxisEndPoint.X - this.bottomAxisStartPoint.X);
double ratio = Math.Abs(this.bottomAxisStartValue - this.bottomAxisEndValue) / (double)width;
double stepSize = width / Math.Ceiling(width / (this.measuredSize.Width + this.bottomAxisMajorTickNumbersSpacing));
// draw the major tick marks
for (double i=0;i<width+1;i+=stepSize)
pe.Graphics.DrawLine(blackPen, (float)i, 0f, (float)i, (float)this.bottomAxisMajorTickHeight);
// draw the major tick mark values (we add one since we need to round up if we are 'close enough')
if (this.bottomAxisMajorTickNumbersShow)
{
this.stringFormat.Alignment = StringAlignment.Center;
this.stringFormat.LineAlignment = StringAlignment.Near;
for (double i=0;i<width+1;i+=stepSize)
{
if (this.bottomAxisValueArray == null)
pe.Graphics.DrawString((this.bottomAxisStartValue+i*ratio).ToString(this.bottomAxisMajorTickNumbersFormat), this.Font, Brushes.Black, (float)i, (float)(this.bottomAxisMajorTickHeight+this.bottomAxisMajorTickOffset), this.stringFormat);
else
pe.Graphics.DrawString(this.bottomAxisValueArray[(int)Math.Round(this.bottomAxisStartValue+i*ratio)].ToString(this.bottomAxisMajorTickNumbersFormat), this.Font, Brushes.Black, (float)i, (float)(this.bottomAxisMajorTickHeight+this.bottomAxisMajorTickOffset), this.stringFormat);
}
}
// draw the axis label
if (this.bottomAxisLabelShow)
pe.Graphics.DrawString(this.bottomAxisLabel, this.Font, Brushes.Black, width/2f, this.bottomAxisMajorTickHeight+this.Font.Height+1, this.stringFormat);
// put the origin back to normal spot for other axis elements
pe.Graphics.TranslateTransform(-this.bottomAxisStartPoint.X, -this.bottomAxisStartPoint.Y);
}
#endregion
#region Left Axis Code
if (this.leftAxisShow && this.leftAxisControl != null && this.leftAxisStartValue != this.leftAxisEndValue)
{
this.leftAxisStartPoint = new Point(this.leftAxisControl.Left-1-this.Left, this.leftAxisControl.Bottom-1-this.Top);
this.leftAxisEndPoint = new Point(this.leftAxisControl.Left-1-this.Left, this.leftAxisControl.Top-this.Top);
// transform origin so we don't have to add these numbers all the time
pe.Graphics.TranslateTransform(this.leftAxisStartPoint.X, this.leftAxisStartPoint.Y);
// calculate the number of ticks to have so that the numbers don't overlap
int height = Math.Abs(this.leftAxisEndPoint.Y - this.leftAxisStartPoint.Y);
double stepSize = height / Math.Ceiling((double)height / (this.Font.Height + this.leftAxisMajorTickNumbersSpacing));
// draw the major tick marks
for (double i=0;i>-height-1;i-=stepSize)
pe.Graphics.DrawLine(blackPen, 0f, (float)i, (float)-this.leftAxisMajorTickHeight, (float)i);
// draw the major tick mark values (we add one since we need to round up if we are 'close enough')
if (this.leftAxisMajorTickNumbersShow)
{
this.stringFormat.Alignment = StringAlignment.Far;
this.stringFormat.LineAlignment = StringAlignment.Center;
for (double i=0;i>-height-1;i-=stepSize)
{
if (this.leftAxisValueArray == null)
pe.Graphics.DrawString((this.leftAxisStartValue+this.leftAxisEndValue*(-i/height)).ToString(this.leftAxisMajorTickNumbersFormat), this.Font, Brushes.Black, (float)(-this.leftAxisMajorTickHeight-this.leftAxisMajorTickOffset), (float)i, this.stringFormat);
else
pe.Graphics.DrawString(this.leftAxisValueArray[(int)Math.Round(this.leftAxisStartValue+this.leftAxisEndValue*(-i/height))].ToString(this.leftAxisMajorTickNumbersFormat), this.Font, Brushes.Black, (float)(-this.leftAxisMajorTickHeight-this.leftAxisMajorTickOffset), (float)i, this.stringFormat);
}
}
// draw the axis label
if (this.leftAxisLabelShow)
{
this.stringFormat.LineAlignment = StringAlignment.Far;
this.stringFormat.Alignment = StringAlignment.Center;
pe.Graphics.RotateTransform(-90f);
if (this.leftAxisValueArray == null)
this.measuredSize = pe.Graphics.MeasureString(this.leftAxisEndValue.ToString(this.leftAxisMajorTickNumbersFormat), this.Font);
else
this.measuredSize = pe.Graphics.MeasureString(this.leftAxisValueArray[(int)this.leftAxisEndValue].ToString(this.leftAxisMajorTickNumbersFormat), this.Font);
pe.Graphics.DrawString(this.leftAxisLabel, this.Font, Brushes.Black, height/2f, -this.leftAxisMajorTickHeight-this.leftAxisMajorTickOffset-this.measuredSize.Width-1, this.stringFormat);
pe.Graphics.RotateTransform(90f);
}
// put the origin back to normal spot for other axis elements
pe.Graphics.TranslateTransform(-this.leftAxisStartPoint.X, -this.leftAxisStartPoint.Y);
}
#endregion
#region Right Axis Code
if (this.rightAxisShow && this.rightAxisControl != null && this.rightAxisStartValue != this.rightAxisEndValue)
{
this.rightAxisStartPoint = new Point(this.rightAxisControl.Right-this.Left, this.rightAxisControl.Bottom-1-this.Top);
this.rightAxisEndPoint = new Point(this.rightAxisControl.Right-this.Left, this.rightAxisControl.Top-this.Top);
// transform origin so we don't have to add these numbers all the time
pe.Graphics.TranslateTransform(this.rightAxisStartPoint.X, this.rightAxisStartPoint.Y);
// calculate the number of ticks to have so that the numbers don't overlap
int height = Math.Abs(this.rightAxisEndPoint.Y - this.rightAxisStartPoint.Y);
double ratio = Math.Abs(this.rightAxisStartValue - this.rightAxisEndValue) / (double)height;
double stepSize = height / Math.Ceiling((double)height / (this.Font.Height + this.rightAxisMajorTickNumbersSpacing));
// draw the major tick marks
for (double i=0;i>-height-1;i-=stepSize)
pe.Graphics.DrawLine(blackPen, 0f, (float)i, (float)this.rightAxisMajorTickHeight, (float)i);
// draw the major tick mark values (we add one since we need to round up if we are 'close enough')
if (this.rightAxisMajorTickNumbersShow)
{
this.stringFormat.Alignment = StringAlignment.Near;
this.stringFormat.LineAlignment = StringAlignment.Center;
for (double i=0;i>-height-1;i-=stepSize)
pe.Graphics.DrawString((this.rightAxisStartValue+(-i*ratio)).ToString(this.rightAxisMajorTickNumbersFormat), this.Font, Brushes.Black, (float)(this.rightAxisMajorTickHeight+this.rightAxisMajorTickOffset), (float)i, this.stringFormat);
}
// draw the axis label
if (this.rightAxisLabelShow)
{
stringFormat.LineAlignment = StringAlignment.Near;
stringFormat.Alignment = StringAlignment.Center;
pe.Graphics.RotateTransform(-90f);
this.measuredSize = pe.Graphics.MeasureString(this.rightAxisEndValue.ToString(this.rightAxisMajorTickNumbersFormat), this.Font);
SizeF tempSize = pe.Graphics.MeasureString(this.rightAxisStartValue.ToString(this.rightAxisMajorTickNumbersFormat), this.Font);
if (tempSize.Width > this.measuredSize.Width)
this.measuredSize = tempSize;
pe.Graphics.DrawString(this.rightAxisLabel, this.Font, Brushes.Black, height/2f, this.rightAxisMajorTickHeight+this.rightAxisMajorTickOffset+this.measuredSize.Width+1, stringFormat);
// rotate origin back to normal spot for other axis elements
pe.Graphics.RotateTransform(90f);
}
pe.Graphics.TranslateTransform(-this.rightAxisStartPoint.X, -this.rightAxisStartPoint.Y);
}
#endregion
// Calling the base class OnPaint
base.OnPaint(pe);
}
protected override void OnResize(EventArgs e)
{
// we need to invalidate so all the axes elements are redrawn/centered
this.Invalidate();
// Calling the base class OnResize
base.OnResize (e);
}
#region Top Axis
public Control TopAxisControl
{
set
{
this.topAxisControl = value;
}
}
public bool TopAxisShow
{
set
{
this.topAxisShow = value;
}
get
{
return this.topAxisShow;
}
}
public float TopAxisStartValue
{
set
{
this.topAxisStartValue = value;
}
get
{
return this.topAxisStartValue;
}
}
public float TopAxisEndValue
{
set
{
this.topAxisEndValue = value;
}
get
{
return this.topAxisEndValue;
}
}
public int TopAxisMajorTickHeight
{
set
{
this.topAxisMajorTickHeight = value;
}
get
{
return this.topAxisMajorTickHeight;
}
}
public int TopAxisMajorTickOffset
{
set
{
this.topAxisMajorTickOffset = value;
}
get
{
return this.topAxisMajorTickOffset;
}
}
public int TopAxisMajorTickNumbersSpacing
{
set
{
this.topAxisMajorTickNumbersSpacing = value;
}
get
{
return this.topAxisMajorTickNumbersSpacing;
}
}
public string TopAxisMajorTickNumbersFormat
{
set
{
this.topAxisMajorTickNumbersFormat = value;
}
get
{
return this.topAxisMajorTickNumbersFormat;
}
}
public bool TopAxisMajorTickNumbersShow
{
set
{
this.topAxisMajorTickNumbersShow = value;
}
get
{
return this.topAxisMajorTickNumbersShow;
}
}
public string TopAxisLabel
{
set
{
this.topAxisLabel = value;
}
get
{
return this.topAxisLabel;
}
}
public bool TopAxisLabelShow
{
set
{
this.topAxisLabelShow = value;
}
get
{
return this.topAxisLabelShow;
}
}
#endregion
#region Bottom Axis
public Control BottomAxisControl
{
set
{
this.bottomAxisControl = value;
}
}
public bool BottomAxisShow
{
set
{
this.bottomAxisShow = value;
}
get
{
return this.bottomAxisShow;
}
}
public float BottomAxisStartValue
{
set
{
this.bottomAxisStartValue = value;
}
get
{
return this.bottomAxisStartValue;
}
}
public float BottomAxisEndValue
{
set
{
this.bottomAxisEndValue = value;
}
get
{
return this.bottomAxisEndValue;
}
}
public double[] BottomAxisValueArray
{
set { this.bottomAxisValueArray = value; }
}
public int BottomAxisMajorTickHeight
{
set
{
this.bottomAxisMajorTickHeight = value;
}
get
{
return this.bottomAxisMajorTickHeight;
}
}
public int BottomAxisMajorTickOffset
{
set
{
this.bottomAxisMajorTickOffset = value;
}
get
{
return this.bottomAxisMajorTickOffset;
}
}
public int BottomAxisMajorTickNumbersSpacing
{
set
{
this.bottomAxisMajorTickNumbersSpacing = value;
}
get
{
return this.bottomAxisMajorTickNumbersSpacing;
}
}
public string BottomAxisMajorTickNumbersFormat
{
set
{
this.bottomAxisMajorTickNumbersFormat = value;
}
get
{
return this.bottomAxisMajorTickNumbersFormat;
}
}
public bool BottomAxisMajorTickNumbersShow
{
set
{
this.bottomAxisMajorTickNumbersShow = value;
}
get
{
return this.bottomAxisMajorTickNumbersShow;
}
}
public string BottomAxisLabel
{
set
{
this.bottomAxisLabel = value;
}
get
{
return this.bottomAxisLabel;
}
}
public bool BottomAxisLabelShow
{
set
{
this.bottomAxisLabelShow = value;
}
get
{
return this.bottomAxisLabelShow;
}
}
#endregion
#region Left Axis
public Control LeftAxisControl
{
set
{
this.leftAxisControl = value;
}
}
public bool LeftAxisShow
{
set
{
this.leftAxisShow = value;
}
get
{
return this.leftAxisShow;
}
}
public float LeftAxisStartValue
{
set
{
this.leftAxisStartValue = value;
}
get
{
return this.leftAxisStartValue;
}
}
public float LeftAxisEndValue
{
set
{
this.leftAxisEndValue = value;
}
get
{
return this.leftAxisEndValue;
}
}
public double[] LeftAxisValueArray
{
set { this.leftAxisValueArray = value; }
}
public int LeftAxisMajorTickHeight
{
set
{
this.leftAxisMajorTickHeight = value;
}
get
{
return this.leftAxisMajorTickHeight;
}
}
public int LeftAxisMajorTickOffset
{
set
{
this.leftAxisMajorTickOffset = value;
}
get
{
return this.leftAxisMajorTickOffset;
}
}
public int LeftAxisMajorTickNumbersSpacing
{
set
{
this.leftAxisMajorTickNumbersSpacing = value;
}
get
{
return this.leftAxisMajorTickNumbersSpacing;
}
}
public string LeftAxisMajorTickNumbersFormat
{
set
{
this.leftAxisMajorTickNumbersFormat = value;
}
get
{
return this.leftAxisMajorTickNumbersFormat;
}
}
public bool LeftAxisMajorTickNumbersShow
{
set
{
this.leftAxisMajorTickNumbersShow = value;
}
get
{
return this.leftAxisMajorTickNumbersShow;
}
}
public string LeftAxisLabel
{
set
{
this.leftAxisLabel = value;
}
get
{
return this.leftAxisLabel;
}
}
public bool LeftAxisLabelShow
{
set
{
this.leftAxisLabelShow = value;
}
get
{
return this.leftAxisLabelShow;
}
}
#endregion
#region Right Axis
public Control RightAxisControl
{
set
{
this.rightAxisControl = value;
}
}
public bool RightAxisShow
{
set
{
this.rightAxisShow = value;
}
get
{
return this.rightAxisShow;
}
}
public float RightAxisStartValue
{
set
{
this.rightAxisStartValue = value;
}
get
{
return this.rightAxisStartValue;
}
}
public float RightAxisEndValue
{
set
{
this.rightAxisEndValue = value;
}
get
{
return this.rightAxisEndValue;
}
}
public int RightAxisMajorTickHeight
{
set
{
this.rightAxisMajorTickHeight = value;
}
get
{
return this.rightAxisMajorTickHeight;
}
}
public int RightAxisMajorTickOffset
{
set
{
this.rightAxisMajorTickOffset = value;
}
get
{
return this.rightAxisMajorTickOffset;
}
}
public int RightAxisMajorTickNumbersSpacing
{
set
{
this.rightAxisMajorTickNumbersSpacing = value;
}
get
{
return this.rightAxisMajorTickNumbersSpacing;
}
}
public string RightAxisMajorTickNumbersFormat
{
set
{
this.rightAxisMajorTickNumbersFormat = value;
}
get
{
return this.rightAxisMajorTickNumbersFormat;
}
}
public bool RightAxisMajorTickNumbersShow
{
set
{
this.rightAxisMajorTickNumbersShow = value;
}
get
{
return this.rightAxisMajorTickNumbersShow;
}
}
public string RightAxisLabel
{
set
{
this.rightAxisLabel = value;
}
get
{
return this.rightAxisLabel;
}
}
public bool RightAxisLabelShow
{
set
{
this.rightAxisLabelShow = value;
}
get
{
return this.rightAxisLabelShow;
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Reflection.Internal;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
namespace System.Reflection.Metadata
{
[DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
public unsafe struct BlobReader
{
/// <summary>An array containing the '\0' character.</summary>
private static readonly char[] _nullCharArray = new char[1] { '\0' };
internal const int InvalidCompressedInteger = Int32.MaxValue;
private readonly MemoryBlock _block;
// Points right behind the last byte of the block.
private readonly byte* _endPointer;
private byte* _currentPointer;
public unsafe BlobReader(byte* buffer, int length)
{
if (length < 0)
{
throw new ArgumentOutOfRangeException("length");
}
if (buffer == null && length != 0)
{
throw new ArgumentNullException("buffer");
}
// the reader performs little-endian specific operations
if (!BitConverter.IsLittleEndian)
{
throw new PlatformNotSupportedException(SR.LitteEndianArchitectureRequired);
}
this = new BlobReader(new MemoryBlock(buffer, length));
}
internal BlobReader(MemoryBlock block)
{
Debug.Assert(BitConverter.IsLittleEndian && block.Length >= 0 && (block.Pointer != null || block.Length == 0));
_block = block;
_currentPointer = block.Pointer;
_endPointer = block.Pointer + block.Length;
}
private string GetDebuggerDisplay()
{
if (_block.Pointer == null)
{
return "<null>";
}
int displayedBytes;
string display = _block.GetDebuggerDisplay(out displayedBytes);
if (this.Offset < displayedBytes)
{
display = display.Insert(this.Offset * 3, "*");
}
else if (displayedBytes == _block.Length)
{
display += "*";
}
else
{
display += "*...";
}
return display;
}
#region Offset, Skipping, Marking, Alignment, Bounds Checking
public int Length
{
get
{
return _block.Length;
}
}
public int Offset
{
get
{
return (int)(_currentPointer - _block.Pointer);
}
}
public int RemainingBytes
{
get
{
return (int)(_endPointer - _currentPointer);
}
}
public void Reset()
{
_currentPointer = _block.Pointer;
}
internal bool SeekOffset(int offset)
{
if (unchecked((uint)offset) >= (uint)_block.Length)
{
return false;
}
_currentPointer = _block.Pointer + offset;
return true;
}
internal void SkipBytes(int count)
{
GetCurrentPointerAndAdvance(count);
}
internal void Align(byte alignment)
{
if (!TryAlign(alignment))
{
ThrowOutOfBounds();
}
}
internal bool TryAlign(byte alignment)
{
int remainder = this.Offset & (alignment - 1);
Debug.Assert((alignment & (alignment - 1)) == 0, "Alignment must be a power of two.");
Debug.Assert(remainder >= 0 && remainder < alignment);
if (remainder != 0)
{
int bytesToSkip = alignment - remainder;
if (bytesToSkip > RemainingBytes)
{
return false;
}
_currentPointer += bytesToSkip;
}
return true;
}
internal MemoryBlock GetMemoryBlockAt(int offset, int length)
{
CheckBounds(offset, length);
return new MemoryBlock(_currentPointer + offset, length);
}
#endregion
#region Bounds Checking
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowOutOfBounds()
{
throw new BadImageFormatException(SR.OutOfBoundsRead);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void CheckBounds(int offset, int byteCount)
{
if (unchecked((ulong)(uint)offset + (uint)byteCount) > (ulong)(_endPointer - _currentPointer))
{
ThrowOutOfBounds();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void CheckBounds(int byteCount)
{
if (unchecked((uint)byteCount) > (_endPointer - _currentPointer))
{
ThrowOutOfBounds();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private byte* GetCurrentPointerAndAdvance(int length)
{
byte* p = _currentPointer;
if (unchecked((uint)length) > (uint)(_endPointer - p))
{
ThrowOutOfBounds();
}
_currentPointer = p + length;
return p;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private byte* GetCurrentPointerAndAdvance1()
{
byte* p = _currentPointer;
if (p == _endPointer)
{
ThrowOutOfBounds();
}
_currentPointer = p + 1;
return p;
}
#endregion
#region Read Methods
public bool ReadBoolean()
{
return ReadByte() == 1;
}
public SByte ReadSByte()
{
return *(SByte*)GetCurrentPointerAndAdvance1();
}
public Byte ReadByte()
{
return *(Byte*)GetCurrentPointerAndAdvance1();
}
public Char ReadChar()
{
return *(Char*)GetCurrentPointerAndAdvance(sizeof(Char));
}
public Int16 ReadInt16()
{
return *(Int16*)GetCurrentPointerAndAdvance(sizeof(Int16));
}
public UInt16 ReadUInt16()
{
return *(UInt16*)GetCurrentPointerAndAdvance(sizeof(UInt16));
}
public Int32 ReadInt32()
{
return *(Int32*)GetCurrentPointerAndAdvance(sizeof(Int32));
}
public UInt32 ReadUInt32()
{
return *(UInt32*)GetCurrentPointerAndAdvance(sizeof(UInt32));
}
public Int64 ReadInt64()
{
return *(Int64*)GetCurrentPointerAndAdvance(sizeof(Int64));
}
public UInt64 ReadUInt64()
{
return *(UInt64*)GetCurrentPointerAndAdvance(sizeof(UInt64));
}
public Single ReadSingle()
{
return *(Single*)GetCurrentPointerAndAdvance(sizeof(Single));
}
public Double ReadDouble()
{
return *(Double*)GetCurrentPointerAndAdvance(sizeof(UInt64));
}
public SignatureHeader ReadSignatureHeader()
{
return new SignatureHeader(ReadByte());
}
/// <summary>
/// Reads UTF8 encoded string starting at the current position.
/// </summary>
/// <param name="byteCount">The number of bytes to read.</param>
/// <returns>The string.</returns>
/// <exception cref="BadImageFormatException"><paramref name="byteCount"/> bytes not available.</exception>
public string ReadUTF8(int byteCount)
{
string s = _block.PeekUtf8(this.Offset, byteCount);
_currentPointer += byteCount;
return s;
}
/// <summary>
/// Reads UTF16 (little-endian) encoded string starting at the current position.
/// </summary>
/// <param name="byteCount">The number of bytes to read.</param>
/// <returns>The string.</returns>
/// <exception cref="BadImageFormatException"><paramref name="byteCount"/> bytes not available.</exception>
public string ReadUTF16(int byteCount)
{
string s = _block.PeekUtf16(this.Offset, byteCount);
_currentPointer += byteCount;
return s;
}
/// <summary>
/// Reads bytes starting at the current position.
/// </summary>
/// <param name="byteCount">The number of bytes to read.</param>
/// <returns>The byte array.</returns>
/// <exception cref="BadImageFormatException"><paramref name="byteCount"/> bytes not available.</exception>
public byte[] ReadBytes(int byteCount)
{
byte[] bytes = _block.PeekBytes(this.Offset, byteCount);
_currentPointer += byteCount;
return bytes;
}
internal string ReadUtf8NullTerminated()
{
int bytesRead;
string value = _block.PeekUtf8NullTerminated(this.Offset, null, MetadataStringDecoder.DefaultUTF8, out bytesRead, '\0');
_currentPointer += bytesRead;
return value;
}
private int ReadCompressedIntegerOrInvalid()
{
int bytesRead;
int value = _block.PeekCompressedInteger(this.Offset, out bytesRead);
_currentPointer += bytesRead;
return value;
}
/// <summary>
/// Reads an unsigned compressed integer value.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <param name="value">The value of the compressed integer that was read.</param>
/// <returns>true if the value was read successfully. false if the data at the current position was not a valid compressed integer.</returns>
public bool TryReadCompressedInteger(out int value)
{
value = ReadCompressedIntegerOrInvalid();
return value != InvalidCompressedInteger;
}
/// <summary>
/// Reads an unsigned compressed integer value.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <returns>The value of the compressed integer that was read.</returns>
/// <exception cref="System.BadImageFormatException">The data at the current position was not a valid compressed integer.</exception>
public int ReadCompressedInteger()
{
int value;
if (!TryReadCompressedInteger(out value))
{
ThrowInvalidCompressedInteger();
}
return value;
}
/// <summary>
/// Reads a signed compressed integer value.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <param name="value">The value of the compressed integer that was read.</param>
/// <returns>true if the value was read successfully. false if the data at the current position was not a valid compressed integer.</returns>
public bool TryReadCompressedSignedInteger(out int value)
{
int bytesRead;
value = _block.PeekCompressedInteger(this.Offset, out bytesRead);
if (value == InvalidCompressedInteger)
{
return false;
}
bool signExtend = (value & 0x1) != 0;
value >>= 1;
if (signExtend)
{
switch (bytesRead)
{
case 1:
value |= unchecked((int)0xffffffc0);
break;
case 2:
value |= unchecked((int)0xffffe000);
break;
default:
Debug.Assert(bytesRead == 4);
value |= unchecked((int)0xf0000000);
break;
}
}
_currentPointer += bytesRead;
return true;
}
/// <summary>
/// Reads a signed compressed integer value.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <returns>The value of the compressed integer that was read.</returns>
/// <exception cref="System.BadImageFormatException">The data at the current position was not a valid compressed integer.</exception>
public int ReadCompressedSignedInteger()
{
int value;
if (!TryReadCompressedSignedInteger(out value))
{
ThrowInvalidCompressedInteger();
}
return value;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowInvalidCompressedInteger()
{
throw new BadImageFormatException(SR.InvalidCompressedInteger);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowInvalidSerializedString()
{
throw new BadImageFormatException(SR.InvalidSerializedString);
}
/// <summary>
/// Reads type code encoded in a serialized custom attribute value.
/// </summary>
/// <returns><see cref="SerializationTypeCode.Invalid"/> if the encoding is invalid.</returns>
public SerializationTypeCode ReadSerializationTypeCode()
{
int value = ReadCompressedIntegerOrInvalid();
if (value > byte.MaxValue)
{
return SerializationTypeCode.Invalid;
}
return unchecked((SerializationTypeCode)value);
}
/// <summary>
/// Reads type code encoded in a signature.
/// </summary>
/// <returns><see cref="SignatureTypeCode.Invalid"/> if the encoding is invalid.</returns>
public SignatureTypeCode ReadSignatureTypeCode()
{
int value = ReadCompressedIntegerOrInvalid();
switch (value)
{
case (int)CorElementType.ELEMENT_TYPE_CLASS:
case (int)CorElementType.ELEMENT_TYPE_VALUETYPE:
return SignatureTypeCode.TypeHandle;
default:
if (value > byte.MaxValue)
{
return SignatureTypeCode.Invalid;
}
return unchecked((SignatureTypeCode)value);
}
}
/// <summary>
/// Reads a string encoded as a compressed integer containing its length followed by
/// its contents in UTF8. Null strings are encoded as a single 0xFF byte.
/// </summary>
/// <remarks>Defined as a 'SerString' in the Ecma CLI specification.</remarks>
/// <returns>String value or null.</returns>
/// <exception cref="BadImageFormatException">If the encoding is invalid.</exception>
public string ReadSerializedString()
{
int length;
if (TryReadCompressedInteger(out length))
{
// Removal of trailing '\0' is a departure from the spec, but required
// for compatibility with legacy compilers.
return ReadUTF8(length).TrimEnd(_nullCharArray);
}
if (ReadByte() != 0xFF)
{
ThrowInvalidSerializedString();
}
return null;
}
/// <summary>
/// Reads a type handle encoded in a signature as TypeDefOrRefOrSpecEncoded (see ECMA-335 II.23.2.8).
/// </summary>
/// <returns>The handle or nil if the encoding is invalid.</returns>
public EntityHandle ReadTypeHandle()
{
uint value = (uint)ReadCompressedIntegerOrInvalid();
uint tokenType = s_corEncodeTokenArray[value & 0x3];
if (value == InvalidCompressedInteger || tokenType == 0)
{
return default(EntityHandle);
}
return new EntityHandle(tokenType | (value >> 2));
}
private static readonly uint[] s_corEncodeTokenArray = new uint[] { TokenTypeIds.TypeDef, TokenTypeIds.TypeRef, TokenTypeIds.TypeSpec, 0 };
#endregion
}
}
| |
#region License
// Copyright (c) 2007-2018, Sean Chambers <schambers80@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System.Data;
using FluentMigrator.Expressions;
using FluentMigrator.Infrastructure;
using FluentMigrator.Model;
namespace FluentMigrator.Builders.Alter.Column
{
/// <summary>
/// An expression builder for a <see cref="AlterColumnExpression"/>
/// </summary>
public class AlterColumnExpressionBuilder : ExpressionBuilderWithColumnTypesBase<AlterColumnExpression, IAlterColumnOptionSyntax>,
IAlterColumnOnTableSyntax,
IAlterColumnAsTypeOrInSchemaSyntax,
IAlterColumnOptionOrForeignKeyCascadeSyntax,
IColumnExpressionBuilder
{
private readonly IMigrationContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="AlterColumnExpressionBuilder"/> class.
/// </summary>
/// <param name="expression">The underlying expression</param>
/// <param name="context">The migration context</param>
public AlterColumnExpressionBuilder(AlterColumnExpression expression, IMigrationContext context)
: base(expression)
{
_context = context;
ColumnHelper = new ColumnExpressionBuilderHelper(this, context);
}
/// <summary>
/// Gets or sets the current foreign key
/// </summary>
public ForeignKeyDefinition CurrentForeignKey { get; set; }
/// <summary>
/// Gets or sets a column expression builder helper
/// </summary>
public ColumnExpressionBuilderHelper ColumnHelper { get; set; }
/// <inheritdoc />
public IAlterColumnAsTypeOrInSchemaSyntax OnTable(string name)
{
Expression.TableName = name;
return this;
}
/// <inheritdoc />
public IAlterColumnAsTypeSyntax InSchema(string schemaName)
{
Expression.SchemaName = schemaName;
return this;
}
/// <inheritdoc />
public IAlterColumnOptionSyntax WithDefault(SystemMethods method)
{
return WithDefaultValue(method);
}
/// <inheritdoc />
public IAlterColumnOptionSyntax WithDefaultValue(object value)
{
// we need to do a drop constraint and then add constraint to change the default value
var dc = new AlterDefaultConstraintExpression
{
TableName = Expression.TableName,
SchemaName = Expression.SchemaName,
ColumnName = Expression.Column.Name,
DefaultValue = value
};
_context.Expressions.Add(dc);
Expression.Column.DefaultValue = value;
return this;
}
/// <inheritdoc />
public IAlterColumnOptionSyntax WithColumnDescription(string description)
{
Expression.Column.ColumnDescription = description;
return this;
}
/// <inheritdoc />
public IAlterColumnOptionSyntax Identity()
{
Expression.Column.IsIdentity = true;
return this;
}
/// <inheritdoc />
public IAlterColumnOptionSyntax Indexed()
{
return Indexed(null);
}
/// <inheritdoc />
public IAlterColumnOptionSyntax Indexed(string indexName)
{
ColumnHelper.Indexed(indexName);
return this;
}
/// <inheritdoc />
public IAlterColumnOptionSyntax PrimaryKey()
{
Expression.Column.IsPrimaryKey = true;
return this;
}
/// <inheritdoc />
public IAlterColumnOptionSyntax PrimaryKey(string primaryKeyName)
{
Expression.Column.IsPrimaryKey = true;
Expression.Column.PrimaryKeyName = primaryKeyName;
return this;
}
/// <inheritdoc />
public IAlterColumnOptionSyntax Nullable()
{
ColumnHelper.SetNullable(true);
return this;
}
/// <inheritdoc />
public IAlterColumnOptionSyntax NotNullable()
{
ColumnHelper.SetNullable(false);
return this;
}
/// <inheritdoc />
public IAlterColumnOptionSyntax Unique()
{
ColumnHelper.Unique(null);
return this;
}
/// <inheritdoc />
public IAlterColumnOptionSyntax Unique(string indexName)
{
ColumnHelper.Unique(indexName);
return this;
}
/// <inheritdoc />
public IAlterColumnOptionOrForeignKeyCascadeSyntax ForeignKey(string primaryTableName, string primaryColumnName)
{
return ForeignKey(null, null, primaryTableName, primaryColumnName);
}
/// <inheritdoc />
public IAlterColumnOptionOrForeignKeyCascadeSyntax ForeignKey(string foreignKeyName, string primaryTableName, string primaryColumnName)
{
return ForeignKey(foreignKeyName, null, primaryTableName, primaryColumnName);
}
/// <inheritdoc />
public IAlterColumnOptionOrForeignKeyCascadeSyntax ForeignKey(string foreignKeyName, string primaryTableSchema, string primaryTableName,
string primaryColumnName)
{
Expression.Column.IsForeignKey = true;
var fk = new CreateForeignKeyExpression
{
ForeignKey = new ForeignKeyDefinition
{
Name = foreignKeyName,
PrimaryTable = primaryTableName,
PrimaryTableSchema = primaryTableSchema,
ForeignTable = Expression.TableName,
ForeignTableSchema = Expression.SchemaName
}
};
fk.ForeignKey.PrimaryColumns.Add(primaryColumnName);
fk.ForeignKey.ForeignColumns.Add(Expression.Column.Name);
_context.Expressions.Add(fk);
CurrentForeignKey = fk.ForeignKey;
Expression.Column.ForeignKey = fk.ForeignKey;
return this;
}
/// <inheritdoc />
public IAlterColumnOptionOrForeignKeyCascadeSyntax ReferencedBy(string foreignTableName, string foreignColumnName)
{
return ReferencedBy(null, null, foreignTableName, foreignColumnName);
}
/// <inheritdoc />
public IAlterColumnOptionOrForeignKeyCascadeSyntax ReferencedBy(string foreignKeyName, string foreignTableName, string foreignColumnName)
{
return ReferencedBy(foreignKeyName, null, foreignTableName, foreignColumnName);
}
/// <inheritdoc />
public IAlterColumnOptionOrForeignKeyCascadeSyntax ReferencedBy(string foreignKeyName, string foreignTableSchema, string foreignTableName,
string foreignColumnName)
{
var fk = new CreateForeignKeyExpression
{
ForeignKey = new ForeignKeyDefinition
{
Name = foreignKeyName,
PrimaryTable = Expression.TableName,
PrimaryTableSchema = Expression.SchemaName,
ForeignTable = foreignTableName,
ForeignTableSchema = foreignTableSchema
}
};
fk.ForeignKey.PrimaryColumns.Add(Expression.Column.Name);
fk.ForeignKey.ForeignColumns.Add(foreignColumnName);
_context.Expressions.Add(fk);
CurrentForeignKey = fk.ForeignKey;
return this;
}
/// <inheritdoc />
public IAlterColumnOptionOrForeignKeyCascadeSyntax ForeignKey()
{
Expression.Column.IsForeignKey = true;
return this;
}
/// <inheritdoc />
public override ColumnDefinition GetColumnForType()
{
return Expression.Column;
}
/// <inheritdoc />
public IAlterColumnOptionOrForeignKeyCascadeSyntax OnDelete(Rule rule)
{
CurrentForeignKey.OnDelete = rule;
return this;
}
/// <inheritdoc />
public IAlterColumnOptionOrForeignKeyCascadeSyntax OnUpdate(Rule rule)
{
CurrentForeignKey.OnUpdate = rule;
return this;
}
/// <inheritdoc />
public IAlterColumnOptionSyntax OnDeleteOrUpdate(Rule rule)
{
OnDelete(rule);
OnUpdate(rule);
return this;
}
/// <inheritdoc />
string IColumnExpressionBuilder.SchemaName => Expression.SchemaName;
/// <inheritdoc />
string IColumnExpressionBuilder.TableName => Expression.TableName;
/// <inheritdoc />
ColumnDefinition IColumnExpressionBuilder.Column => Expression.Column;
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Collections.Generic;
using OpenHome.Net.Core;
namespace OpenHome.Net.Device.Providers
{
public interface IDvProviderOpenhomeOrgTestLights1 : IDisposable
{
}
/// <summary>
/// Provider for the openhome.org:TestLights:1 UPnP service
/// </summary>
public class DvProviderOpenhomeOrgTestLights1 : DvProvider, IDisposable, IDvProviderOpenhomeOrgTestLights1
{
private GCHandle iGch;
private ActionDelegate iDelegateGetCount;
private ActionDelegate iDelegateGetRoom;
private ActionDelegate iDelegateGetName;
private ActionDelegate iDelegateGetPosition;
private ActionDelegate iDelegateSetColor;
private ActionDelegate iDelegateGetColor;
private ActionDelegate iDelegateGetColorComponents;
/// <summary>
/// Constructor
/// </summary>
/// <param name="aDevice">Device which owns this provider</param>
protected DvProviderOpenhomeOrgTestLights1(DvDevice aDevice)
: base(aDevice, "openhome.org", "TestLights", 1)
{
iGch = GCHandle.Alloc(this);
}
/// <summary>
/// Signal that the action GetCount is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// GetCount must be overridden if this is called.</remarks>
protected void EnableActionGetCount()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("GetCount");
action.AddOutputParameter(new ParameterUint("Count"));
iDelegateGetCount = new ActionDelegate(DoGetCount);
EnableAction(action, iDelegateGetCount, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action GetRoom is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// GetRoom must be overridden if this is called.</remarks>
protected void EnableActionGetRoom()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("GetRoom");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterUint("Index"));
action.AddOutputParameter(new ParameterString("RoomName", allowedValues));
iDelegateGetRoom = new ActionDelegate(DoGetRoom);
EnableAction(action, iDelegateGetRoom, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action GetName is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// GetName must be overridden if this is called.</remarks>
protected void EnableActionGetName()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("GetName");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterUint("Index"));
action.AddOutputParameter(new ParameterString("FriendlyName", allowedValues));
iDelegateGetName = new ActionDelegate(DoGetName);
EnableAction(action, iDelegateGetName, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action GetPosition is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// GetPosition must be overridden if this is called.</remarks>
protected void EnableActionGetPosition()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("GetPosition");
action.AddInputParameter(new ParameterUint("Index"));
action.AddOutputParameter(new ParameterUint("X"));
action.AddOutputParameter(new ParameterUint("Y"));
action.AddOutputParameter(new ParameterUint("Z"));
iDelegateGetPosition = new ActionDelegate(DoGetPosition);
EnableAction(action, iDelegateGetPosition, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action SetColor is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// SetColor must be overridden if this is called.</remarks>
protected void EnableActionSetColor()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("SetColor");
action.AddInputParameter(new ParameterUint("Index"));
action.AddInputParameter(new ParameterUint("Color"));
iDelegateSetColor = new ActionDelegate(DoSetColor);
EnableAction(action, iDelegateSetColor, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action GetColor is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// GetColor must be overridden if this is called.</remarks>
protected void EnableActionGetColor()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("GetColor");
action.AddInputParameter(new ParameterUint("Index"));
action.AddOutputParameter(new ParameterUint("Color"));
iDelegateGetColor = new ActionDelegate(DoGetColor);
EnableAction(action, iDelegateGetColor, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action GetColorComponents is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// GetColorComponents must be overridden if this is called.</remarks>
protected void EnableActionGetColorComponents()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("GetColorComponents");
action.AddInputParameter(new ParameterUint("Color"));
action.AddOutputParameter(new ParameterUint("Brightness"));
action.AddOutputParameter(new ParameterUint("Red"));
action.AddOutputParameter(new ParameterUint("Green"));
action.AddOutputParameter(new ParameterUint("Blue"));
iDelegateGetColorComponents = new ActionDelegate(DoGetColorComponents);
EnableAction(action, iDelegateGetColorComponents, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// GetCount action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// GetCount action for the owning device.
///
/// Must be implemented iff EnableActionGetCount was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aCount"></param>
protected virtual void GetCount(IDvInvocation aInvocation, out uint aCount)
{
throw (new ActionDisabledError());
}
/// <summary>
/// GetRoom action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// GetRoom action for the owning device.
///
/// Must be implemented iff EnableActionGetRoom was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aIndex"></param>
/// <param name="aRoomName"></param>
protected virtual void GetRoom(IDvInvocation aInvocation, uint aIndex, out string aRoomName)
{
throw (new ActionDisabledError());
}
/// <summary>
/// GetName action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// GetName action for the owning device.
///
/// Must be implemented iff EnableActionGetName was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aIndex"></param>
/// <param name="aFriendlyName"></param>
protected virtual void GetName(IDvInvocation aInvocation, uint aIndex, out string aFriendlyName)
{
throw (new ActionDisabledError());
}
/// <summary>
/// GetPosition action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// GetPosition action for the owning device.
///
/// Must be implemented iff EnableActionGetPosition was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aIndex"></param>
/// <param name="aX"></param>
/// <param name="aY"></param>
/// <param name="aZ"></param>
protected virtual void GetPosition(IDvInvocation aInvocation, uint aIndex, out uint aX, out uint aY, out uint aZ)
{
throw (new ActionDisabledError());
}
/// <summary>
/// SetColor action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// SetColor action for the owning device.
///
/// Must be implemented iff EnableActionSetColor was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aIndex"></param>
/// <param name="aColor"></param>
protected virtual void SetColor(IDvInvocation aInvocation, uint aIndex, uint aColor)
{
throw (new ActionDisabledError());
}
/// <summary>
/// GetColor action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// GetColor action for the owning device.
///
/// Must be implemented iff EnableActionGetColor was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aIndex"></param>
/// <param name="aColor"></param>
protected virtual void GetColor(IDvInvocation aInvocation, uint aIndex, out uint aColor)
{
throw (new ActionDisabledError());
}
/// <summary>
/// GetColorComponents action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// GetColorComponents action for the owning device.
///
/// Must be implemented iff EnableActionGetColorComponents was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aColor"></param>
/// <param name="aBrightness"></param>
/// <param name="aRed"></param>
/// <param name="aGreen"></param>
/// <param name="aBlue"></param>
protected virtual void GetColorComponents(IDvInvocation aInvocation, uint aColor, out uint aBrightness, out uint aRed, out uint aGreen, out uint aBlue)
{
throw (new ActionDisabledError());
}
private static int DoGetCount(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderOpenhomeOrgTestLights1 self = (DvProviderOpenhomeOrgTestLights1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
uint count;
try
{
invocation.ReadStart();
invocation.ReadEnd();
self.GetCount(invocation, out count);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "GetCount");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "GetCount"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetCount", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteUint("Count", count);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetCount", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoGetRoom(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderOpenhomeOrgTestLights1 self = (DvProviderOpenhomeOrgTestLights1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
uint index;
string roomName;
try
{
invocation.ReadStart();
index = invocation.ReadUint("Index");
invocation.ReadEnd();
self.GetRoom(invocation, index, out roomName);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "GetRoom");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "GetRoom"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetRoom", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteString("RoomName", roomName);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetRoom", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoGetName(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderOpenhomeOrgTestLights1 self = (DvProviderOpenhomeOrgTestLights1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
uint index;
string friendlyName;
try
{
invocation.ReadStart();
index = invocation.ReadUint("Index");
invocation.ReadEnd();
self.GetName(invocation, index, out friendlyName);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "GetName");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "GetName"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetName", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteString("FriendlyName", friendlyName);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetName", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoGetPosition(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderOpenhomeOrgTestLights1 self = (DvProviderOpenhomeOrgTestLights1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
uint index;
uint x;
uint y;
uint z;
try
{
invocation.ReadStart();
index = invocation.ReadUint("Index");
invocation.ReadEnd();
self.GetPosition(invocation, index, out x, out y, out z);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "GetPosition");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "GetPosition"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetPosition", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteUint("X", x);
invocation.WriteUint("Y", y);
invocation.WriteUint("Z", z);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetPosition", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoSetColor(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderOpenhomeOrgTestLights1 self = (DvProviderOpenhomeOrgTestLights1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
uint index;
uint color;
try
{
invocation.ReadStart();
index = invocation.ReadUint("Index");
color = invocation.ReadUint("Color");
invocation.ReadEnd();
self.SetColor(invocation, index, color);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "SetColor");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "SetColor"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "SetColor", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "SetColor", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoGetColor(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderOpenhomeOrgTestLights1 self = (DvProviderOpenhomeOrgTestLights1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
uint index;
uint color;
try
{
invocation.ReadStart();
index = invocation.ReadUint("Index");
invocation.ReadEnd();
self.GetColor(invocation, index, out color);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "GetColor");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "GetColor"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetColor", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteUint("Color", color);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetColor", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoGetColorComponents(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderOpenhomeOrgTestLights1 self = (DvProviderOpenhomeOrgTestLights1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
uint color;
uint brightness;
uint red;
uint green;
uint blue;
try
{
invocation.ReadStart();
color = invocation.ReadUint("Color");
invocation.ReadEnd();
self.GetColorComponents(invocation, color, out brightness, out red, out green, out blue);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "GetColorComponents");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "GetColorComponents"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetColorComponents", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteUint("Brightness", brightness);
invocation.WriteUint("Red", red);
invocation.WriteUint("Green", green);
invocation.WriteUint("Blue", blue);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetColorComponents", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
/// <summary>
/// Must be called for each class instance. Must be called before Core.Library.Close().
/// </summary>
public virtual void Dispose()
{
if (DisposeProvider())
iGch.Free();
}
}
}
| |
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Reflection;
using UnrealBuildTool;
namespace AutomationTool
{
/// <summary>
/// Platform abstraction layer.
/// </summary>
public class Platform : CommandUtils
{
#region Intialization
private static Dictionary<UnrealTargetPlatform, Platform> AllPlatforms = new Dictionary<UnrealTargetPlatform, Platform>();
internal static void InitializePlatforms(Assembly[] AssembliesWithPlatforms = null)
{
LogVerbose("Creating platforms.");
// Create all available platforms.
foreach (var ScriptAssembly in (AssembliesWithPlatforms != null ? AssembliesWithPlatforms : AppDomain.CurrentDomain.GetAssemblies()))
{
CreatePlatformsFromAssembly(ScriptAssembly);
}
// Create dummy platforms for platforms we don't support
foreach (var PlatformType in Enum.GetValues(typeof(UnrealTargetPlatform)))
{
var TargetType = (UnrealTargetPlatform)PlatformType;
Platform ExistingInstance;
if (AllPlatforms.TryGetValue(TargetType, out ExistingInstance) == false)
{
LogVerbose("Creating placeholder platform for target: {0}", TargetType);
AllPlatforms.Add(TargetType, new Platform(TargetType));
}
}
}
private static void CreatePlatformsFromAssembly(Assembly ScriptAssembly)
{
LogVerbose("Looking for platforms in {0}", ScriptAssembly.Location);
Type[] AllTypes = null;
try
{
AllTypes = ScriptAssembly.GetTypes();
}
catch (Exception Ex)
{
LogError("Failed to get assembly types for {0}", ScriptAssembly.Location);
if (Ex is ReflectionTypeLoadException)
{
var TypeLoadException = (ReflectionTypeLoadException)Ex;
if (!IsNullOrEmpty(TypeLoadException.LoaderExceptions))
{
LogError("Loader Exceptions:");
foreach (var LoaderException in TypeLoadException.LoaderExceptions)
{
Log(System.Diagnostics.TraceEventType.Error, LoaderException);
}
}
else
{
LogError("No Loader Exceptions available.");
}
}
// Re-throw, this is still a critical error!
throw Ex;
}
foreach (var PotentialPlatformType in AllTypes)
{
if (PotentialPlatformType != typeof(Platform) && typeof(Platform).IsAssignableFrom(PotentialPlatformType) && !PotentialPlatformType.IsAbstract)
{
LogVerbose("Creating platform {0} from {1}.", PotentialPlatformType.Name, ScriptAssembly.Location);
var PlatformInstance = Activator.CreateInstance(PotentialPlatformType) as Platform;
Platform ExistingInstance;
if (!AllPlatforms.TryGetValue(PlatformInstance.PlatformType, out ExistingInstance))
{
AllPlatforms.Add(PlatformInstance.PlatformType, PlatformInstance);
}
else
{
LogWarning("Platform {0} already exists", PotentialPlatformType.Name);
}
}
}
}
#endregion
protected UnrealTargetPlatform TargetPlatformType = UnrealTargetPlatform.Unknown;
public Platform(UnrealTargetPlatform PlatformType)
{
TargetPlatformType = PlatformType;
}
/// <summary>
/// Allow the platform to alter the ProjectParams
/// </summary>
/// <param name="ProjParams"></param>
public virtual void PlatformSetupParams(ref ProjectParams ProjParams)
{
}
/// <summary>
/// Package files for the current platform.
/// </summary>
/// <param name="ProjectPath"></param>
/// <param name="ProjectExeFilename"></param>
public virtual void Package(ProjectParams Params, DeploymentContext SC, int WorkingCL)
{
throw new AutomationException("{0} does not yet implement Packaging.", PlatformType);
}
/// <summary>
/// Allow platform to do platform specific work on archived project before it's deployed.
/// </summary>
/// <param name="Params"></param>
/// <param name="SC"></param>
public virtual void ProcessArchivedProject(ProjectParams Params, DeploymentContext SC)
{
}
/// <summary>
/// Get all connected device names for this platform
/// </summary>
/// <param name="Params"></param>
/// <param name="SC"></param>
public virtual void GetConnectedDevices(ProjectParams Params, out List<string> Devices)
{
Devices = null;
LogWarning("{0} does not implement GetConnectedDevices", PlatformType);
}
/// <summary>
/// Deploy the application on the current platform
/// </summary>
/// <param name="Params"></param>
/// <param name="SC"></param>
public virtual void Deploy(ProjectParams Params, DeploymentContext SC)
{
LogWarning("{0} does not implement Deploy...", PlatformType);
}
/// <summary>
/// Run the client application on the platform
/// </summary>
/// <param name="ClientRunFlags"></param>
/// <param name="ClientApp"></param>
/// <param name="ClientCmdLine"></param>
public virtual ProcessResult RunClient(ERunOptions ClientRunFlags, string ClientApp, string ClientCmdLine, ProjectParams Params)
{
PushDir(Path.GetDirectoryName(ClientApp));
// Always start client process and don't wait for exit.
ProcessResult ClientProcess = Run(ClientApp, ClientCmdLine, null, ClientRunFlags | ERunOptions.NoWaitForExit);
PopDir();
return ClientProcess;
}
/// <summary>
/// Allow platform specific clean-up or detection after client has run
/// </summary>
/// <param name="ClientRunFlags"></param>
public virtual void PostRunClient(ProcessResult Result, ProjectParams Params)
{
// do nothing in the default case
}
/// <summary>
/// Get the platform-specific name for the executable (with out the file extension)
/// </summary>
/// <param name="InExecutableName"></param>
/// <returns></returns>
public virtual string GetPlatformExecutableName(string InExecutableName)
{
return InExecutableName;
}
public virtual List<string> GetExecutableNames(DeploymentContext SC, bool bIsRun = false)
{
var ExecutableNames = new List<String>();
string Ext = AutomationTool.Platform.GetExeExtension(SC.StageTargetPlatform.TargetPlatformType);
if (!String.IsNullOrEmpty(SC.CookPlatform))
{
if (SC.StageExecutables.Count() > 0)
{
foreach (var StageExecutable in SC.StageExecutables)
{
string ExeName = SC.StageTargetPlatform.GetPlatformExecutableName(StageExecutable);
if (!SC.IsCodeBasedProject)
{
ExecutableNames.Add(CombinePaths(SC.RuntimeRootDir, "Engine/Binaries", SC.PlatformDir, ExeName + Ext));
}
else
{
ExecutableNames.Add(CombinePaths(SC.RuntimeProjectRootDir, "Binaries", SC.PlatformDir, ExeName + Ext));
}
}
}
//@todo, probably the rest of this can go away once everything passes it through
else if (SC.DedicatedServer)
{
if (!SC.IsCodeBasedProject)
{
string ExeName = SC.StageTargetPlatform.GetPlatformExecutableName("UE4Server");
ExecutableNames.Add(CombinePaths(SC.RuntimeRootDir, "Engine/Binaries", SC.PlatformDir, ExeName + Ext));
}
else
{
string ExeName = SC.StageTargetPlatform.GetPlatformExecutableName(SC.ShortProjectName + "Server");
string ClientApp = CombinePaths(SC.RuntimeProjectRootDir, "Binaries", SC.PlatformDir, ExeName + Ext);
var TestApp = CombinePaths(SC.ProjectRoot, "Binaries", SC.PlatformDir, SC.ShortProjectName + "Server" + Ext);
string Game = "Game";
//@todo, this is sketchy, someone might ask what the exe is before it is compiled
if (!FileExists_NoExceptions(ClientApp) && !FileExists_NoExceptions(TestApp) && SC.ShortProjectName.EndsWith(Game, StringComparison.InvariantCultureIgnoreCase))
{
ExeName = SC.StageTargetPlatform.GetPlatformExecutableName(SC.ShortProjectName.Substring(0, SC.ShortProjectName.Length - Game.Length) + "Server");
ClientApp = CombinePaths(SC.RuntimeProjectRootDir, "Binaries", SC.PlatformDir, ExeName + Ext);
}
ExecutableNames.Add(ClientApp);
}
}
else
{
if (!SC.IsCodeBasedProject)
{
string ExeName = SC.StageTargetPlatform.GetPlatformExecutableName("UE4Game");
ExecutableNames.Add(CombinePaths(SC.RuntimeRootDir, "Engine/Binaries", SC.PlatformDir, ExeName + Ext));
}
else
{
string ExeName = SC.StageTargetPlatform.GetPlatformExecutableName(SC.ShortProjectName);
ExecutableNames.Add(CombinePaths(SC.RuntimeProjectRootDir, "Binaries", SC.PlatformDir, ExeName + Ext));
}
}
}
else
{
string ExeName = SC.StageTargetPlatform.GetPlatformExecutableName("UE4Editor");
ExecutableNames.Add(CombinePaths(SC.RuntimeRootDir, "Engine/Binaries", SC.PlatformDir, ExeName + Ext));
}
return ExecutableNames;
}
/// <summary>
/// Get the files to deploy, specific to this platform, typically binaries
/// </summary>
/// <param name="SC">Deployment Context</param>
public virtual void GetFilesToDeployOrStage(ProjectParams Params, DeploymentContext SC)
{
throw new AutomationException("{0} does not yet implement GetFilesToDeployOrStage.", PlatformType);
}
/// <summary>
/// Called after CopyUsingStagingManifest. Does anything platform specific that requires a final list of staged files.
/// e.g. PlayGo emulation control file generation for PS4.
/// </summary>
/// <param name="Params"></param>
/// <param name="SC"></param>
public virtual void PostStagingFileCopy(ProjectParams Params, DeploymentContext SC)
{
}
/// <summary>
/// Get the files to deploy, specific to this platform, typically binaries
/// </summary>
/// <param name="SC">Deployment Context</param>
public virtual void GetFilesToArchive(ProjectParams Params, DeploymentContext SC)
{
SC.ArchiveFiles(SC.StageDirectory);
}
/// <summary>
/// Gets cook platform name for this platform.
/// </summary>
/// <param name="bDedicatedServer">True if cooking for dedicated server</param>
/// <param name="bIsClientOnly">True if cooking for client only</param>
/// <param name="CookFlavor">Additional parameter used to indicate special sub-target platform</param>
/// <returns>Cook platform string.</returns>
public virtual string GetCookPlatform(bool bDedicatedServer, bool bIsClientOnly, string CookFlavor)
{
throw new AutomationException("{0} does not yet implement GetCookPlatform.", PlatformType);
}
/// <summary>
/// Gets extra cook commandline arguments for this platform.
/// </summary>
/// <param name="Params"> ProjectParams </param>
/// <returns>Cook platform string.</returns>
public virtual string GetCookExtraCommandLine(ProjectParams Params)
{
return "";
}
/// <summary>
/// Gets extra maps needed on this platform.
/// </summary>
/// <returns>extra maps</returns>
public virtual List<string> GetCookExtraMaps()
{
return new List<string>();
}
/// <summary>
/// Gets editor cook platform name for this platform. Cooking the editor is not useful, but this is used to fill the derived data cache
/// </summary>
/// <returns>Cook platform string.</returns>
public virtual string GetEditorCookPlatform()
{
return GetCookPlatform(false, false, "");
}
/// <summary>
/// return true if we need to change the case of filenames inside of pak files
/// </summary>
/// <returns></returns>
public virtual bool DeployPakInternalLowerCaseFilenames()
{
return false;
}
/// <summary>
/// return true if we need to change the case of filenames outside of pak files
/// </summary>
/// <returns></returns>
public virtual bool DeployLowerCaseFilenames(bool bUFSFile)
{
return false;
}
/// <summary>
/// Converts local path to target platform path.
/// </summary>
/// <param name="LocalPath">Local path.</param>
/// <param name="LocalRoot">Local root.</param>
/// <returns>Local path converted to device format path.</returns>
public virtual string LocalPathToTargetPath(string LocalPath, string LocalRoot)
{
return LocalPath;
}
/// <summary>
/// Returns a list of the compiler produced debug file extensions
/// </summary>
/// <returns>a list of the compiler produced debug file extensions</returns>
public virtual List<string> GetDebugFileExtentions()
{
return new List<string>();
}
/// <summary>
/// Remaps movie directory for platforms that need a remap
/// </summary>
public virtual bool StageMovies
{
get { return true; }
}
/// <summary>
/// UnrealTargetPlatform type for this platform.
/// </summary>
public UnrealTargetPlatform PlatformType
{
get { return TargetPlatformType; }
}
/// <summary>
/// True if this platform is supported.
/// </summary>
public virtual bool IsSupported
{
get { return false; }
}
/// <summary>
/// True if this platform requires UFE for deploying
/// </summary>
public virtual bool DeployViaUFE
{
get { return false; }
}
/// <summary>
/// True if this platform requires UFE for launching
/// </summary>
public virtual bool LaunchViaUFE
{
get { return false; }
}
/// <summary>
/// True if this platform can write to the abslog path that's on the host desktop.
/// </summary>
public virtual bool UseAbsLog
{
get { return true; }
}
/// <summary>
/// Remaps the given content directory to its final location
/// </summary>
public virtual string Remap(string Dest)
{
return Dest;
}
/// <summary>
/// Tri-state - The intent is to override command line parameters for pak if needed per platform.
/// </summary>
///
public enum PakType { Always, Never, DontCare };
public virtual PakType RequiresPak(ProjectParams Params)
{
return PakType.DontCare;
}
/// <summary>
/// Returns platform specific command line options for UnrealPak
/// </summary>
public virtual string GetPlatformPakCommandLine()
{
return "";
}
/// <summary>
/// Returns whether the platform requires a package to deploy to a device
/// </summary>
public virtual bool RequiresPackageToDeploy
{
get { return false; }
}
public virtual List<string> GetFilesForCRCCheck()
{
string CmdLine = "UE4CommandLine.txt";
if (DeployLowerCaseFilenames(true))
{
CmdLine = CmdLine.ToLowerInvariant();
}
return new List<string>() { CmdLine };
}
#region Hooks
public virtual void PreBuildAgenda(UE4Build Build, UE4Build.BuildAgenda Agenda)
{
}
public virtual void PostBuildTarget(UE4Build Build, string ProjectName, string UProjectPath, string Config)
{
}
/// <summary>
/// General purpose command to run generic string commands inside the platform interfeace
/// </summary>
/// <param name="Command"></param>
public virtual int RunCommand(string Command)
{
return 0;
}
public virtual bool ShouldUseManifestForUBTBuilds(string AddArgs)
{
return true;
}
/// <summary>
/// Determines whether we should stage a UE4CommandLine.txt for this platform
/// </summary>
public virtual bool ShouldStageCommandLine(ProjectParams Params, DeploymentContext SC)
{
return true;
}
/// <summary>
/// Only relevant for the mac and PC at the moment. Example calling the Mac platform with PS4 as an arg will return false. Can't compile or cook for the PS4 on the mac.
/// </summary>
public virtual bool CanHostPlatform(UnrealTargetPlatform Platform)
{
return false;
}
/// <summary>
/// Allows some platforms to not be compiled, for instance when BuildCookRun -build is performed
/// </summary>
/// <returns><c>true</c> if this instance can be compiled; otherwise, <c>false</c>.</returns>
public virtual bool CanBeCompiled()
{
return true;
}
public virtual bool RetrieveDeployedManifests(ProjectParams Params, DeploymentContext SC, out List<string> UFSManifests, out List<string> NonUFSManifests)
{
UFSManifests = null;
NonUFSManifests = null;
return false;
}
public virtual bool SignExecutables(DeploymentContext SC, ProjectParams Params)
{
return true;
}
public virtual UnrealTargetPlatform[] GetStagePlatforms()
{
return new UnrealTargetPlatform[] { PlatformType };
}
#endregion
#region Utilities
public static string GetExeExtension(UnrealTargetPlatform Target)
{
switch (Target)
{
case UnrealTargetPlatform.Win32:
case UnrealTargetPlatform.Win64:
case UnrealTargetPlatform.WinRT:
case UnrealTargetPlatform.WinRT_ARM:
case UnrealTargetPlatform.XboxOne:
return ".exe";
case UnrealTargetPlatform.PS4:
return ".self";
case UnrealTargetPlatform.IOS:
return ".stub";
case UnrealTargetPlatform.Linux:
return "";
case UnrealTargetPlatform.HTML5:
return ".js";
}
return String.Empty;
}
public static Dictionary<UnrealTargetPlatform, Platform> Platforms
{
get { return AllPlatforms; }
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements;
using Microsoft.VisualStudio.Text;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
{
internal interface ICodeModelService : ICodeModelNavigationPointService
{
/// <summary>
/// Retrieves the Option nodes (i.e. VB Option statements) parented
/// by the given node.
/// </summary>
IEnumerable<SyntaxNode> GetOptionNodes(SyntaxNode parent);
/// <summary>
/// Retrieves the import nodes (e.g. using/Import directives) parented
/// by the given node.
/// </summary>
IEnumerable<SyntaxNode> GetImportNodes(SyntaxNode parent);
/// <summary>
/// Retrieves the attributes parented or owned by the given node.
/// </summary>
IEnumerable<SyntaxNode> GetAttributeNodes(SyntaxNode parent);
/// <summary>
/// Retrieves the attribute arguments parented by the given node.
/// </summary>
IEnumerable<SyntaxNode> GetAttributeArgumentNodes(SyntaxNode parent);
/// <summary>
/// Retrieves the Inherits nodes (i.e. VB Inherits statements) parented
/// or owned by the given node.
/// </summary>
IEnumerable<SyntaxNode> GetInheritsNodes(SyntaxNode parent);
/// <summary>
/// Retrieves the Implements nodes (i.e. VB Implements statements) parented
/// or owned by the given node.
/// </summary>
IEnumerable<SyntaxNode> GetImplementsNodes(SyntaxNode parent);
/// <summary>
/// Retrieves the logical members of a given node, flattening the declarators
/// in field declarations. For example, if a class contains the field "int foo, bar",
/// two nodes are returned -- one for "foo" and one for "bar".
/// </summary>
IEnumerable<SyntaxNode> GetFlattenedMemberNodes(SyntaxNode parent);
SyntaxNodeKey GetNodeKey(SyntaxNode node);
SyntaxNodeKey TryGetNodeKey(SyntaxNode node);
SyntaxNode LookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree);
bool TryLookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree, out SyntaxNode node);
bool MatchesScope(SyntaxNode node, EnvDTE.vsCMElement scope);
string Language { get; }
string AssemblyAttributeString { get; }
EnvDTE.CodeElement CreateInternalCodeElement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node);
EnvDTE.CodeElement CreateExternalCodeElement(CodeModelState state, ProjectId projectId, ISymbol symbol);
EnvDTE.CodeElement CreateUnknownCodeElement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node);
EnvDTE.CodeElement CreateUnknownRootNamespaceCodeElement(CodeModelState state, FileCodeModel fileCodeModel);
EnvDTE.CodeElement CreateCodeType(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol);
/// <summary>
/// Used by RootCodeModel.CreateCodeTypeRef to create an EnvDTE.CodeTypeRef.
/// </summary>
EnvDTE.CodeTypeRef CreateCodeTypeRef(CodeModelState state, ProjectId projectId, object type);
EnvDTE.vsCMTypeRef GetTypeKindForCodeTypeRef(ITypeSymbol typeSymbol);
string GetAsFullNameForCodeTypeRef(ITypeSymbol typeSymbol);
string GetAsStringForCodeTypeRef(ITypeSymbol typeSymbol);
bool IsParameterNode(SyntaxNode node);
bool IsAttributeNode(SyntaxNode node);
bool IsAttributeArgumentNode(SyntaxNode node);
bool IsOptionNode(SyntaxNode node);
bool IsImportNode(SyntaxNode node);
ISymbol ResolveSymbol(Workspace workspace, ProjectId projectId, SymbolKey symbolId);
string GetUnescapedName(string name);
/// <summary>
/// Retrieves the value to be returned from the EnvDTE.CodeElement.Name property.
/// </summary>
string GetName(SyntaxNode node);
SyntaxNode GetNodeWithName(SyntaxNode node);
SyntaxNode SetName(SyntaxNode node, string name);
/// <summary>
/// Retrieves the value to be returned from the EnvDTE.CodeElement.FullName property.
/// </summary>
string GetFullName(SyntaxNode node, SemanticModel semanticModel);
/// <summary>
/// Retrieves the value to be returned from the EnvDTE.CodeElement.FullName property for external code elements
/// </summary>
string GetFullName(ISymbol symbol);
/// <summary>
/// Given a name, attempts to convert it to a fully qualified name.
/// </summary>
string GetFullyQualifiedName(string name, int position, SemanticModel semanticModel);
void Rename(ISymbol symbol, string newName, Solution solution);
SyntaxNode GetNodeWithModifiers(SyntaxNode node);
SyntaxNode GetNodeWithType(SyntaxNode node);
SyntaxNode GetNodeWithInitializer(SyntaxNode node);
EnvDTE.vsCMAccess GetAccess(ISymbol symbol);
EnvDTE.vsCMAccess GetAccess(SyntaxNode node);
SyntaxNode SetAccess(SyntaxNode node, EnvDTE.vsCMAccess access);
EnvDTE.vsCMElement GetElementKind(SyntaxNode node);
bool IsAccessorNode(SyntaxNode node);
MethodKind GetAccessorKind(SyntaxNode node);
bool TryGetAccessorNode(SyntaxNode parentNode, MethodKind kind, out SyntaxNode accessorNode);
bool TryGetParameterNode(SyntaxNode parentNode, string name, out SyntaxNode parameterNode);
bool TryGetImportNode(SyntaxNode parentNode, string dottedName, out SyntaxNode importNode);
bool TryGetOptionNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode optionNode);
bool TryGetInheritsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode inheritsNode);
bool TryGetImplementsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode implementsNode);
bool TryGetAttributeNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode attributeNode);
bool TryGetAttributeArgumentNode(SyntaxNode attributeNode, int index, out SyntaxNode attributeArgumentNode);
void GetOptionNameAndOrdinal(SyntaxNode parentNode, SyntaxNode optionNode, out string name, out int ordinal);
void GetInheritsNamespaceAndOrdinal(SyntaxNode parentNode, SyntaxNode inheritsNode, out string namespaceName, out int ordinal);
void GetImplementsNamespaceAndOrdinal(SyntaxNode parentNode, SyntaxNode implementsNode, out string namespaceName, out int ordinal);
void GetAttributeArgumentParentAndIndex(SyntaxNode attributeArgumentNode, out SyntaxNode attributeNode, out int index);
void GetAttributeNameAndOrdinal(SyntaxNode parentNode, SyntaxNode attributeNode, out string name, out int ordinal);
SyntaxNode GetAttributeTargetNode(SyntaxNode attributeNode);
string GetAttributeTarget(SyntaxNode attributeNode);
string GetAttributeValue(SyntaxNode attributeNode);
SyntaxNode SetAttributeTarget(SyntaxNode attributeNode, string value);
SyntaxNode SetAttributeValue(SyntaxNode attributeNode, string value);
/// <summary>
/// Given a node, finds the related node that holds on to the attribute information.
/// Generally, this will be an ancestor node. For example, given a C# VariableDeclarator,
/// looks up the syntax tree to find the FieldDeclaration.
/// </summary>
SyntaxNode GetNodeWithAttributes(SyntaxNode node);
/// <summary>
/// Given node for an attribute, returns a node that can represent the parent.
/// For example, an attribute on a C# field cannot use the FieldDeclaration (as it is
/// not keyed) but instead must use one of the FieldDeclaration's VariableDeclarators.
/// </summary>
SyntaxNode GetEffectiveParentForAttribute(SyntaxNode node);
SyntaxNode CreateAttributeNode(string name, string value, string target = null);
SyntaxNode CreateAttributeArgumentNode(string name, string value);
SyntaxNode CreateImportNode(string name, string alias = null);
SyntaxNode CreateParameterNode(string name, string type);
string GetAttributeArgumentValue(SyntaxNode attributeArgumentNode);
string GetImportAlias(SyntaxNode node);
string GetImportNamespaceOrType(SyntaxNode node);
string GetParameterName(SyntaxNode node);
EnvDTE80.vsCMParameterKind GetParameterKind(SyntaxNode node);
SyntaxNode SetParameterKind(SyntaxNode node, EnvDTE80.vsCMParameterKind kind);
EnvDTE.vsCMFunction ValidateFunctionKind(SyntaxNode containerNode, EnvDTE.vsCMFunction kind, string name);
bool SupportsEventThrower { get; }
bool GetCanOverride(SyntaxNode memberNode);
SyntaxNode SetCanOverride(SyntaxNode memberNode, bool value);
EnvDTE80.vsCMClassKind GetClassKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol);
SyntaxNode SetClassKind(SyntaxNode typeNode, EnvDTE80.vsCMClassKind kind);
string GetComment(SyntaxNode node);
SyntaxNode SetComment(SyntaxNode node, string value);
EnvDTE80.vsCMConstKind GetConstKind(SyntaxNode variableNode);
SyntaxNode SetConstKind(SyntaxNode variableNode, EnvDTE80.vsCMConstKind kind);
EnvDTE80.vsCMDataTypeKind GetDataTypeKind(SyntaxNode typeNode, INamedTypeSymbol symbol);
SyntaxNode SetDataTypeKind(SyntaxNode typeNode, EnvDTE80.vsCMDataTypeKind kind);
string GetDocComment(SyntaxNode node);
SyntaxNode SetDocComment(SyntaxNode node, string value);
EnvDTE80.vsCMInheritanceKind GetInheritanceKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol);
SyntaxNode SetInheritanceKind(SyntaxNode node, EnvDTE80.vsCMInheritanceKind kind);
bool GetIsAbstract(SyntaxNode memberNode, ISymbol symbol);
SyntaxNode SetIsAbstract(SyntaxNode memberNode, bool value);
bool GetIsConstant(SyntaxNode memberNode);
SyntaxNode SetIsConstant(SyntaxNode memberNode, bool value);
bool GetIsDefault(SyntaxNode propertyNode);
SyntaxNode SetIsDefault(SyntaxNode propertyNode, bool value);
bool GetIsGeneric(SyntaxNode memberNode);
bool GetIsPropertyStyleEvent(SyntaxNode eventNode);
bool GetIsShared(SyntaxNode memberNode, ISymbol symbol);
SyntaxNode SetIsShared(SyntaxNode memberNode, bool value);
bool GetMustImplement(SyntaxNode memberNode);
SyntaxNode SetMustImplement(SyntaxNode memberNode, bool value);
EnvDTE80.vsCMOverrideKind GetOverrideKind(SyntaxNode memberNode);
SyntaxNode SetOverrideKind(SyntaxNode memberNode, EnvDTE80.vsCMOverrideKind kind);
EnvDTE80.vsCMPropertyKind GetReadWrite(SyntaxNode memberNode);
SyntaxNode SetType(SyntaxNode node, ITypeSymbol typeSymbol);
Document Delete(Document document, SyntaxNode node);
string GetMethodXml(SyntaxNode node, SemanticModel semanticModel);
string GetInitExpression(SyntaxNode node);
SyntaxNode AddInitExpression(SyntaxNode node, string value);
CodeGenerationDestination GetDestination(SyntaxNode containerNode);
/// <summary>
/// Retrieves the Accessibility for an EnvDTE.vsCMAccess. If the specified value is
/// EnvDTE.vsCMAccess.vsCMAccessDefault, then the SymbolKind and CodeGenerationDestination hints
/// will be used to retrieve the correct Accessibility for the current language.
/// </summary>
Accessibility GetAccessibility(EnvDTE.vsCMAccess access, SymbolKind targetSymbolKind, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified);
bool GetWithEvents(EnvDTE.vsCMAccess access);
/// <summary>
/// Given an "type" argument received from a CodeModel client, converts it to an ITypeSymbol. Note that
/// this parameter is a VARIANT and could be an EnvDTE.vsCMTypeRef, a string representing a fully-qualified
/// type name, or an EnvDTE.CodeTypeRef.
/// </summary>
ITypeSymbol GetTypeSymbol(object type, SemanticModel semanticModel, int position);
ITypeSymbol GetTypeSymbolFromFullName(string fullName, Compilation compilation);
SyntaxNode CreateReturnDefaultValueStatement(ITypeSymbol type);
int PositionVariantToAttributeInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel);
int PositionVariantToMemberInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel);
int PositionVariantToAttributeArgumentInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel);
int PositionVariantToImportInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel);
int PositionVariantToParameterInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel);
SyntaxNode InsertAttribute(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode attributeNode,
CancellationToken cancellationToken,
out Document newDocument);
SyntaxNode InsertAttributeArgument(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode attributeArgumentNode,
CancellationToken cancellationToken,
out Document newDocument);
SyntaxNode InsertImport(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode importNode,
CancellationToken cancellationToken,
out Document newDocument);
SyntaxNode InsertMember(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode newMemberNode,
CancellationToken cancellationToken,
out Document newDocument);
SyntaxNode InsertParameter(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode parameterNode,
CancellationToken cancellationToken,
out Document newDocument);
Document UpdateNode(
Document document,
SyntaxNode node,
SyntaxNode newNode,
CancellationToken cancellationToken);
Queue<CodeModelEvent> CollectCodeModelEvents(SyntaxTree oldTree, SyntaxTree newTree);
bool IsNamespace(SyntaxNode node);
bool IsType(SyntaxNode node);
IList<string> GetHandledEventNames(SyntaxNode method, SemanticModel semanticModel);
bool HandlesEvent(string eventName, SyntaxNode method, SemanticModel semanticModel);
Document AddHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken);
Document RemoveHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken);
string[] GetFunctionExtenderNames();
object GetFunctionExtender(string name, SyntaxNode node, ISymbol symbol);
string[] GetPropertyExtenderNames();
object GetPropertyExtender(string name, SyntaxNode node, ISymbol symbol);
string[] GetExternalTypeExtenderNames();
object GetExternalTypeExtender(string name, string externalLocation);
string[] GetTypeExtenderNames();
object GetTypeExtender(string name, AbstractCodeType codeType);
bool IsValidBaseType(SyntaxNode node, ITypeSymbol typeSymbol);
SyntaxNode AddBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position);
SyntaxNode RemoveBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel);
bool IsValidInterfaceType(SyntaxNode node, ITypeSymbol typeSymbol);
SyntaxNode AddImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position);
SyntaxNode RemoveImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel);
string GetPrototype(SyntaxNode node, ISymbol symbol, PrototypeFlags flags);
void AttachFormatTrackingToBuffer(ITextBuffer buffer);
void DetachFormatTrackingToBuffer(ITextBuffer buffer);
void EnsureBufferFormatted(ITextBuffer buffer);
}
}
| |
/***************************************************************************************************************************************
* Copyright (C) 2001-2012 LearnLift USA *
* Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com *
* *
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License *
* as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty *
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, *
* write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************************************************************************/
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using MLifter.Controls.Properties;
using MLifter.Components;
using MLifter.BusinessLayer;
namespace MLifter.Controls
{
/// <summary>
/// This frame is used in various parts of the program. It gives the user the
/// possibility to select given fieldIDs.
/// </summary>
/// <remarks>Documented by Dev04, 2007-07-20</remarks>
public class FieldsFrame : System.Windows.Forms.UserControl
{
private System.Windows.Forms.Button SBAdd;
private System.Windows.Forms.Button SBAddAll;
private System.Windows.Forms.Button SBDel;
private IContainer components;
public int[] Order = new int[0];
public string[] StrOrder;
private int maxKey;
public const int FIELDSELEMENTS = 15;
private ImageList TangoCollection16;
private ImageList OldButtonCollection16;
private DragNDrop.DragAndDropListView LBFields;
private DragNDrop.DragAndDropListView LBSelFields;
private ToolTip ToolTipControl;
private Button SBDelAll;
private ColumnHeader columnHeader2;
private ColumnHeader columnHeader1;
public string[] FullStr = new string[FIELDSELEMENTS];
public delegate void FieldEventHandler(object sender);
public event FieldEventHandler OnUpdate;
/// <summary>
/// Constructor of FieldsForm
/// </summary>
/// <remarks>Documented by Dev04, 2007-07-20</remarks>
public FieldsFrame()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// TODO: Add any initialization after the InitializeComponent call
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <remarks>Documented by Dev04, 2007-07-20</remarks>
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()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FieldsFrame));
this.SBAdd = new System.Windows.Forms.Button();
this.TangoCollection16 = new System.Windows.Forms.ImageList(this.components);
this.SBAddAll = new System.Windows.Forms.Button();
this.SBDel = new System.Windows.Forms.Button();
this.OldButtonCollection16 = new System.Windows.Forms.ImageList(this.components);
this.ToolTipControl = new System.Windows.Forms.ToolTip(this.components);
this.SBDelAll = new System.Windows.Forms.Button();
this.LBSelFields = new DragNDrop.DragAndDropListView();
this.columnHeader2 = new System.Windows.Forms.ColumnHeader();
this.LBFields = new DragNDrop.DragAndDropListView();
this.columnHeader1 = new System.Windows.Forms.ColumnHeader();
this.SuspendLayout();
//
// SBAdd
//
resources.ApplyResources(this.SBAdd, "SBAdd");
this.SBAdd.ImageList = this.TangoCollection16;
this.SBAdd.Name = "SBAdd";
this.SBAdd.Click += new System.EventHandler(this.SBAdd_Click);
//
// TangoCollection16
//
this.TangoCollection16.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("TangoCollection16.ImageStream")));
this.TangoCollection16.TransparentColor = System.Drawing.Color.Transparent;
this.TangoCollection16.Images.SetKeyName(0, "go-next.png");
this.TangoCollection16.Images.SetKeyName(1, "go-last.png");
this.TangoCollection16.Images.SetKeyName(2, "go-previous.png");
this.TangoCollection16.Images.SetKeyName(3, "go-first.png");
//
// SBAddAll
//
resources.ApplyResources(this.SBAddAll, "SBAddAll");
this.SBAddAll.ImageList = this.TangoCollection16;
this.SBAddAll.Name = "SBAddAll";
this.SBAddAll.Click += new System.EventHandler(this.SBAddAll_Click);
//
// SBDel
//
resources.ApplyResources(this.SBDel, "SBDel");
this.SBDel.ImageList = this.TangoCollection16;
this.SBDel.Name = "SBDel";
this.SBDel.Click += new System.EventHandler(this.SBDel_Click);
//
// OldButtonCollection16
//
this.OldButtonCollection16.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("OldButtonCollection16.ImageStream")));
this.OldButtonCollection16.TransparentColor = System.Drawing.Color.Transparent;
this.OldButtonCollection16.Images.SetKeyName(0, "");
this.OldButtonCollection16.Images.SetKeyName(1, "");
this.OldButtonCollection16.Images.SetKeyName(2, "");
this.OldButtonCollection16.Images.SetKeyName(3, "delete2.gif");
//
// SBDelAll
//
resources.ApplyResources(this.SBDelAll, "SBDelAll");
this.SBDelAll.ImageList = this.TangoCollection16;
this.SBDelAll.Name = "SBDelAll";
this.SBDelAll.Click += new System.EventHandler(this.SBDelAll_Click);
//
// LBSelFields
//
this.LBSelFields.AllowDrop = true;
this.LBSelFields.AllowReorder = true;
this.LBSelFields.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader2});
this.LBSelFields.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None;
this.LBSelFields.LineColor = System.Drawing.Color.YellowGreen;
resources.ApplyResources(this.LBSelFields, "LBSelFields");
this.LBSelFields.Name = "LBSelFields";
this.LBSelFields.TileSize = new System.Drawing.Size(156, 16);
this.LBSelFields.UseCompatibleStateImageBehavior = false;
this.LBSelFields.View = System.Windows.Forms.View.Details;
this.LBSelFields.DoubleClick += new System.EventHandler(this.LBSelFields_DoubleClick);
this.LBSelFields.DragDrop += new System.Windows.Forms.DragEventHandler(this.ListView_DragDrop);
this.LBSelFields.MouseMove += new System.Windows.Forms.MouseEventHandler(this.ListItem_MouseMove);
this.LBSelFields.KeyDown += new System.Windows.Forms.KeyEventHandler(this.LBSelFields_KeyDown);
//
// columnHeader2
//
resources.ApplyResources(this.columnHeader2, "columnHeader2");
//
// LBFields
//
this.LBFields.AllowDrop = true;
this.LBFields.AllowReorder = true;
this.LBFields.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1});
this.LBFields.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None;
this.LBFields.Items.AddRange(new System.Windows.Forms.ListViewItem[] {
((System.Windows.Forms.ListViewItem)(resources.GetObject("LBFields.Items"))),
((System.Windows.Forms.ListViewItem)(resources.GetObject("LBFields.Items1"))),
((System.Windows.Forms.ListViewItem)(resources.GetObject("LBFields.Items2"))),
((System.Windows.Forms.ListViewItem)(resources.GetObject("LBFields.Items3")))});
this.LBFields.LineColor = System.Drawing.Color.YellowGreen;
resources.ApplyResources(this.LBFields, "LBFields");
this.LBFields.Name = "LBFields";
this.LBFields.TileSize = new System.Drawing.Size(156, 16);
this.LBFields.UseCompatibleStateImageBehavior = false;
this.LBFields.View = System.Windows.Forms.View.Details;
this.LBFields.DoubleClick += new System.EventHandler(this.LBFields_DoubleClick);
this.LBFields.DragDrop += new System.Windows.Forms.DragEventHandler(this.ListView_DragDrop);
this.LBFields.MouseMove += new System.Windows.Forms.MouseEventHandler(this.ListItem_MouseMove);
this.LBFields.KeyDown += new System.Windows.Forms.KeyEventHandler(this.LBFields_KeyDown);
//
// columnHeader1
//
resources.ApplyResources(this.columnHeader1, "columnHeader1");
//
// FieldsFrame
//
this.Controls.Add(this.LBSelFields);
this.Controls.Add(this.LBFields);
this.Controls.Add(this.SBDelAll);
this.Controls.Add(this.SBDel);
this.Controls.Add(this.SBAddAll);
this.Controls.Add(this.SBAdd);
this.Name = "FieldsFrame";
resources.ApplyResources(this, "$this");
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// Add: move from LBFields to LBSelFields
/// </summary>
/// <param name="e">not used</param>
/// <param name="sender">not used</param>
/// <remarks>Documented by Dev04, 2007-07-20</remarks>
private void SBAdd_Click(object sender, System.EventArgs e)
{
for (int i = 0; i <= maxKey; i++)
if (LBFields.SelectedItems.ContainsKey(Convert.ToString(i)))
{
ListViewItem item = LBFields.Items[Convert.ToString(i)];
LBFields.Items[Convert.ToString(i)].Remove();
LBSelFields.Items.Add(item);
}
CalcOrder();
LBFields.SelectedIndices.Clear();
LBSelFields.SelectedIndices.Clear();
}
/// <summary>
/// Select all fieldIDs, then add them (with SBAdd_Click)
/// </summary>
/// <param name="e">used for starting SBAdd_Click event</param>
/// <param name="sender">used for starting SBAdd_Click event</param>
/// <remarks>Documented by Dev04, 2007-07-20</remarks>
private void SBAddAll_Click(object sender, System.EventArgs e)
{
// Select all fieldIDs, then add them
for (int i = 0; i < LBFields.Items.Count; i++)
LBFields.SelectedIndices.Add(i);
SBAdd_Click(sender, e);
}
/// <summary>
/// Remove: move from LBSelFields to LBFields
/// </summary>
/// <param name="e">not used</param>
/// <param name="sender">not used</param>
/// <remarks>Documented by Dev04, 2007-07-20</remarks>
private void SBDel_Click(object sender, System.EventArgs e)
{
for (int i = 0; i <= maxKey; i++)
if (LBSelFields.SelectedItems.ContainsKey(Convert.ToString(i)))
{
ListViewItem item = LBSelFields.Items[Convert.ToString(i)];
LBSelFields.Items[Convert.ToString(i)].Remove();
LBFields.Items.Add(item);
}
CalcOrder();
LBFields.SelectedIndices.Clear();
LBSelFields.SelectedIndices.Clear();
}
/// <summary>
/// Select all fieldIDs, then remove them (with SBDel_Click)
/// </summary>
/// <param name="e">used for starting SBDel_Click event</param>
/// <param name="sender">used for starting SBDel_Click event</param>
/// <remarks>Documented by Dev04, 2007-07-20</remarks>
private void SBDelAll_Click(object sender, EventArgs e)
{
for (int i = 0; i < LBSelFields.Items.Count; i++)
LBSelFields.SelectedIndices.Add(i);
SBDel_Click(sender, e);
}
/// <summary>
/// Deletes double-clicked field from LBSelFields
/// </summary>
/// <param name="e">used for starting SBDel_Click event</param>
/// <param name="sender">used for starting SBDel_Click event</param>
/// <remarks>Documented by Dev04, 2007-07-20</remarks>
private void LBSelFields_DoubleClick(object sender, System.EventArgs e)
{
SBDel_Click(sender, e);
}
/// <summary>
/// Adds double-clicked field to LBSelFields
/// </summary>
/// <param name="e">used for starting SBAdd_Click event</param>
/// <param name="sender">used for starting SBAdd_Click event</param>
/// <remarks>Documented by Dev04, 2007-07-20</remarks>
private void LBFields_DoubleClick(object sender, System.EventArgs e)
{
SBAdd_Click(sender, e);
}
/// <summary>
/// If the "right" key is pressed on the keyboard and the focus is on LBFields,
/// it moves the selected item to LBSelFields.
/// </summary>
/// <param name="e">not used</param>
/// <param name="sender">used for starting SBAdd_Click event</param>
/// <remarks>Documented by Dev04, 2007-07-20</remarks>
private void LBFields_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == Keys.Right)
SBAdd_Click(sender, null);
}
/// <summary>
/// If the "left" key or the "delete" key is pressed on the keyboard and the focus is on LBSelFields,
/// it moves the selected item to LBFields.
/// </summary>
/// <param name="e">not used</param>
/// <param name="sender">used for starting SBDel_Click event</param>
/// <remarks>Documented by Dev04, 2007-07-20</remarks>
private void LBSelFields_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete || e.KeyCode == Keys.Left)
SBDel_Click(sender, null);
}
/// <summary>
/// Prepares the form to have the Questions and Answers by default
/// on the right side e.g. for the export.
/// No Unit Test necessary.
/// </summary>
/// <remarks>Documented by Dev04, 2007-07-20</remarks>
public void Prepare(Dictionary dictionary)
{
this.setToolTips();
string question_caption = dictionary.QuestionCaption;
string answer_caption = dictionary.AnswerCaption;
// Add the available fieldIDs to the left side }
LBFields.Items.Clear();
LBFields.SetLockCode("field");
LBSelFields.Items.Clear();
LBSelFields.SetLockCode("field");
// Set standard field as selected
FullStr[0] = String.Format(Resources.LISTBOXFIELDS_QUESTION_TEXT, question_caption);
LBSelFields.Items.Add("0", FullStr[0], 0);
FullStr[1] = String.Format(Resources.LISTBOXFIELDS_ANSWER_TEXT, answer_caption);
LBSelFields.Items.Add("1", FullStr[1], 0);
FullStr[2] = String.Format(Resources.LISTBOXFIELDS_EXQUESTION_TEXT, question_caption);
LBFields.Items.Add("2", FullStr[2], 0);
FullStr[3] = String.Format(Resources.LISTBOXFIELDS_EXANSWER_TEXT, answer_caption);
LBFields.Items.Add("3", FullStr[3], 0);
FullStr[4] = String.Format(Resources.LISTBOXFIELDS_QUESTION_DISTRACTORS_TEXT, question_caption);
LBFields.Items.Add("4", FullStr[4], 0);
FullStr[5] = String.Format(Resources.LISTBOXFIELDS_ANSWER_DISTRACTORS_TEXT, answer_caption);
LBFields.Items.Add("5", FullStr[5], 0);
maxKey = 5; // highest key when adding
CalcOrder();
}
/// <summary>
/// Prepares the form to have the Media-File-Options on the left side.
/// No Unit Test necessary.
/// </summary>
/// <remarks>Documented by Dev04, 2007-07-20</remarks>
public void PrepareImage(Dictionary dictionary)
{
Prepare(dictionary);
string question_caption = dictionary.QuestionCaption;
string answer_caption = dictionary.AnswerCaption;
// Add sound and images
FullStr[6] = String.Format(Resources.LISTBOXFIELDS_SOUND_QUESTION_TEXT, question_caption);
LBFields.Items.Add("6", FullStr[6], 0);
FullStr[7] = String.Format(Resources.LISTBOXFIELDS_SOUND_ANSWER_TEXT, answer_caption);
LBFields.Items.Add("7", FullStr[7], 0);
FullStr[8] = String.Format(Resources.LISTBOXFIELDS_SOUND_EXQUESTION_TEXT, question_caption);
LBFields.Items.Add("8", FullStr[8], 0);
FullStr[9] = String.Format(Resources.LISTBOXFIELDS_SOUND_EXANSWER_TEXT, answer_caption);
LBFields.Items.Add("9", FullStr[9], 0);
FullStr[10] = String.Format(Resources.LISTBOXFIELDS_VIDEO_QUESTION_TEXT, question_caption);
LBFields.Items.Add("10", FullStr[10], 0);
FullStr[11] = String.Format(Resources.LISTBOXFIELDS_VIDEO_ANSWER_TEXT, answer_caption);
LBFields.Items.Add("11", FullStr[11], 0);
FullStr[12] = String.Format(Resources.LISTBOXFIELDS_IMAGE_QUESTION_TEXT, question_caption);
LBFields.Items.Add("12", FullStr[12], 0);
FullStr[13] = String.Format(Resources.LISTBOXFIELDS_IMAGE_ANSWER_TEXT, answer_caption);
LBFields.Items.Add("13", FullStr[13], 0);
maxKey = 13; // highest key when adding
}
/// <summary>
/// Prepares the form to contain the Chapter-field.
/// </summary>
/// <param name="dictionary">The dictionary.</param>
/// <remarks>Documented by Dev02, 2008-01-24</remarks>
public void PrepareChapter(Dictionary dictionary)
{
PrepareImage(dictionary);
//Add chapter
LBFields.Items.Add("14", Resources.LISTBOXFIELDS_CHAPTER, 0);
maxKey = 14; // highest key when adding
}
/// <summary>
/// Gets a value indicating whether the current field selection [contains Media files].
/// </summary>
/// <value><c>true</c> if [contains Media]; otherwise, <c>false</c>.</value>
/// <remarks>Documented by Dev02, 2008-02-12</remarks>
public bool ContainsMedia
{
get
{
bool containsMedia = false;
foreach (string field in StrOrder)
{
for (int i = 6; i <= 13; i++)
if (FullStr[i] == field)
containsMedia = true;
}
return containsMedia;
}
}
/// <summary>
/// Based on the fieldIDs, calculate the Order array
/// No Unit Test necessary.
/// </summary>
/// <remarks>Documented by Dev04, 2007-07-20</remarks>
private void CalcOrder()
{
Order = new int[FIELDSELEMENTS];
int h = LBSelFields.Items.Count;
StrOrder = new string[h];
for (int i = 0; i < LBSelFields.Items.Count; i++)
{
Order[i] = Convert.ToInt32(LBSelFields.Items[i].Name);
StrOrder[i] = LBSelFields.Items[i].Text;
}
if (OnUpdate != null)
OnUpdate(this);
}
/// <summary>
/// Sets Tool Tips for the controls.
/// No Unit Test necessary.
/// </summary>
/// <remarks>Documented by Dev04, 2007-07-20</remarks>
private void setToolTips()
{
ToolTipControl.SetToolTip(SBAdd, Resources.TOOLTIP_FRMFIELDS_ADD);
ToolTipControl.SetToolTip(SBAddAll, Resources.TOOLTIP_FRMFIELDS_ADDALL);
ToolTipControl.SetToolTip(SBDel, Resources.TOOLTIP_FRMFIELDS_DELETE);
ToolTipControl.SetToolTip(SBDelAll, Resources.TOOLTIP_FRMFIELDS_DELETEALL);
ToolTipControl.SetToolTip(LBSelFields, Resources.TOOLTIP_FRMFIELDS_LISTBOXSELFIELDS);
ToolTipControl.SetToolTip(LBFields, Resources.TOOLTIP_FRMFIELDS_LISTBOXFIELDS);
}
/// <summary>
/// Display arrayList hint, showing the full field title.
/// </summary>
/// <remarks>Documented by Dev04, 2007-07-20</remarks>
private void ListItem_MouseMove(object sender, MouseEventArgs e)
{
ListViewItem current = (sender as DragNDrop.DragAndDropListView).GetItemAt(e.X, e.Y);
if (current != null)
ToolTipControl.SetToolTip((sender as DragNDrop.DragAndDropListView), current.Text);
else
ToolTipControl.SetToolTip((sender as DragNDrop.DragAndDropListView), "");
}
/// <summary>
/// Recalculates the order after drag+drop of an item.
/// </summary>
/// <remarks>Documented by Dev04, 2007-07-20</remarks>
private void ListView_DragDrop(object sender, DragEventArgs e)
{
CalcOrder();
}
}
}
| |
// 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.Data.SqlTypes;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Transactions;
namespace System.Data.Common
{
internal static partial class ADP
{
// The class ADP defines the exceptions that are specific to the Adapters.
// The class contains functions that take the proper informational variables and then construct
// the appropriate exception with an error string obtained from the resource framework.
// The exception is then returned to the caller, so that the caller may then throw from its
// location so that the catcher of the exception will have the appropriate call stack.
// This class is used so that there will be compile time checking of error messages.
internal static Exception ExceptionWithStackTrace(Exception e)
{
try
{
throw e;
}
catch (Exception caught)
{
return caught;
}
}
//
// COM+ exceptions
//
internal static IndexOutOfRangeException IndexOutOfRange(int value)
{
IndexOutOfRangeException e = new IndexOutOfRangeException(value.ToString(CultureInfo.InvariantCulture));
return e;
}
internal static IndexOutOfRangeException IndexOutOfRange()
{
IndexOutOfRangeException e = new IndexOutOfRangeException();
return e;
}
internal static TimeoutException TimeoutException(string error)
{
TimeoutException e = new TimeoutException(error);
return e;
}
internal static InvalidOperationException InvalidOperation(string error, Exception inner)
{
InvalidOperationException e = new InvalidOperationException(error, inner);
return e;
}
internal static OverflowException Overflow(string error)
{
return Overflow(error, null);
}
internal static OverflowException Overflow(string error, Exception inner)
{
OverflowException e = new OverflowException(error, inner);
return e;
}
internal static TypeLoadException TypeLoad(string error)
{
TypeLoadException e = new TypeLoadException(error);
TraceExceptionAsReturnValue(e);
return e;
}
internal static PlatformNotSupportedException DbTypeNotSupported(string dbType)
{
PlatformNotSupportedException e = new PlatformNotSupportedException(SR.GetString(SR.SQL_DbTypeNotSupportedOnThisPlatform, dbType));
return e;
}
internal static InvalidCastException InvalidCast()
{
InvalidCastException e = new InvalidCastException();
return e;
}
internal static IOException IO(string error)
{
IOException e = new IOException(error);
return e;
}
internal static IOException IO(string error, Exception inner)
{
IOException e = new IOException(error, inner);
return e;
}
internal static ObjectDisposedException ObjectDisposed(object instance)
{
ObjectDisposedException e = new ObjectDisposedException(instance.GetType().Name);
return e;
}
internal static Exception DataTableDoesNotExist(string collectionName)
{
return Argument(SR.GetString(SR.MDF_DataTableDoesNotExist, collectionName));
}
internal static InvalidOperationException MethodCalledTwice(string method)
{
InvalidOperationException e = new InvalidOperationException(SR.GetString(SR.ADP_CalledTwice, method));
return e;
}
// IDbCommand.CommandType
internal static ArgumentOutOfRangeException InvalidCommandType(CommandType value)
{
#if DEBUG
switch (value)
{
case CommandType.Text:
case CommandType.StoredProcedure:
case CommandType.TableDirect:
Debug.Fail("valid CommandType " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(CommandType), (int)value);
}
// IDbConnection.BeginTransaction, OleDbTransaction.Begin
internal static ArgumentOutOfRangeException InvalidIsolationLevel(IsolationLevel value)
{
#if DEBUG
switch (value)
{
case IsolationLevel.Unspecified:
case IsolationLevel.Chaos:
case IsolationLevel.ReadUncommitted:
case IsolationLevel.ReadCommitted:
case IsolationLevel.RepeatableRead:
case IsolationLevel.Serializable:
case IsolationLevel.Snapshot:
Debug.Fail("valid IsolationLevel " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(IsolationLevel), (int)value);
}
// IDataParameter.Direction
internal static ArgumentOutOfRangeException InvalidParameterDirection(ParameterDirection value)
{
#if DEBUG
switch (value)
{
case ParameterDirection.Input:
case ParameterDirection.Output:
case ParameterDirection.InputOutput:
case ParameterDirection.ReturnValue:
Debug.Fail("valid ParameterDirection " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(ParameterDirection), (int)value);
}
internal static Exception TooManyRestrictions(string collectionName)
{
return Argument(SR.GetString(SR.MDF_TooManyRestrictions, collectionName));
}
// IDbCommand.UpdateRowSource
internal static ArgumentOutOfRangeException InvalidUpdateRowSource(UpdateRowSource value)
{
#if DEBUG
switch (value)
{
case UpdateRowSource.None:
case UpdateRowSource.OutputParameters:
case UpdateRowSource.FirstReturnedRecord:
case UpdateRowSource.Both:
Debug.Fail("valid UpdateRowSource " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(UpdateRowSource), (int)value);
}
//
// DbConnectionOptions, DataAccess
//
internal static ArgumentException InvalidMinMaxPoolSizeValues()
{
return ADP.Argument(SR.GetString(SR.ADP_InvalidMinMaxPoolSizeValues));
}
//
// DbConnection
//
internal static InvalidOperationException NoConnectionString()
{
return InvalidOperation(SR.GetString(SR.ADP_NoConnectionString));
}
internal static Exception MethodNotImplemented([CallerMemberName] string methodName = "")
{
return NotImplemented.ByDesignWithMessage(methodName);
}
internal static Exception QueryFailed(string collectionName, Exception e)
{
return InvalidOperation(SR.GetString(SR.MDF_QueryFailed, collectionName), e);
}
//
// : DbConnectionOptions, DataAccess, SqlClient
//
internal static Exception InvalidConnectionOptionValueLength(string key, int limit)
{
return Argument(SR.GetString(SR.ADP_InvalidConnectionOptionValueLength, key, limit));
}
internal static Exception MissingConnectionOptionValue(string key, string requiredAdditionalKey)
{
return Argument(SR.GetString(SR.ADP_MissingConnectionOptionValue, key, requiredAdditionalKey));
}
//
// DbConnectionPool and related
//
internal static Exception PooledOpenTimeout()
{
return ADP.InvalidOperation(SR.GetString(SR.ADP_PooledOpenTimeout));
}
internal static Exception NonPooledOpenTimeout()
{
return ADP.TimeoutException(SR.GetString(SR.ADP_NonPooledOpenTimeout));
}
//
// DbProviderException
//
internal static InvalidOperationException TransactionConnectionMismatch()
{
return Provider(SR.GetString(SR.ADP_TransactionConnectionMismatch));
}
internal static InvalidOperationException TransactionRequired(string method)
{
return Provider(SR.GetString(SR.ADP_TransactionRequired, method));
}
internal static Exception CommandTextRequired(string method)
{
return InvalidOperation(SR.GetString(SR.ADP_CommandTextRequired, method));
}
internal static Exception NoColumns()
{
return Argument(SR.GetString(SR.MDF_NoColumns));
}
internal static InvalidOperationException ConnectionRequired(string method)
{
return InvalidOperation(SR.GetString(SR.ADP_ConnectionRequired, method));
}
internal static InvalidOperationException OpenConnectionRequired(string method, ConnectionState state)
{
return InvalidOperation(SR.GetString(SR.ADP_OpenConnectionRequired, method, ADP.ConnectionStateMsg(state)));
}
internal static Exception OpenReaderExists()
{
return OpenReaderExists(null);
}
internal static Exception OpenReaderExists(Exception e)
{
return InvalidOperation(SR.GetString(SR.ADP_OpenReaderExists), e);
}
//
// DbDataReader
//
internal static Exception NonSeqByteAccess(long badIndex, long currIndex, string method)
{
return InvalidOperation(SR.GetString(SR.ADP_NonSeqByteAccess, badIndex.ToString(CultureInfo.InvariantCulture), currIndex.ToString(CultureInfo.InvariantCulture), method));
}
internal static Exception InvalidXml()
{
return Argument(SR.GetString(SR.MDF_InvalidXml));
}
internal static Exception NegativeParameter(string parameterName)
{
return InvalidOperation(SR.GetString(SR.ADP_NegativeParameter, parameterName));
}
internal static Exception InvalidXmlMissingColumn(string collectionName, string columnName)
{
return Argument(SR.GetString(SR.MDF_InvalidXmlMissingColumn, collectionName, columnName));
}
//
// SqlMetaData, SqlTypes, SqlClient
//
internal static Exception InvalidMetaDataValue()
{
return ADP.Argument(SR.GetString(SR.ADP_InvalidMetaDataValue));
}
internal static InvalidOperationException NonSequentialColumnAccess(int badCol, int currCol)
{
return InvalidOperation(SR.GetString(SR.ADP_NonSequentialColumnAccess, badCol.ToString(CultureInfo.InvariantCulture), currCol.ToString(CultureInfo.InvariantCulture)));
}
internal static Exception InvalidXmlInvalidValue(string collectionName, string columnName)
{
return Argument(SR.GetString(SR.MDF_InvalidXmlInvalidValue, collectionName, columnName));
}
internal static Exception CollectionNameIsNotUnique(string collectionName)
{
return Argument(SR.GetString(SR.MDF_CollectionNameISNotUnique, collectionName));
}
//
// : IDbCommand
//
internal static Exception InvalidCommandTimeout(int value, [CallerMemberName] string property = "")
{
return Argument(SR.GetString(SR.ADP_InvalidCommandTimeout, value.ToString(CultureInfo.InvariantCulture)), property);
}
internal static Exception UninitializedParameterSize(int index, Type dataType)
{
return InvalidOperation(SR.GetString(SR.ADP_UninitializedParameterSize, index.ToString(CultureInfo.InvariantCulture), dataType.Name));
}
internal static Exception UnableToBuildCollection(string collectionName)
{
return Argument(SR.GetString(SR.MDF_UnableToBuildCollection, collectionName));
}
internal static Exception PrepareParameterType(DbCommand cmd)
{
return InvalidOperation(SR.GetString(SR.ADP_PrepareParameterType, cmd.GetType().Name));
}
internal static Exception UndefinedCollection(string collectionName)
{
return Argument(SR.GetString(SR.MDF_UndefinedCollection, collectionName));
}
internal static Exception UnsupportedVersion(string collectionName)
{
return Argument(SR.GetString(SR.MDF_UnsupportedVersion, collectionName));
}
internal static Exception AmbigousCollectionName(string collectionName)
{
return Argument(SR.GetString(SR.MDF_AmbigousCollectionName, collectionName));
}
internal static Exception PrepareParameterSize(DbCommand cmd)
{
return InvalidOperation(SR.GetString(SR.ADP_PrepareParameterSize, cmd.GetType().Name));
}
internal static Exception PrepareParameterScale(DbCommand cmd, string type)
{
return InvalidOperation(SR.GetString(SR.ADP_PrepareParameterScale, cmd.GetType().Name, type));
}
internal static Exception MissingDataSourceInformationColumn()
{
return Argument(SR.GetString(SR.MDF_MissingDataSourceInformationColumn));
}
internal static Exception IncorrectNumberOfDataSourceInformationRows()
{
return Argument(SR.GetString(SR.MDF_IncorrectNumberOfDataSourceInformationRows));
}
internal static Exception MismatchedAsyncResult(string expectedMethod, string gotMethod)
{
return InvalidOperation(SR.GetString(SR.ADP_MismatchedAsyncResult, expectedMethod, gotMethod));
}
//
// : ConnectionUtil
//
internal static Exception ClosedConnectionError()
{
return InvalidOperation(SR.GetString(SR.ADP_ClosedConnectionError));
}
internal static Exception ConnectionAlreadyOpen(ConnectionState state)
{
return InvalidOperation(SR.GetString(SR.ADP_ConnectionAlreadyOpen, ADP.ConnectionStateMsg(state)));
}
internal static Exception TransactionPresent()
{
return InvalidOperation(SR.GetString(SR.ADP_TransactionPresent));
}
internal static Exception LocalTransactionPresent()
{
return InvalidOperation(SR.GetString(SR.ADP_LocalTransactionPresent));
}
internal static Exception OpenConnectionPropertySet(string property, ConnectionState state)
{
return InvalidOperation(SR.GetString(SR.ADP_OpenConnectionPropertySet, property, ADP.ConnectionStateMsg(state)));
}
internal static Exception EmptyDatabaseName()
{
return Argument(SR.GetString(SR.ADP_EmptyDatabaseName));
}
internal enum ConnectionError
{
BeginGetConnectionReturnsNull,
GetConnectionReturnsNull,
ConnectionOptionsMissing,
CouldNotSwitchToClosedPreviouslyOpenedState,
}
internal static Exception MissingRestrictionColumn()
{
return Argument(SR.GetString(SR.MDF_MissingRestrictionColumn));
}
internal static Exception InternalConnectionError(ConnectionError internalError)
{
return InvalidOperation(SR.GetString(SR.ADP_InternalConnectionError, (int)internalError));
}
internal static Exception InvalidConnectRetryCountValue()
{
return Argument(SR.GetString(SR.SQLCR_InvalidConnectRetryCountValue));
}
internal static Exception MissingRestrictionRow()
{
return Argument(SR.GetString(SR.MDF_MissingRestrictionRow));
}
internal static Exception InvalidConnectRetryIntervalValue()
{
return Argument(SR.GetString(SR.SQLCR_InvalidConnectRetryIntervalValue));
}
//
// : DbDataReader
//
internal static InvalidOperationException AsyncOperationPending()
{
return InvalidOperation(SR.GetString(SR.ADP_PendingAsyncOperation));
}
//
// : Stream
//
internal static IOException ErrorReadingFromStream(Exception internalException)
{
return IO(SR.GetString(SR.SqlMisc_StreamErrorMessage), internalException);
}
internal static ArgumentException InvalidDataType(TypeCode typecode)
{
return Argument(SR.GetString(SR.ADP_InvalidDataType, typecode.ToString()));
}
internal static ArgumentException UnknownDataType(Type dataType)
{
return Argument(SR.GetString(SR.ADP_UnknownDataType, dataType.FullName));
}
internal static ArgumentException DbTypeNotSupported(DbType type, Type enumtype)
{
return Argument(SR.GetString(SR.ADP_DbTypeNotSupported, type.ToString(), enumtype.Name));
}
internal static ArgumentException UnknownDataTypeCode(Type dataType, TypeCode typeCode)
{
return Argument(SR.GetString(SR.ADP_UnknownDataTypeCode, ((int)typeCode).ToString(CultureInfo.InvariantCulture), dataType.FullName));
}
internal static ArgumentException InvalidOffsetValue(int value)
{
return Argument(SR.GetString(SR.ADP_InvalidOffsetValue, value.ToString(CultureInfo.InvariantCulture)));
}
internal static ArgumentException InvalidSizeValue(int value)
{
return Argument(SR.GetString(SR.ADP_InvalidSizeValue, value.ToString(CultureInfo.InvariantCulture)));
}
internal static ArgumentException ParameterValueOutOfRange(decimal value)
{
return ADP.Argument(SR.GetString(SR.ADP_ParameterValueOutOfRange, value.ToString((IFormatProvider)null)));
}
internal static ArgumentException ParameterValueOutOfRange(SqlDecimal value)
{
return ADP.Argument(SR.GetString(SR.ADP_ParameterValueOutOfRange, value.ToString()));
}
internal static ArgumentException VersionDoesNotSupportDataType(string typeName)
{
return Argument(SR.GetString(SR.ADP_VersionDoesNotSupportDataType, typeName));
}
internal static Exception ParameterConversionFailed(object value, Type destType, Exception inner)
{
Debug.Assert(null != value, "null value on conversion failure");
Debug.Assert(null != inner, "null inner on conversion failure");
Exception e;
string message = SR.GetString(SR.ADP_ParameterConversionFailed, value.GetType().Name, destType.Name);
if (inner is ArgumentException)
{
e = new ArgumentException(message, inner);
}
else if (inner is FormatException)
{
e = new FormatException(message, inner);
}
else if (inner is InvalidCastException)
{
e = new InvalidCastException(message, inner);
}
else if (inner is OverflowException)
{
e = new OverflowException(message, inner);
}
else
{
e = inner;
}
return e;
}
//
// : IDataParameterCollection
//
internal static Exception ParametersMappingIndex(int index, DbParameterCollection collection)
{
return CollectionIndexInt32(index, collection.GetType(), collection.Count);
}
internal static Exception ParametersSourceIndex(string parameterName, DbParameterCollection collection, Type parameterType)
{
return CollectionIndexString(parameterType, ADP.ParameterName, parameterName, collection.GetType());
}
internal static Exception ParameterNull(string parameter, DbParameterCollection collection, Type parameterType)
{
return CollectionNullValue(parameter, collection.GetType(), parameterType);
}
internal static Exception UndefinedPopulationMechanism(string populationMechanism)
{
throw new NotImplementedException();
}
internal static Exception InvalidParameterType(DbParameterCollection collection, Type parameterType, object invalidValue)
{
return CollectionInvalidType(collection.GetType(), parameterType, invalidValue);
}
//
// : IDbTransaction
//
internal static Exception ParallelTransactionsNotSupported(DbConnection obj)
{
return InvalidOperation(SR.GetString(SR.ADP_ParallelTransactionsNotSupported, obj.GetType().Name));
}
internal static Exception TransactionZombied(DbTransaction obj)
{
return InvalidOperation(SR.GetString(SR.ADP_TransactionZombied, obj.GetType().Name));
}
// global constant strings
internal const string Parameter = "Parameter";
internal const string ParameterName = "ParameterName";
internal const string ParameterSetPosition = "set_Position";
internal const int DefaultCommandTimeout = 30;
internal const float FailoverTimeoutStep = 0.08F; // fraction of timeout to use for fast failover connections
// security issue, don't rely upon public static readonly values
internal static readonly string StrEmpty = ""; // String.Empty
internal const int CharSize = sizeof(char);
internal static Delegate FindBuilder(MulticastDelegate mcd)
{
if (null != mcd)
{
foreach (Delegate del in mcd.GetInvocationList())
{
if (del.Target is DbCommandBuilder)
return del;
}
}
return null;
}
internal static void TimerCurrent(out long ticks)
{
ticks = DateTime.UtcNow.ToFileTimeUtc();
}
internal static long TimerCurrent()
{
return DateTime.UtcNow.ToFileTimeUtc();
}
internal static long TimerFromSeconds(int seconds)
{
long result = checked((long)seconds * TimeSpan.TicksPerSecond);
return result;
}
internal static long TimerFromMilliseconds(long milliseconds)
{
long result = checked(milliseconds * TimeSpan.TicksPerMillisecond);
return result;
}
internal static bool TimerHasExpired(long timerExpire)
{
bool result = TimerCurrent() > timerExpire;
return result;
}
internal static long TimerRemaining(long timerExpire)
{
long timerNow = TimerCurrent();
long result = checked(timerExpire - timerNow);
return result;
}
internal static long TimerRemainingMilliseconds(long timerExpire)
{
long result = TimerToMilliseconds(TimerRemaining(timerExpire));
return result;
}
internal static long TimerRemainingSeconds(long timerExpire)
{
long result = TimerToSeconds(TimerRemaining(timerExpire));
return result;
}
internal static long TimerToMilliseconds(long timerValue)
{
long result = timerValue / TimeSpan.TicksPerMillisecond;
return result;
}
private static long TimerToSeconds(long timerValue)
{
long result = timerValue / TimeSpan.TicksPerSecond;
return result;
}
internal static string MachineName()
{
return Environment.MachineName;
}
internal static Transaction GetCurrentTransaction()
{
return Transaction.Current;
}
internal static bool IsDirection(DbParameter value, ParameterDirection condition)
{
#if DEBUG
IsDirectionValid(condition);
#endif
return (condition == (condition & value.Direction));
}
#if DEBUG
private static void IsDirectionValid(ParameterDirection value)
{
switch (value)
{ // @perfnote: Enum.IsDefined
case ParameterDirection.Input:
case ParameterDirection.Output:
case ParameterDirection.InputOutput:
case ParameterDirection.ReturnValue:
break;
default:
throw ADP.InvalidParameterDirection(value);
}
}
#endif
internal static void IsNullOrSqlType(object value, out bool isNull, out bool isSqlType)
{
if ((value == null) || (value == DBNull.Value))
{
isNull = true;
isSqlType = false;
}
else
{
INullable nullable = (value as INullable);
if (nullable != null)
{
isNull = nullable.IsNull;
// Duplicated from DataStorage.cs
// For back-compat, SqlXml is not in this list
isSqlType = ((value is SqlBinary) ||
(value is SqlBoolean) ||
(value is SqlByte) ||
(value is SqlBytes) ||
(value is SqlChars) ||
(value is SqlDateTime) ||
(value is SqlDecimal) ||
(value is SqlDouble) ||
(value is SqlGuid) ||
(value is SqlInt16) ||
(value is SqlInt32) ||
(value is SqlInt64) ||
(value is SqlMoney) ||
(value is SqlSingle) ||
(value is SqlString));
}
else
{
isNull = false;
isSqlType = false;
}
}
}
private static Version s_systemDataVersion;
internal static Version GetAssemblyVersion()
{
// NOTE: Using lazy thread-safety since we don't care if two threads both happen to update the value at the same time
if (s_systemDataVersion == null)
{
s_systemDataVersion = new Version(ThisAssembly.InformationalVersion);
}
return s_systemDataVersion;
}
internal static readonly string[] AzureSqlServerEndpoints = {SR.GetString(SR.AZURESQL_GenericEndpoint),
SR.GetString(SR.AZURESQL_GermanEndpoint),
SR.GetString(SR.AZURESQL_UsGovEndpoint),
SR.GetString(SR.AZURESQL_ChinaEndpoint)};
// This method assumes dataSource parameter is in TCP connection string format.
internal static bool IsAzureSqlServerEndpoint(string dataSource)
{
// remove server port
int i = dataSource.LastIndexOf(',');
if (i >= 0)
{
dataSource = dataSource.Substring(0, i);
}
// check for the instance name
i = dataSource.LastIndexOf('\\');
if (i >= 0)
{
dataSource = dataSource.Substring(0, i);
}
// trim redundant whitespace
dataSource = dataSource.Trim();
// check if servername end with any azure endpoints
for (i = 0; i < AzureSqlServerEndpoints.Length; i++)
{
if (dataSource.EndsWith(AzureSqlServerEndpoints[i], StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
internal static ArgumentOutOfRangeException InvalidDataRowVersion(DataRowVersion value)
{
#if DEBUG
switch (value)
{
case DataRowVersion.Default:
case DataRowVersion.Current:
case DataRowVersion.Original:
case DataRowVersion.Proposed:
Debug.Fail($"Invalid DataRowVersion {value}");
break;
}
#endif
return InvalidEnumerationValue(typeof(DataRowVersion), (int)value);
}
internal static ArgumentException SingleValuedProperty(string propertyName, string value)
{
ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_SingleValuedProperty, propertyName, value));
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentException DoubleValuedProperty(string propertyName, string value1, string value2)
{
ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_DoubleValuedProperty, propertyName, value1, value2));
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentException InvalidPrefixSuffix()
{
ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_InvalidPrefixSuffix));
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentOutOfRangeException InvalidCommandBehavior(CommandBehavior value)
{
Debug.Assert((0 > (int)value) || ((int)value > 0x3F), "valid CommandType " + value.ToString());
return InvalidEnumerationValue(typeof(CommandBehavior), (int)value);
}
internal static void ValidateCommandBehavior(CommandBehavior value)
{
if (((int)value < 0) || (0x3F < (int)value))
{
throw InvalidCommandBehavior(value);
}
}
internal static ArgumentOutOfRangeException NotSupportedCommandBehavior(CommandBehavior value, string method)
{
return NotSupportedEnumerationValue(typeof(CommandBehavior), value.ToString(), method);
}
internal static ArgumentException BadParameterName(string parameterName)
{
ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_BadParameterName, parameterName));
TraceExceptionAsReturnValue(e);
return e;
}
internal static Exception DeriveParametersNotSupported(IDbCommand value)
{
return DataAdapter(SR.GetString(SR.ADP_DeriveParametersNotSupported, value.GetType().Name, value.CommandType.ToString()));
}
internal static Exception NoStoredProcedureExists(string sproc)
{
return InvalidOperation(SR.GetString(SR.ADP_NoStoredProcedureExists, sproc));
}
//
// DbProviderException
//
internal static InvalidOperationException TransactionCompletedButNotDisposed()
{
return Provider(SR.GetString(SR.ADP_TransactionCompletedButNotDisposed));
}
internal static ArgumentOutOfRangeException InvalidUserDefinedTypeSerializationFormat(Microsoft.SqlServer.Server.Format value)
{
return InvalidEnumerationValue(typeof(Microsoft.SqlServer.Server.Format), (int)value);
}
internal static ArgumentOutOfRangeException NotSupportedUserDefinedTypeSerializationFormat(Microsoft.SqlServer.Server.Format value, string method)
{
return NotSupportedEnumerationValue(typeof(Microsoft.SqlServer.Server.Format), value.ToString(), method);
}
internal static ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName, object value)
{
ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName, value, message);
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentException InvalidArgumentLength(string argumentName, int limit)
{
return Argument(SR.GetString(SR.ADP_InvalidArgumentLength, argumentName, limit));
}
internal static ArgumentException MustBeReadOnly(string argumentName)
{
return Argument(SR.GetString(SR.ADP_MustBeReadOnly, argumentName));
}
internal static InvalidOperationException InvalidMixedUsageOfSecureAndClearCredential()
{
return InvalidOperation(SR.GetString(SR.ADP_InvalidMixedUsageOfSecureAndClearCredential));
}
internal static ArgumentException InvalidMixedArgumentOfSecureAndClearCredential()
{
return Argument(SR.GetString(SR.ADP_InvalidMixedUsageOfSecureAndClearCredential));
}
internal static InvalidOperationException InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity()
{
return InvalidOperation(SR.GetString(SR.ADP_InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity));
}
internal static ArgumentException InvalidMixedArgumentOfSecureCredentialAndIntegratedSecurity()
{
return Argument(SR.GetString(SR.ADP_InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity));
}
internal static InvalidOperationException InvalidMixedUsageOfAccessTokenAndIntegratedSecurity()
{
return ADP.InvalidOperation(SR.GetString(SR.ADP_InvalidMixedUsageOfAccessTokenAndIntegratedSecurity));
}
static internal InvalidOperationException InvalidMixedUsageOfAccessTokenAndUserIDPassword()
{
return ADP.InvalidOperation(SR.GetString(SR.ADP_InvalidMixedUsageOfAccessTokenAndUserIDPassword));
}
static internal Exception InvalidMixedUsageOfCredentialAndAccessToken()
{
return ADP.InvalidOperation(SR.GetString(SR.ADP_InvalidMixedUsageOfCredentialAndAccessToken));
}
}
}
| |
namespace SIL.Windows.Forms.WritingSystems
{
partial class WSSortControl
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region 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()
{
this.label1 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this._testSortText = new System.Windows.Forms.TextBox();
this._testSortResult = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this._testSortButton = new System.Windows.Forms.Button();
this.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel();
this.tableLayoutPanel4 = new System.Windows.Forms.TableLayoutPanel();
this._sortUsingComboBox = new System.Windows.Forms.ComboBox();
this.switcher_panel = new System.Windows.Forms.Panel();
this._sortrules_panel = new System.Windows.Forms.Panel();
this._languagecombo_panel = new System.Windows.Forms.TableLayoutPanel();
this.label2 = new System.Windows.Forms.Label();
this._languageComboBox = new System.Windows.Forms.ComboBox();
this._sortRulesTextBox = new System.Windows.Forms.TextBox();
this._helpLabel = new System.Windows.Forms.LinkLabel();
this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
this.tableLayoutPanel5 = new System.Windows.Forms.TableLayoutPanel();
this.tableLayoutPanel3.SuspendLayout();
this.tableLayoutPanel4.SuspendLayout();
this.switcher_panel.SuspendLayout();
this._sortrules_panel.SuspendLayout();
this._languagecombo_panel.SuspendLayout();
this.tableLayoutPanel2.SuspendLayout();
this.tableLayoutPanel5.SuspendLayout();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(3, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(29, 13);
this.label1.TabIndex = 0;
this.label1.Text = "&Sort:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(3, 29);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(65, 13);
this.label3.TabIndex = 0;
this.label3.Text = "Te&xt to Sort:";
//
// _testSortText
//
this._testSortText.AcceptsReturn = true;
this._testSortText.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this._testSortText.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this._testSortText.Location = new System.Drawing.Point(3, 45);
this._testSortText.Multiline = true;
this._testSortText.Name = "_testSortText";
this._testSortText.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this._testSortText.Size = new System.Drawing.Size(426, 161);
this._testSortText.TabIndex = 1;
this._testSortText.Enter += new System.EventHandler(this.TextControl_Enter);
this._testSortText.Leave += new System.EventHandler(this.TextControl_Leave);
//
// _testSortResult
//
this._testSortResult.BackColor = System.Drawing.SystemColors.Window;
this._testSortResult.Dock = System.Windows.Forms.DockStyle.Fill;
this._testSortResult.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this._testSortResult.Location = new System.Drawing.Point(3, 225);
this._testSortResult.Multiline = true;
this._testSortResult.Name = "_testSortResult";
this._testSortResult.ReadOnly = true;
this._testSortResult.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this._testSortResult.Size = new System.Drawing.Size(426, 161);
this._testSortResult.TabIndex = 1;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(3, 209);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(62, 13);
this.label4.TabIndex = 0;
this.label4.Text = "Sort Result:";
//
// _testSortButton
//
this._testSortButton.Anchor = System.Windows.Forms.AnchorStyles.Top;
this._testSortButton.AutoSize = true;
this._testSortButton.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this._testSortButton.Location = new System.Drawing.Point(186, 3);
this._testSortButton.Name = "_testSortButton";
this._testSortButton.Size = new System.Drawing.Size(60, 23);
this._testSortButton.TabIndex = 0;
this._testSortButton.Text = "&Test Sort";
this._testSortButton.UseVisualStyleBackColor = true;
this._testSortButton.Click += new System.EventHandler(this._testSortButton_Click);
//
// tableLayoutPanel3
//
this.tableLayoutPanel3.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.tableLayoutPanel3.ColumnCount = 2;
this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel3.Controls.Add(this.tableLayoutPanel4, 1, 0);
this.tableLayoutPanel3.Controls.Add(this.switcher_panel, 1, 1);
this.tableLayoutPanel3.Controls.Add(this._helpLabel, 1, 2);
this.tableLayoutPanel3.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel3.Location = new System.Drawing.Point(3, 3);
this.tableLayoutPanel3.Name = "tableLayoutPanel3";
this.tableLayoutPanel3.RowCount = 3;
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel3.Size = new System.Drawing.Size(187, 389);
this.tableLayoutPanel3.TabIndex = 0;
//
// tableLayoutPanel4
//
this.tableLayoutPanel4.AutoSize = true;
this.tableLayoutPanel4.ColumnCount = 2;
this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel4.Controls.Add(this.label1, 0, 1);
this.tableLayoutPanel4.Controls.Add(this._sortUsingComboBox, 1, 1);
this.tableLayoutPanel4.Location = new System.Drawing.Point(3, 3);
this.tableLayoutPanel4.Name = "tableLayoutPanel4";
this.tableLayoutPanel4.RowCount = 2;
this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel4.Size = new System.Drawing.Size(181, 27);
this.tableLayoutPanel4.TabIndex = 1;
//
// _sortUsingComboBox
//
this._sortUsingComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this._sortUsingComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this._sortUsingComboBox.FormattingEnabled = true;
this._sortUsingComboBox.Location = new System.Drawing.Point(38, 3);
this._sortUsingComboBox.Name = "_sortUsingComboBox";
this._sortUsingComboBox.Size = new System.Drawing.Size(140, 21);
this._sortUsingComboBox.TabIndex = 2;
this._sortUsingComboBox.SelectedIndexChanged += new System.EventHandler(this._sortUsingComboBox_SelectedIndexChanged);
//
// switcher_panel
//
this.switcher_panel.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.switcher_panel.Controls.Add(this._sortrules_panel);
this.switcher_panel.Dock = System.Windows.Forms.DockStyle.Fill;
this.switcher_panel.Location = new System.Drawing.Point(3, 36);
this.switcher_panel.Name = "switcher_panel";
this.switcher_panel.Size = new System.Drawing.Size(181, 337);
this.switcher_panel.TabIndex = 1;
//
// _sortrules_panel
//
this._sortrules_panel.Controls.Add(this._languagecombo_panel);
this._sortrules_panel.Controls.Add(this._sortRulesTextBox);
this._sortrules_panel.Dock = System.Windows.Forms.DockStyle.Fill;
this._sortrules_panel.Location = new System.Drawing.Point(0, 0);
this._sortrules_panel.Name = "_sortrules_panel";
this._sortrules_panel.Size = new System.Drawing.Size(181, 337);
this._sortrules_panel.TabIndex = 4;
//
// _languagecombo_panel
//
this._languagecombo_panel.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this._languagecombo_panel.ColumnCount = 1;
this._languagecombo_panel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this._languagecombo_panel.Controls.Add(this.label2, 0, 0);
this._languagecombo_panel.Controls.Add(this._languageComboBox, 0, 1);
this._languagecombo_panel.Dock = System.Windows.Forms.DockStyle.Fill;
this._languagecombo_panel.Location = new System.Drawing.Point(0, 0);
this._languagecombo_panel.Name = "_languagecombo_panel";
this._languagecombo_panel.RowCount = 2;
this._languagecombo_panel.RowStyles.Add(new System.Windows.Forms.RowStyle());
this._languagecombo_panel.RowStyles.Add(new System.Windows.Forms.RowStyle());
this._languagecombo_panel.Size = new System.Drawing.Size(181, 337);
this._languagecombo_panel.TabIndex = 1;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(3, 0);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(58, 13);
this.label2.TabIndex = 0;
this.label2.Text = "&Language:";
//
// _languageComboBox
//
this._languageComboBox.Dock = System.Windows.Forms.DockStyle.Fill;
this._languageComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this._languageComboBox.DropDownWidth = 156;
this._languageComboBox.FormattingEnabled = true;
this._languageComboBox.Location = new System.Drawing.Point(3, 16);
this._languageComboBox.Name = "_languageComboBox";
this._languageComboBox.Size = new System.Drawing.Size(175, 21);
this._languageComboBox.TabIndex = 1;
this._languageComboBox.SelectedIndexChanged += new System.EventHandler(this._languageComboBox_SelectedIndexChanged);
//
// _sortRulesTextBox
//
this._sortRulesTextBox.AcceptsReturn = true;
this._sortRulesTextBox.Dock = System.Windows.Forms.DockStyle.Fill;
this._sortRulesTextBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this._sortRulesTextBox.Location = new System.Drawing.Point(0, 0);
this._sortRulesTextBox.Multiline = true;
this._sortRulesTextBox.Name = "_sortRulesTextBox";
this._sortRulesTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this._sortRulesTextBox.Size = new System.Drawing.Size(181, 337);
this._sortRulesTextBox.TabIndex = 0;
this._sortRulesTextBox.TextChanged += new System.EventHandler(this._sortRulesTextBox_TextChanged);
this._sortRulesTextBox.Leave += new System.EventHandler(this._sortRulesTextBox_TextChanged);
//
// _helpLabel
//
this._helpLabel.AutoSize = true;
this._helpLabel.Location = new System.Drawing.Point(3, 376);
this._helpLabel.Name = "_helpLabel";
this._helpLabel.Size = new System.Drawing.Size(29, 13);
this._helpLabel.TabIndex = 3;
this._helpLabel.TabStop = true;
this._helpLabel.Text = "Help";
this._helpLabel.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.OnHelpLabelClicked);
//
// tableLayoutPanel2
//
this.tableLayoutPanel2.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.tableLayoutPanel2.ColumnCount = 1;
this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel2.Controls.Add(this._testSortResult, 0, 4);
this.tableLayoutPanel2.Controls.Add(this.label4, 0, 3);
this.tableLayoutPanel2.Controls.Add(this.label3, 0, 1);
this.tableLayoutPanel2.Controls.Add(this._testSortText, 0, 2);
this.tableLayoutPanel2.Controls.Add(this._testSortButton, 0, 0);
this.tableLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel2.Location = new System.Drawing.Point(196, 3);
this.tableLayoutPanel2.Name = "tableLayoutPanel2";
this.tableLayoutPanel2.RowCount = 5;
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel2.Size = new System.Drawing.Size(432, 389);
this.tableLayoutPanel2.TabIndex = 0;
//
// tableLayoutPanel5
//
this.tableLayoutPanel5.ColumnCount = 2;
this.tableLayoutPanel5.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel5.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel5.Controls.Add(this.tableLayoutPanel3, 0, 0);
this.tableLayoutPanel5.Controls.Add(this.tableLayoutPanel2, 1, 0);
this.tableLayoutPanel5.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel5.Location = new System.Drawing.Point(0, 0);
this.tableLayoutPanel5.Name = "tableLayoutPanel5";
this.tableLayoutPanel5.RowCount = 1;
this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel5.Size = new System.Drawing.Size(631, 395);
this.tableLayoutPanel5.TabIndex = 3;
//
// WSSortControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.tableLayoutPanel5);
this.Name = "WSSortControl";
this.Size = new System.Drawing.Size(631, 395);
this.tableLayoutPanel3.ResumeLayout(false);
this.tableLayoutPanel3.PerformLayout();
this.tableLayoutPanel4.ResumeLayout(false);
this.tableLayoutPanel4.PerformLayout();
this.switcher_panel.ResumeLayout(false);
this._sortrules_panel.ResumeLayout(false);
this._sortrules_panel.PerformLayout();
this._languagecombo_panel.ResumeLayout(false);
this._languagecombo_panel.PerformLayout();
this.tableLayoutPanel2.ResumeLayout(false);
this.tableLayoutPanel2.PerformLayout();
this.tableLayoutPanel5.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox _testSortText;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox _testSortResult;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Button _testSortButton;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel3;
private System.Windows.Forms.Panel switcher_panel;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2;
private System.Windows.Forms.TableLayoutPanel _languagecombo_panel;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ComboBox _languageComboBox;
private System.Windows.Forms.TextBox _sortRulesTextBox;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel4;
private System.Windows.Forms.ComboBox _sortUsingComboBox;
private System.Windows.Forms.LinkLabel _helpLabel;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel5;
private System.Windows.Forms.Panel _sortrules_panel;
}
}
| |
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Relational.Migrations.Infrastructure;
using AllReady.Models;
namespace AllReady.Migrations
{
[ContextType(typeof(AllReadyContext))]
partial class AllReadyContextModelSnapshot : ModelSnapshot
{
public override void BuildModel(ModelBuilder builder)
{
builder
.Annotation("SqlServer:ValueGeneration", "Identity");
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("Id")
.GenerateValueOnAdd();
b.Property<string>("ConcurrencyStamp")
.ConcurrencyToken();
b.Property<string>("Name");
b.Property<string>("NormalizedName");
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetRoles");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.GenerateValueOnAdd()
.StoreGeneratedPattern(StoreGeneratedPattern.Identity);
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId");
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetRoleClaims");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.GenerateValueOnAdd()
.StoreGeneratedPattern(StoreGeneratedPattern.Identity);
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId");
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetUserClaims");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.GenerateValueOnAdd();
b.Property<string>("ProviderKey")
.GenerateValueOnAdd();
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId");
b.Key("LoginProvider", "ProviderKey");
b.Annotation("Relational:TableName", "AspNetUserLogins");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.Key("UserId", "RoleId");
b.Annotation("Relational:TableName", "AspNetUserRoles");
});
builder.Entity("AllReady.Models.Activity", b =>
{
b.Property<int>("Id")
.GenerateValueOnAdd()
.StoreGeneratedPattern(StoreGeneratedPattern.Identity);
b.Property<int>("CampaignId");
b.Property<string>("Description");
b.Property<DateTime>("EndDateTimeUtc");
b.Property<string>("ImageUrl");
b.Property<int?>("LocationId");
b.Property<string>("Name");
b.Property<string>("OrganizerId");
b.Property<DateTime>("StartDateTimeUtc");
b.Property<int>("TenantId");
b.Key("Id");
});
builder.Entity("AllReady.Models.ActivitySignup", b =>
{
b.Property<int>("Id")
.GenerateValueOnAdd()
.StoreGeneratedPattern(StoreGeneratedPattern.Identity);
b.Property<int?>("ActivityId");
b.Property<DateTime?>("CheckinDateTime");
b.Property<DateTime>("SignupDateTime");
b.Property<string>("UserId");
b.Key("Id");
});
builder.Entity("AllReady.Models.ApplicationUser", b =>
{
b.Property<string>("Id")
.GenerateValueOnAdd();
b.Property<int>("AccessFailedCount");
b.Property<int?>("AssociatedTenantId");
b.Property<string>("ConcurrencyStamp")
.ConcurrencyToken();
b.Property<string>("Email");
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail");
b.Property<string>("NormalizedUserName");
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName");
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetUsers");
});
builder.Entity("AllReady.Models.Campaign", b =>
{
b.Property<int>("Id")
.GenerateValueOnAdd()
.StoreGeneratedPattern(StoreGeneratedPattern.Identity);
b.Property<string>("Description");
b.Property<DateTime>("EndDateTimeUtc");
b.Property<string>("ImageUrl");
b.Property<int>("ManagingTenantId");
b.Property<string>("Name");
b.Property<string>("OrganizerId");
b.Property<DateTime>("StartDateTimeUtc");
b.Key("Id");
});
builder.Entity("AllReady.Models.CampaignSponsors", b =>
{
b.Property<int>("Id")
.GenerateValueOnAdd()
.StoreGeneratedPattern(StoreGeneratedPattern.Identity);
b.Property<int?>("CampaignId");
b.Property<int?>("TenantId");
b.Key("Id");
});
builder.Entity("AllReady.Models.Location", b =>
{
b.Property<int>("Id")
.GenerateValueOnAdd()
.StoreGeneratedPattern(StoreGeneratedPattern.Identity);
b.Property<string>("Address1");
b.Property<string>("Address2");
b.Property<string>("City");
b.Property<string>("Country");
b.Property<string>("Name");
b.Property<string>("PhoneNumber");
b.Property<string>("PostalCodePostalCode");
b.Property<string>("State");
b.Key("Id");
});
builder.Entity("AllReady.Models.PostalCodeGeo", b =>
{
b.Property<string>("PostalCode")
.GenerateValueOnAdd();
b.Property<string>("City");
b.Property<string>("State");
b.Key("PostalCode");
});
builder.Entity("AllReady.Models.AllReadyTask", b =>
{
b.Property<int>("Id")
.GenerateValueOnAdd()
.StoreGeneratedPattern(StoreGeneratedPattern.Identity);
b.Property<int?>("ActivityId");
b.Property<string>("Description");
b.Property<DateTime?>("EndDateTimeUtc");
b.Property<string>("Name");
b.Property<DateTime?>("StartDateTimeUtc");
b.Property<int?>("TenantId");
b.Key("Id");
});
builder.Entity("AllReady.Models.TaskUsers", b =>
{
b.Property<int>("Id")
.GenerateValueOnAdd()
.StoreGeneratedPattern(StoreGeneratedPattern.Identity);
b.Property<string>("Status");
b.Property<DateTime>("StatusDateTimeUtc");
b.Property<string>("StatusDescription");
b.Property<int?>("TaskId");
b.Property<string>("UserId");
b.Key("Id");
});
builder.Entity("AllReady.Models.Tenant", b =>
{
b.Property<int>("Id")
.GenerateValueOnAdd()
.StoreGeneratedPattern(StoreGeneratedPattern.Identity);
b.Property<string>("LogoUrl");
b.Property<string>("Name");
b.Property<string>("WebUrl");
b.Key("Id");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.InverseCollection()
.ForeignKey("RoleId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Reference("AllReady.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Reference("AllReady.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.InverseCollection()
.ForeignKey("RoleId");
b.Reference("AllReady.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
builder.Entity("AllReady.Models.Activity", b =>
{
b.Reference("AllReady.Models.Campaign")
.InverseCollection()
.ForeignKey("CampaignId");
b.Reference("AllReady.Models.Location")
.InverseCollection()
.ForeignKey("LocationId");
b.Reference("AllReady.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("OrganizerId");
b.Reference("AllReady.Models.Tenant")
.InverseCollection()
.ForeignKey("TenantId");
});
builder.Entity("AllReady.Models.ActivitySignup", b =>
{
b.Reference("AllReady.Models.Activity")
.InverseCollection()
.ForeignKey("ActivityId");
b.Reference("AllReady.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
builder.Entity("AllReady.Models.ApplicationUser", b =>
{
b.Reference("AllReady.Models.Tenant")
.InverseCollection()
.ForeignKey("AssociatedTenantId");
});
builder.Entity("AllReady.Models.Campaign", b =>
{
b.Reference("AllReady.Models.Tenant")
.InverseCollection()
.ForeignKey("ManagingTenantId");
b.Reference("AllReady.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("OrganizerId");
});
builder.Entity("AllReady.Models.CampaignSponsors", b =>
{
b.Reference("AllReady.Models.Campaign")
.InverseCollection()
.ForeignKey("CampaignId");
b.Reference("AllReady.Models.Tenant")
.InverseCollection()
.ForeignKey("TenantId");
});
builder.Entity("AllReady.Models.Location", b =>
{
b.Reference("AllReady.Models.PostalCodeGeo")
.InverseCollection()
.ForeignKey("PostalCodePostalCode");
});
builder.Entity("AllReady.Models.AllReadyTask", b =>
{
b.Reference("AllReady.Models.Activity")
.InverseCollection()
.ForeignKey("ActivityId");
b.Reference("AllReady.Models.Tenant")
.InverseCollection()
.ForeignKey("TenantId");
});
builder.Entity("AllReady.Models.TaskUsers", b =>
{
b.Reference("AllReady.Models.AllReadyTask")
.InverseCollection()
.ForeignKey("TaskId");
b.Reference("AllReady.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
namespace UnityTest.IntegrationTests
{
[Serializable]
public class PlatformRunnerSettingsWindow : EditorWindow
{
private BuildTarget m_BuildTarget;
private List<string> m_IntegrationTestScenes;
private List<string> m_OtherScenesToBuild;
private List<string> m_AllScenesInProject;
private Vector2 m_ScrollPosition;
private readonly List<string> m_Interfaces = new List<string>();
private readonly List<string> m_SelectedScenes = new List<string>();
private int m_SelectedInterface;
[SerializeField]
private bool m_AdvancedNetworkingSettings;
private PlatformRunnerSettings m_Settings;
private string m_SelectedSceneInAll;
private string m_SelectedSceneInTest;
private string m_SelectedSceneInBuild;
readonly GUIContent m_Label = new GUIContent("Results target directory", "Directory where the results will be saved. If no value is specified, the results will be generated in project's data folder.");
public PlatformRunnerSettingsWindow()
{
if (m_OtherScenesToBuild == null)
m_OtherScenesToBuild = new List<string> ();
if (m_IntegrationTestScenes == null)
m_IntegrationTestScenes = new List<string> ();
titleContent = new GUIContent("Platform runner");
m_BuildTarget = PlatformRunner.defaultBuildTarget;
position.Set(position.xMin, position.yMin, 200, position.height);
m_AllScenesInProject = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.unity", SearchOption.AllDirectories).ToList();
m_AllScenesInProject.Sort();
var currentScene = (Directory.GetCurrentDirectory() + EditorApplication.currentScene).Replace("\\", "").Replace("/", "");
var currentScenePath = m_AllScenesInProject.Where(s => s.Replace("\\", "").Replace("/", "") == currentScene);
m_SelectedScenes.AddRange(currentScenePath);
m_Interfaces.Add("(Any)");
m_Interfaces.AddRange(TestRunnerConfigurator.GetAvailableNetworkIPs());
m_Interfaces.Add("127.0.0.1");
LoadFromPrefereneces ();
}
public void OnEnable()
{
m_Settings = ProjectSettingsBase.Load<PlatformRunnerSettings>();
// If not configured pre populate with all scenes that have test components on game objects
// This needs to be done outsie of constructor
if (m_IntegrationTestScenes.Count == 0)
m_IntegrationTestScenes = GetScenesWithTestComponents (m_AllScenesInProject);
}
public void OnGUI()
{
EditorGUILayout.BeginVertical();
GUIContent label;
/* We have three lists here, The tests to run, supporting scenes to include in the build and the list of all scenes so users can
* pick the scenes they want to include. The motiviation here is that test scenes may require to additively load other scenes as part of the tests
*/
EditorGUILayout.BeginHorizontal ();
// Integration Tests To Run
EditorGUILayout.BeginVertical ();
label = new GUIContent("Tests:", "All Integration Test scenes that you wish to run on the platform");
EditorGUILayout.LabelField(label, EditorStyles.boldLabel, GUILayout.Height(20f));
EditorGUI.BeginDisabledGroup(string.IsNullOrEmpty(m_SelectedSceneInTest));
if (GUILayout.Button("Remove Integration Test")) {
m_IntegrationTestScenes.Remove(m_SelectedSceneInTest);
m_SelectedSceneInTest = "";
}
EditorGUI.EndDisabledGroup();
DrawVerticalSceneList (ref m_IntegrationTestScenes, ref m_SelectedSceneInTest);
EditorGUILayout.EndVertical ();
// Extra scenes to include in build
EditorGUILayout.BeginVertical ();
label = new GUIContent("Other Scenes in Build:", "If your Integration Tests additivly load any other scenes then you want to include them here so they are part of the build");
EditorGUILayout.LabelField(label, EditorStyles.boldLabel, GUILayout.Height(20f));
EditorGUI.BeginDisabledGroup(string.IsNullOrEmpty(m_SelectedSceneInBuild));
if (GUILayout.Button("Remove From Build")) {
m_OtherScenesToBuild.Remove(m_SelectedSceneInBuild);
m_SelectedSceneInBuild = "";
}
EditorGUI.EndDisabledGroup();
DrawVerticalSceneList (ref m_OtherScenesToBuild, ref m_SelectedSceneInBuild);
EditorGUILayout.EndVertical ();
EditorGUILayout.Separator ();
// All Scenes
EditorGUILayout.BeginVertical ();
label = new GUIContent("Availble Scenes", "These are all the scenes within your project, please select some to run tests");
EditorGUILayout.LabelField(label, EditorStyles.boldLabel, GUILayout.Height(20f));
EditorGUILayout.BeginHorizontal ();
EditorGUI.BeginDisabledGroup(string.IsNullOrEmpty(m_SelectedSceneInAll));
if (GUILayout.Button("Add As Test")) {
if (!m_IntegrationTestScenes.Contains (m_SelectedSceneInAll) && !m_OtherScenesToBuild.Contains (m_SelectedSceneInAll)) {
m_IntegrationTestScenes.Add(m_SelectedSceneInAll);
}
}
if (GUILayout.Button("Add to Build")) {
if (!m_IntegrationTestScenes.Contains (m_SelectedSceneInAll) && !m_OtherScenesToBuild.Contains (m_SelectedSceneInAll)) {
m_OtherScenesToBuild.Add(m_SelectedSceneInAll);
}
}
EditorGUI.EndDisabledGroup();
EditorGUILayout.EndHorizontal ();
DrawVerticalSceneList (ref m_AllScenesInProject, ref m_SelectedSceneInAll);
EditorGUILayout.EndVertical ();
// ButtoNetworkResultsReceiverns to edit scenes in lists
EditorGUILayout.EndHorizontal ();
GUILayout.Space(3);
// Select target platform
m_BuildTarget = (BuildTarget)EditorGUILayout.EnumPopup("Build tests for", m_BuildTarget);
if (PlatformRunner.defaultBuildTarget != m_BuildTarget)
{
if (GUILayout.Button("Make default target platform"))
{
PlatformRunner.defaultBuildTarget = m_BuildTarget;
}
}
GUI.enabled = true;
// Select various Network settings
DrawSetting();
var build = GUILayout.Button("Build and run tests");
EditorGUILayout.EndVertical();
if (build)
{
BuildAndRun ();
}
}
private void DrawVerticalSceneList(ref List<string> sourceList, ref string selectString)
{
m_ScrollPosition = EditorGUILayout.BeginScrollView(m_ScrollPosition, Styles.testList);
EditorGUI.indentLevel++;
foreach (var scenePath in sourceList)
{
var path = Path.GetFileNameWithoutExtension(scenePath);
var guiContent = new GUIContent(path, scenePath);
var rect = GUILayoutUtility.GetRect(guiContent, EditorStyles.label);
if (rect.Contains(Event.current.mousePosition))
{
if (Event.current.type == EventType.mouseDown && Event.current.button == 0)
{
selectString = scenePath;
Event.current.Use();
}
}
var style = new GUIStyle(EditorStyles.label);
if (selectString == scenePath)
style.normal.textColor = new Color(0.3f, 0.5f, 0.85f);
EditorGUI.LabelField(rect, guiContent, style);
}
EditorGUI.indentLevel--;
EditorGUILayout.EndScrollView();
}
public static List<string> GetScenesWithTestComponents(List<string> allScenes)
{
List<Object> results = EditorReferencesUtil.FindScenesWhichContainAsset("TestComponent.cs");
List<string> integrationTestScenes = new List<string>();
foreach (Object obj in results) {
string result = allScenes.FirstOrDefault(s => s.Contains(obj.name));
if (!string.IsNullOrEmpty(result))
integrationTestScenes.Add(result);
}
return integrationTestScenes;
}
private void DrawSetting()
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.BeginHorizontal();
m_Settings.resultsPath = EditorGUILayout.TextField(m_Label, m_Settings.resultsPath);
if (GUILayout.Button("Search", EditorStyles.miniButton, GUILayout.Width(50)))
{
var selectedPath = EditorUtility.SaveFolderPanel("Result files destination", m_Settings.resultsPath, "");
if (!string.IsNullOrEmpty(selectedPath))
m_Settings.resultsPath = Path.GetFullPath(selectedPath);
}
EditorGUILayout.EndHorizontal();
if (!string.IsNullOrEmpty(m_Settings.resultsPath))
{
Uri uri;
if (!Uri.TryCreate(m_Settings.resultsPath, UriKind.Absolute, out uri) || !uri.IsFile || uri.IsWellFormedOriginalString())
{
EditorGUILayout.HelpBox("Invalid URI path", MessageType.Warning);
}
}
m_Settings.sendResultsOverNetwork = EditorGUILayout.Toggle("Send results to editor", m_Settings.sendResultsOverNetwork);
EditorGUI.BeginDisabledGroup(!m_Settings.sendResultsOverNetwork);
m_AdvancedNetworkingSettings = EditorGUILayout.Foldout(m_AdvancedNetworkingSettings, "Advanced network settings");
if (m_AdvancedNetworkingSettings)
{
m_SelectedInterface = EditorGUILayout.Popup("Network interface", m_SelectedInterface, m_Interfaces.ToArray());
EditorGUI.BeginChangeCheck();
m_Settings.port = EditorGUILayout.IntField("Network port", m_Settings.port);
if (EditorGUI.EndChangeCheck())
{
if (m_Settings.port > IPEndPoint.MaxPort)
m_Settings.port = IPEndPoint.MaxPort;
else if (m_Settings.port < IPEndPoint.MinPort)
m_Settings.port = IPEndPoint.MinPort;
}
EditorGUI.EndDisabledGroup();
}
if (EditorGUI.EndChangeCheck())
{
m_Settings.Save();
}
}
private void BuildAndRun()
{
SaveToPreferences ();
var config = new PlatformRunnerConfiguration
{
buildTarget = m_BuildTarget,
buildScenes = m_OtherScenesToBuild,
testScenes = m_IntegrationTestScenes,
projectName = m_IntegrationTestScenes.Count > 1 ? "IntegrationTests" : Path.GetFileNameWithoutExtension(EditorApplication.currentScene),
resultsDir = m_Settings.resultsPath,
sendResultsOverNetwork = m_Settings.sendResultsOverNetwork,
ipList = m_Interfaces.Skip(1).ToList(),
port = m_Settings.port
};
if (m_SelectedInterface > 0)
config.ipList = new List<string> {m_Interfaces.ElementAt(m_SelectedInterface)};
PlatformRunner.BuildAndRunInPlayer(config);
Close ();
}
public void OnLostFocus() {
SaveToPreferences ();
}
public void OnDestroy() {
SaveToPreferences ();
}
private void SaveToPreferences()
{
EditorPrefs.SetString (Animator.StringToHash (Application.dataPath + "uttTestScenes").ToString (), String.Join (",",m_IntegrationTestScenes.ToArray()));
EditorPrefs.SetString (Animator.StringToHash (Application.dataPath + "uttBuildScenes").ToString (), String.Join (",",m_OtherScenesToBuild.ToArray()));
}
private void LoadFromPrefereneces()
{
string storedTestScenes = EditorPrefs.GetString (Animator.StringToHash (Application.dataPath + "uttTestScenes").ToString ());
string storedBuildScenes = EditorPrefs.GetString (Animator.StringToHash (Application.dataPath + "uttBuildScenes").ToString ());
List<string> parsedTestScenes = storedTestScenes.Split (',').ToList ();
List<string> parsedBuildScenes = storedBuildScenes.Split (',').ToList ();
// Sanity check scenes actually exist
foreach (string str in parsedTestScenes) {
if (m_AllScenesInProject.Contains(str))
m_IntegrationTestScenes.Add(str);
}
foreach (string str in parsedBuildScenes) {
if (m_AllScenesInProject.Contains(str))
m_OtherScenesToBuild.Add(str);
}
}
}
}
| |
//
// https://github.com/NServiceKit/NServiceKit.Redis/
// NServiceKit.Redis: ECMA CLI Binding to the Redis key-value storage system
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2013 ServiceStack.
//
// Licensed under the same terms of Redis and ServiceStack: new BSD license.
//
using System;
using System.Collections.Generic;
namespace NServiceKit.Redis
{
/// <summary>Interface for redis native client.</summary>
public interface IRedisNativeClient
: IDisposable
{
//Redis utility operations
/// <summary>
/// Info
/// </summary>
Dictionary<string, string> Info { get; }
/// <summary>Gets or sets the database.</summary>
///
/// <value>The database.</value>
long Db { get; set; }
/// <summary>Gets the size of the database.</summary>
///
/// <value>The size of the database.</value>
long DbSize { get; }
/// <summary>Gets the Date/Time of the last save.</summary>
///
/// <value>The last save.</value>
DateTime LastSave { get; }
/// <summary>Saves this object.</summary>
void Save();
/// <summary>Background save.</summary>
void BgSave();
/// <summary>Shuts down this object and frees any resources it is using.</summary>
void Shutdown();
/// <summary>Background rewrite aof.</summary>
void BgRewriteAof();
/// <summary>Quits this object.</summary>
void Quit();
/// <summary>Flushes the database.</summary>
void FlushDb();
/// <summary>Flushes all.</summary>
void FlushAll();
/// <summary>Pings this object.</summary>
///
/// <returns>true if it succeeds, false if it fails.</returns>
bool Ping();
/// <summary>Echoes.</summary>
///
/// <param name="text">The text.</param>
///
/// <returns>A string.</returns>
string Echo(string text);
/// <summary>Slave of.</summary>
///
/// <param name="hostname">The hostname.</param>
/// <param name="port"> The port.</param>
void SlaveOf(string hostname, int port);
/// <summary>Slave of no one.</summary>
void SlaveOfNoOne();
/// <summary>Configuration get.</summary>
///
/// <param name="pattern">Specifies the pattern.</param>
///
/// <returns>A byte[][].</returns>
byte[][] ConfigGet(string pattern);
/// <summary>Configuration set.</summary>
///
/// <param name="item"> The item.</param>
/// <param name="value">The value.</param>
void ConfigSet(string item, byte[] value);
/// <summary>Configuration reset stat.</summary>
void ConfigResetStat();
/// <summary>Gets the time.</summary>
///
/// <returns>A byte[][].</returns>
byte[][] Time();
/// <summary>Debug segfault.</summary>
void DebugSegfault();
/// <summary>Dumps.</summary>
///
/// <param name="key">The key.</param>
///
/// <returns>A byte[].</returns>
byte[] Dump(string key);
/// <summary>Restores.</summary>
///
/// <param name="key"> The key.</param>
/// <param name="expireMs"> The expire in milliseconds.</param>
/// <param name="dumpValue">The dump value.</param>
///
/// <returns>A byte[].</returns>
byte[] Restore(string key, long expireMs, byte[] dumpValue);
/// <summary>Migrates.</summary>
///
/// <param name="host"> The host.</param>
/// <param name="port"> The port.</param>
/// <param name="destinationDb">Destination database.</param>
/// <param name="timeoutMs"> The timeout in milliseconds.</param>
void Migrate(string host, int port, int destinationDb, long timeoutMs);
/// <summary>Moves.</summary>
///
/// <param name="key">The key.</param>
/// <param name="db"> The database.</param>
///
/// <returns>true if it succeeds, false if it fails.</returns>
bool Move(string key, int db);
/// <summary>Object idle time.</summary>
///
/// <param name="key">The key.</param>
///
/// <returns>A long.</returns>
long ObjectIdleTime(string key);
/// <summary>Keys.</summary>
///
/// <param name="pattern">Specifies the pattern.</param>
///
/// <returns>A byte[][].</returns>
byte[][] Keys(string pattern);
/// <summary>Exists.</summary>
///
/// <param name="key">The key.</param>
///
/// <returns>A long.</returns>
long Exists(string key);
/// <summary>String lens.</summary>
///
/// <param name="key">The key.</param>
///
/// <returns>A long.</returns>
long StrLen(string key);
/// <summary>Sets.</summary>
///
/// <param name="key"> The key.</param>
/// <param name="value">The value.</param>
void Set(string key, byte[] value);
/// <summary>Sets an ex.</summary>
///
/// <param name="key"> The key.</param>
/// <param name="expireInSeconds">The expire in seconds.</param>
/// <param name="value"> The value.</param>
void SetEx(string key, int expireInSeconds, byte[] value);
/// <summary>Persists.</summary>
///
/// <param name="key">The key.</param>
///
/// <returns>true if it succeeds, false if it fails.</returns>
bool Persist(string key);
/// <summary>Sets an ex.</summary>
///
/// <param name="key"> The key.</param>
/// <param name="expireInMs">The expire in milliseconds.</param>
/// <param name="value"> The value.</param>
void PSetEx(string key, long expireInMs, byte[] value);
/// <summary>Sets a nx.</summary>
///
/// <param name="key"> The key.</param>
/// <param name="value">The value.</param>
///
/// <returns>A long.</returns>
long SetNX(string key, byte[] value);
/// <summary>Sets.</summary>
///
/// <param name="keys"> The keys.</param>
/// <param name="values">The values.</param>
void MSet(byte[][] keys, byte[][] values);
/// <summary>Sets.</summary>
///
/// <param name="keys"> The keys.</param>
/// <param name="values">The values.</param>
void MSet(string[] keys, byte[][] values);
/// <summary>Sets a nx.</summary>
///
/// <param name="keys"> The keys.</param>
/// <param name="values">The values.</param>
///
/// <returns>true if it succeeds, false if it fails.</returns>
bool MSetNx(byte[][] keys, byte[][] values);
/// <summary>Sets a nx.</summary>
///
/// <param name="keys"> The keys.</param>
/// <param name="values">The values.</param>
///
/// <returns>true if it succeeds, false if it fails.</returns>
bool MSetNx(string[] keys, byte[][] values);
/// <summary>Gets.</summary>
///
/// <param name="key">The key.</param>
///
/// <returns>A byte[].</returns>
byte[] Get(string key);
/// <summary>Gets a set.</summary>
///
/// <param name="key"> The key.</param>
/// <param name="value">The value.</param>
///
/// <returns>An array of byte.</returns>
byte[] GetSet(string key, byte[] value);
/// <summary>Gets the given keys.</summary>
///
/// <param name="keysAndArgs">A variable-length parameters list containing keys and arguments.</param>
///
/// <returns>A byte[][].</returns>
byte[][] MGet(params byte[][] keysAndArgs);
/// <summary>Gets the given keys.</summary>
///
/// <param name="keys">The keys.</param>
///
/// <returns>A byte[][].</returns>
byte[][] MGet(params string[] keys);
/// <summary>Deletes the given keys.</summary>
///
/// <param name="key">The key.</param>
///
/// <returns>A long.</returns>
long Del(string key);
/// <summary>Deletes the given keys.</summary>
///
/// <param name="keys">The keys.</param>
///
/// <returns>A long.</returns>
long Del(params string[] keys);
/// <summary>Incrs.</summary>
///
/// <param name="key">The key.</param>
///
/// <returns>A long.</returns>
long Incr(string key);
/// <summary>Increment by.</summary>
///
/// <param name="key"> The key.</param>
/// <param name="incrBy">Amount to increment by.</param>
///
/// <returns>A long.</returns>
long IncrBy(string key, int incrBy);
/// <summary>Increment by float.</summary>
///
/// <param name="key"> The key.</param>
/// <param name="incrBy">Amount to increment by.</param>
///
/// <returns>A double.</returns>
double IncrByFloat(string key, double incrBy);
/// <summary>Decrs.</summary>
///
/// <param name="key">The key.</param>
///
/// <returns>A long.</returns>
long Decr(string key);
/// <summary>Decrement by.</summary>
///
/// <param name="key"> The key.</param>
/// <param name="decrBy">Amount to decrement by.</param>
///
/// <returns>A long.</returns>
long DecrBy(string key, int decrBy);
/// <summary>Appends a key.</summary>
///
/// <param name="key"> The key.</param>
/// <param name="value">The value.</param>
///
/// <returns>A long.</returns>
long Append(string key, byte[] value);
/// <summary>(This method is obsolete) substrs.</summary>
///
/// <param name="key"> The key.</param>
/// <param name="fromIndex">Zero-based index of from.</param>
/// <param name="toIndex"> Zero-based index of to.</param>
///
/// <returns>A byte[].</returns>
[Obsolete("Was renamed to GetRange in 2.4")]
byte[] Substr(string key, int fromIndex, int toIndex);
/// <summary>Finds the range of the given arguments.</summary>
///
/// <param name="key"> The key.</param>
/// <param name="fromIndex">Zero-based index of from.</param>
/// <param name="toIndex"> Zero-based index of to.</param>
///
/// <returns>The calculated range.</returns>
byte[] GetRange(string key, int fromIndex, int toIndex);
/// <summary>Sets a range.</summary>
///
/// <param name="key"> The key.</param>
/// <param name="offset">The offset.</param>
/// <param name="value"> The value.</param>
///
/// <returns>A long.</returns>
long SetRange(string key, int offset, byte[] value);
/// <summary>Gets a bit.</summary>
///
/// <param name="key"> The key.</param>
/// <param name="offset">The offset.</param>
///
/// <returns>The bit.</returns>
long GetBit(string key, int offset);
/// <summary>Sets a bit.</summary>
///
/// <param name="key"> The key.</param>
/// <param name="offset">The offset.</param>
/// <param name="value"> The value.</param>
///
/// <returns>A long.</returns>
long SetBit(string key, int offset, int value);
/// <summary>Random key.</summary>
///
/// <returns>A string.</returns>
string RandomKey();
/// <summary>Renames.</summary>
///
/// <param name="oldKeyname">The old keyname.</param>
/// <param name="newKeyname">The new keyname.</param>
void Rename(string oldKeyname, string newKeyname);
/// <summary>Rename nx.</summary>
///
/// <param name="oldKeyname">The old keyname.</param>
/// <param name="newKeyname">The new keyname.</param>
///
/// <returns>true if it succeeds, false if it fails.</returns>
bool RenameNx(string oldKeyname, string newKeyname);
/// <summary>Expires.</summary>
///
/// <param name="key"> The key.</param>
/// <param name="seconds">The seconds.</param>
///
/// <returns>true if it succeeds, false if it fails.</returns>
bool Expire(string key, int seconds);
/// <summary>Expires.</summary>
///
/// <param name="key"> The key.</param>
/// <param name="ttlMs">The TTL in milliseconds.</param>
///
/// <returns>true if it succeeds, false if it fails.</returns>
bool PExpire(string key, long ttlMs);
/// <summary>Expire at.</summary>
///
/// <param name="key"> The key.</param>
/// <param name="unixTime">The unix time.</param>
///
/// <returns>true if it succeeds, false if it fails.</returns>
bool ExpireAt(string key, long unixTime);
/// <summary>Expire at.</summary>
///
/// <param name="key"> The key.</param>
/// <param name="unixTimeMs">The unix time in milliseconds.</param>
///
/// <returns>true if it succeeds, false if it fails.</returns>
bool PExpireAt(string key, long unixTimeMs);
/// <summary>Ttls.</summary>
///
/// <param name="key">The key.</param>
///
/// <returns>A long.</returns>
long Ttl(string key);
/// <summary>Ttls.</summary>
///
/// <param name="key">The key.</param>
///
/// <returns>A long.</returns>
long PTtl(string key);
/// <summary>Sorts.</summary>
///
/// <param name="listOrSetId">Identifier for the list or set.</param>
/// <param name="sortOptions">Options for controlling the sort.</param>
///
/// <returns>The sorted values.</returns>
byte[][] Sort(string listOrSetId, SortOptions sortOptions);
/// <summary>Ranges.</summary>
///
/// <param name="listId"> Identifier for the list.</param>
/// <param name="startingFrom">The starting from.</param>
/// <param name="endingAt"> The ending at.</param>
///
/// <returns>A byte[][].</returns>
byte[][] LRange(string listId, int startingFrom, int endingAt);
/// <summary>Pushes an object onto this stack.</summary>
///
/// <param name="listId">Identifier for the list.</param>
/// <param name="value"> The value.</param>
///
/// <returns>A long.</returns>
long RPush(string listId, byte[] value);
/// <summary>Pushes an x coordinate.</summary>
///
/// <param name="listId">Identifier for the list.</param>
/// <param name="value"> The value.</param>
///
/// <returns>A long.</returns>
long RPushX(string listId, byte[] value);
/// <summary>Pushes an object onto this stack.</summary>
///
/// <param name="listId">Identifier for the list.</param>
/// <param name="value"> The value.</param>
///
/// <returns>A long.</returns>
long LPush(string listId, byte[] value);
/// <summary>Pushes an x coordinate.</summary>
///
/// <param name="listId">Identifier for the list.</param>
/// <param name="value"> The value.</param>
///
/// <returns>A long.</returns>
long LPushX(string listId, byte[] value);
/// <summary>Trims.</summary>
///
/// <param name="listId"> Identifier for the list.</param>
/// <param name="keepStartingFrom">The keep starting from.</param>
/// <param name="keepEndingAt"> The keep ending at.</param>
void LTrim(string listId, int keepStartingFrom, int keepEndingAt);
/// <summary>Rems.</summary>
///
/// <param name="listId"> Identifier for the list.</param>
/// <param name="removeNoOfMatches">The remove no of matches.</param>
/// <param name="value"> The value.</param>
///
/// <returns>A long.</returns>
long LRem(string listId, int removeNoOfMatches, byte[] value);
/// <summary>Lens.</summary>
///
/// <param name="listId">Identifier for the list.</param>
///
/// <returns>A long.</returns>
long LLen(string listId);
/// <summary>Indexes.</summary>
///
/// <param name="listId"> Identifier for the list.</param>
/// <param name="listIndex">Zero-based index of the list.</param>
///
/// <returns>A byte[].</returns>
byte[] LIndex(string listId, int listIndex);
/// <summary>Inserts.</summary>
///
/// <param name="listId"> Identifier for the list.</param>
/// <param name="insertBefore">true to insert before.</param>
/// <param name="pivot"> The pivot.</param>
/// <param name="value"> The value.</param>
void LInsert(string listId, bool insertBefore, byte[] pivot, byte[] value);
/// <summary>Sets.</summary>
///
/// <param name="listId"> Identifier for the list.</param>
/// <param name="listIndex">Zero-based index of the list.</param>
/// <param name="value"> The value.</param>
void LSet(string listId, int listIndex, byte[] value);
/// <summary>Removes and returns the top-of-stack object.</summary>
///
/// <param name="listId">Identifier for the list.</param>
///
/// <returns>The previous top-of-stack object.</returns>
byte[] LPop(string listId);
/// <summary>Removes and returns the top-of-stack object.</summary>
///
/// <param name="listId">Identifier for the list.</param>
///
/// <returns>The previous top-of-stack object.</returns>
byte[] RPop(string listId);
/// <summary>Bl pop.</summary>
///
/// <param name="listId"> Identifier for the list.</param>
/// <param name="timeOutSecs">The time out in seconds.</param>
///
/// <returns>A byte[][].</returns>
byte[][] BLPop(string listId, int timeOutSecs);
/// <summary>Bl pop.</summary>
///
/// <param name="listIds"> List of identifiers for the lists.</param>
/// <param name="timeOutSecs">The time out in seconds.</param>
///
/// <returns>A byte[][].</returns>
byte[][] BLPop(string[] listIds, int timeOutSecs);
/// <summary>Bl pop value.</summary>
///
/// <param name="listId"> Identifier for the list.</param>
/// <param name="timeOutSecs">The time out in seconds.</param>
///
/// <returns>A byte[][].</returns>
byte[] BLPopValue(string listId, int timeOutSecs);
/// <summary>Bl pop value.</summary>
///
/// <param name="listIds"> List of identifiers for the lists.</param>
/// <param name="timeOutSecs">The time out in seconds.</param>
///
/// <returns>A byte[][].</returns>
byte[][] BLPopValue(string[] listIds, int timeOutSecs);
/// <summary>Line break pop.</summary>
///
/// <param name="listId"> Identifier for the list.</param>
/// <param name="timeOutSecs">The time out in seconds.</param>
///
/// <returns>A byte[][].</returns>
byte[][] BRPop(string listId, int timeOutSecs);
/// <summary>Line break pop.</summary>
///
/// <param name="listIds"> List of identifiers for the lists.</param>
/// <param name="timeOutSecs">The time out in seconds.</param>
///
/// <returns>A byte[][].</returns>
byte[][] BRPop(string[] listIds, int timeOutSecs);
/// <summary>Pops the l push.</summary>
///
/// <param name="fromListId">Identifier for from list.</param>
/// <param name="toListId"> Identifier for to list.</param>
///
/// <returns>A byte[].</returns>
byte[] RPopLPush(string fromListId, string toListId);
/// <summary>Line break pop value.</summary>
///
/// <param name="listId"> Identifier for the list.</param>
/// <param name="timeOutSecs">The time out in seconds.</param>
///
/// <returns>A byte[][].</returns>
byte[] BRPopValue(string listId, int timeOutSecs);
/// <summary>Line break pop value.</summary>
///
/// <param name="listIds"> List of identifiers for the lists.</param>
/// <param name="timeOutSecs">The time out in seconds.</param>
///
/// <returns>A byte[][].</returns>
byte[][] BRPopValue(string[] listIds, int timeOutSecs);
/// <summary>Line break pop l push.</summary>
///
/// <param name="fromListId"> Identifier for from list.</param>
/// <param name="toListId"> Identifier for to list.</param>
/// <param name="timeOutSecs">The time out in seconds.</param>
///
/// <returns>A byte[].</returns>
byte[] BRPopLPush(string fromListId, string toListId, int timeOutSecs);
/// <summary>Members.</summary>
///
/// <param name="setId">Identifier for the set.</param>
///
/// <returns>A byte[][].</returns>
byte[][] SMembers(string setId);
/// <summary>Adds setId.</summary>
///
/// <param name="setId">Identifier for the set.</param>
/// <param name="value">The value.</param>
///
/// <returns>A long.</returns>
long SAdd(string setId, byte[] value);
/// <summary>Adds setId.</summary>
///
/// <param name="setId"> Identifier for the set.</param>
/// <param name="values">The values.</param>
///
/// <returns>A long.</returns>
long SAdd(string setId, byte[][] values);
/// <summary>Rems.</summary>
///
/// <param name="setId">Identifier for the set.</param>
/// <param name="value">The value.</param>
///
/// <returns>A long.</returns>
long SRem(string setId, byte[] value);
/// <summary>Removes and returns the top-of-stack object.</summary>
///
/// <param name="setId">Identifier for the set.</param>
///
/// <returns>The previous top-of-stack object.</returns>
byte[] SPop(string setId);
/// <summary>Moves.</summary>
///
/// <param name="fromSetId">Identifier for from set.</param>
/// <param name="toSetId"> Identifier for to set.</param>
/// <param name="value"> The value.</param>
void SMove(string fromSetId, string toSetId, byte[] value);
/// <summary>Cards.</summary>
///
/// <param name="setId">Identifier for the set.</param>
///
/// <returns>A long.</returns>
long SCard(string setId);
/// <summary>Is member.</summary>
///
/// <param name="setId">Identifier for the set.</param>
/// <param name="value">The value.</param>
///
/// <returns>A long.</returns>
long SIsMember(string setId, byte[] value);
/// <summary>Inters the given set identifiers.</summary>
///
/// <param name="setIds">List of identifiers for the sets.</param>
///
/// <returns>A byte[][].</returns>
byte[][] SInter(params string[] setIds);
/// <summary>Inter store.</summary>
///
/// <param name="intoSetId">Identifier for the into set.</param>
/// <param name="setIds"> List of identifiers for the sets.</param>
void SInterStore(string intoSetId, params string[] setIds);
/// <summary>Unions the given set identifiers.</summary>
///
/// <param name="setIds">List of identifiers for the sets.</param>
///
/// <returns>A byte[][].</returns>
byte[][] SUnion(params string[] setIds);
/// <summary>Union store.</summary>
///
/// <param name="intoSetId">Identifier for the into set.</param>
/// <param name="setIds"> List of identifiers for the sets.</param>
void SUnionStore(string intoSetId, params string[] setIds);
/// <summary>Compares two string objects to determine their relative ordering.</summary>
///
/// <param name="fromSetId"> Identifier for from set.</param>
/// <param name="withSetIds">List of identifiers for the with sets.</param>
///
/// <returns>A byte[][].</returns>
byte[][] SDiff(string fromSetId, params string[] withSetIds);
/// <summary>Difference store.</summary>
///
/// <param name="intoSetId"> Identifier for the into set.</param>
/// <param name="fromSetId"> Identifier for from set.</param>
/// <param name="withSetIds">List of identifiers for the with sets.</param>
void SDiffStore(string intoSetId, string fromSetId, params string[] withSetIds);
/// <summary>Random member.</summary>
///
/// <param name="setId">Identifier for the set.</param>
///
/// <returns>A byte[].</returns>
byte[] SRandMember(string setId);
/// <summary>Adds setId.</summary>
///
/// <param name="setId">Identifier for the set.</param>
/// <param name="score">The score.</param>
/// <param name="value">The value.</param>
///
/// <returns>A long.</returns>
long ZAdd(string setId, double score, byte[] value);
/// <summary>Adds setId.</summary>
///
/// <param name="setId">Identifier for the set.</param>
/// <param name="score">The score.</param>
/// <param name="value">The value.</param>
///
/// <returns>A long.</returns>
long ZAdd(string setId, long score, byte[] value);
/// <summary>Z coordinate rems.</summary>
///
/// <param name="setId">Identifier for the set.</param>
/// <param name="value">The value.</param>
///
/// <returns>A long.</returns>
long ZRem(string setId, byte[] value);
/// <summary>Increment by.</summary>
///
/// <param name="setId"> Identifier for the set.</param>
/// <param name="incrBy">Amount to increment by.</param>
/// <param name="value"> The value.</param>
///
/// <returns>A double.</returns>
double ZIncrBy(string setId, double incrBy, byte[] value);
/// <summary>Increment by.</summary>
///
/// <param name="setId"> Identifier for the set.</param>
/// <param name="incrBy">Amount to increment by.</param>
/// <param name="value"> The value.</param>
///
/// <returns>A double.</returns>
double ZIncrBy(string setId, long incrBy, byte[] value);
/// <summary>Z coordinate ranks.</summary>
///
/// <param name="setId">Identifier for the set.</param>
/// <param name="value">The value.</param>
///
/// <returns>A long.</returns>
long ZRank(string setId, byte[] value);
/// <summary>Reverse rank.</summary>
///
/// <param name="setId">Identifier for the set.</param>
/// <param name="value">The value.</param>
///
/// <returns>A long.</returns>
long ZRevRank(string setId, byte[] value);
/// <summary>Z coordinate ranges.</summary>
///
/// <param name="setId">Identifier for the set.</param>
/// <param name="min"> The minimum.</param>
/// <param name="max"> The maximum.</param>
///
/// <returns>A byte[][].</returns>
byte[][] ZRange(string setId, int min, int max);
/// <summary>Range with scores.</summary>
///
/// <param name="setId">Identifier for the set.</param>
/// <param name="min"> The minimum.</param>
/// <param name="max"> The maximum.</param>
///
/// <returns>A byte[][].</returns>
byte[][] ZRangeWithScores(string setId, int min, int max);
/// <summary>Reverse range.</summary>
///
/// <param name="setId">Identifier for the set.</param>
/// <param name="min"> The minimum.</param>
/// <param name="max"> The maximum.</param>
///
/// <returns>A byte[][].</returns>
byte[][] ZRevRange(string setId, int min, int max);
/// <summary>Reverse range with scores.</summary>
///
/// <param name="setId">Identifier for the set.</param>
/// <param name="min"> The minimum.</param>
/// <param name="max"> The maximum.</param>
///
/// <returns>A byte[][].</returns>
byte[][] ZRevRangeWithScores(string setId, int min, int max);
/// <summary>Range by score.</summary>
///
/// <param name="setId">Identifier for the set.</param>
/// <param name="min"> The minimum.</param>
/// <param name="max"> The maximum.</param>
/// <param name="skip"> The skip.</param>
/// <param name="take"> The take.</param>
///
/// <returns>A byte[][].</returns>
byte[][] ZRangeByScore(string setId, double min, double max, int? skip, int? take);
/// <summary>Range by score.</summary>
///
/// <param name="setId">Identifier for the set.</param>
/// <param name="min"> The minimum.</param>
/// <param name="max"> The maximum.</param>
/// <param name="skip"> The skip.</param>
/// <param name="take"> The take.</param>
///
/// <returns>A byte[][].</returns>
byte[][] ZRangeByScore(string setId, long min, long max, int? skip, int? take);
/// <summary>Range by score with scores.</summary>
///
/// <param name="setId">Identifier for the set.</param>
/// <param name="min"> The minimum.</param>
/// <param name="max"> The maximum.</param>
/// <param name="skip"> The skip.</param>
/// <param name="take"> The take.</param>
///
/// <returns>A byte[][].</returns>
byte[][] ZRangeByScoreWithScores(string setId, double min, double max, int? skip, int? take);
/// <summary>Range by score with scores.</summary>
///
/// <param name="setId">Identifier for the set.</param>
/// <param name="min"> The minimum.</param>
/// <param name="max"> The maximum.</param>
/// <param name="skip"> The skip.</param>
/// <param name="take"> The take.</param>
///
/// <returns>A byte[][].</returns>
byte[][] ZRangeByScoreWithScores(string setId, long min, long max, int? skip, int? take);
/// <summary>Reverse range by score.</summary>
///
/// <param name="setId">Identifier for the set.</param>
/// <param name="min"> The minimum.</param>
/// <param name="max"> The maximum.</param>
/// <param name="skip"> The skip.</param>
/// <param name="take"> The take.</param>
///
/// <returns>A byte[][].</returns>
byte[][] ZRevRangeByScore(string setId, double min, double max, int? skip, int? take);
/// <summary>Reverse range by score.</summary>
///
/// <param name="setId">Identifier for the set.</param>
/// <param name="min"> The minimum.</param>
/// <param name="max"> The maximum.</param>
/// <param name="skip"> The skip.</param>
/// <param name="take"> The take.</param>
///
/// <returns>A byte[][].</returns>
byte[][] ZRevRangeByScore(string setId, long min, long max, int? skip, int? take);
/// <summary>Reverse range by score with scores.</summary>
///
/// <param name="setId">Identifier for the set.</param>
/// <param name="min"> The minimum.</param>
/// <param name="max"> The maximum.</param>
/// <param name="skip"> The skip.</param>
/// <param name="take"> The take.</param>
///
/// <returns>A byte[][].</returns>
byte[][] ZRevRangeByScoreWithScores(string setId, double min, double max, int? skip, int? take);
/// <summary>Reverse range by score with scores.</summary>
///
/// <param name="setId">Identifier for the set.</param>
/// <param name="min"> The minimum.</param>
/// <param name="max"> The maximum.</param>
/// <param name="skip"> The skip.</param>
/// <param name="take"> The take.</param>
///
/// <returns>A byte[][].</returns>
byte[][] ZRevRangeByScoreWithScores(string setId, long min, long max, int? skip, int? take);
/// <summary>Rem range by rank.</summary>
///
/// <param name="setId">Identifier for the set.</param>
/// <param name="min"> The minimum.</param>
/// <param name="max"> The maximum.</param>
///
/// <returns>A long.</returns>
long ZRemRangeByRank(string setId, int min, int max);
/// <summary>Rem range by score.</summary>
///
/// <param name="setId"> Identifier for the set.</param>
/// <param name="fromScore">from score.</param>
/// <param name="toScore"> to score.</param>
///
/// <returns>A long.</returns>
long ZRemRangeByScore(string setId, double fromScore, double toScore);
/// <summary>Rem range by score.</summary>
///
/// <param name="setId"> Identifier for the set.</param>
/// <param name="fromScore">from score.</param>
/// <param name="toScore"> to score.</param>
///
/// <returns>A long.</returns>
long ZRemRangeByScore(string setId, long fromScore, long toScore);
/// <summary>Z coordinate cards.</summary>
///
/// <param name="setId">Identifier for the set.</param>
///
/// <returns>A long.</returns>
long ZCard(string setId);
/// <summary>Z coordinate scores.</summary>
///
/// <param name="setId">Identifier for the set.</param>
/// <param name="value">The value.</param>
///
/// <returns>A double.</returns>
double ZScore(string setId, byte[] value);
/// <summary>Union store.</summary>
///
/// <param name="intoSetId">Identifier for the into set.</param>
/// <param name="setIds"> List of identifiers for the sets.</param>
///
/// <returns>A long.</returns>
long ZUnionStore(string intoSetId, params string[] setIds);
/// <summary>Inter store.</summary>
///
/// <param name="intoSetId">Identifier for the into set.</param>
/// <param name="setIds"> List of identifiers for the sets.</param>
///
/// <returns>A long.</returns>
long ZInterStore(string intoSetId, params string[] setIds);
/// <summary>Sets.</summary>
///
/// <param name="hashId">Identifier for the hash.</param>
/// <param name="key"> The key.</param>
/// <param name="value"> The value.</param>
///
/// <returns>A long.</returns>
long HSet(string hashId, byte[] key, byte[] value);
/// <summary>Hm set.</summary>
///
/// <param name="hashId">Identifier for the hash.</param>
/// <param name="keys"> The keys.</param>
/// <param name="values">The values.</param>
void HMSet(string hashId, byte[][] keys, byte[][] values);
/// <summary>Sets a nx.</summary>
///
/// <param name="hashId">Identifier for the hash.</param>
/// <param name="key"> The key.</param>
/// <param name="value"> The value.</param>
///
/// <returns>A long.</returns>
long HSetNX(string hashId, byte[] key, byte[] value);
/// <summary>Incrbies.</summary>
///
/// <param name="hashId"> Identifier for the hash.</param>
/// <param name="key"> The key.</param>
/// <param name="incrementBy">Amount to increment by.</param>
///
/// <returns>A long.</returns>
long HIncrby(string hashId, byte[] key, int incrementBy);
/// <summary>Incrby float.</summary>
///
/// <param name="hashId"> Identifier for the hash.</param>
/// <param name="key"> The key.</param>
/// <param name="incrementBy">Amount to increment by.</param>
///
/// <returns>A double.</returns>
double HIncrbyFloat(string hashId, byte[] key, double incrementBy);
/// <summary>Gets.</summary>
///
/// <param name="hashId">Identifier for the hash.</param>
/// <param name="key"> The key.</param>
///
/// <returns>A byte[].</returns>
byte[] HGet(string hashId, byte[] key);
/// <summary>Hm get.</summary>
///
/// <param name="hashId"> Identifier for the hash.</param>
/// <param name="keysAndArgs">A variable-length parameters list containing keys and arguments.</param>
///
/// <returns>A byte[][].</returns>
byte[][] HMGet(string hashId, params byte[][] keysAndArgs);
/// <summary>Deletes this object.</summary>
///
/// <param name="hashId">Identifier for the hash.</param>
/// <param name="key"> The key.</param>
///
/// <returns>A long.</returns>
long HDel(string hashId, byte[] key);
/// <summary>Exists.</summary>
///
/// <param name="hashId">Identifier for the hash.</param>
/// <param name="key"> The key.</param>
///
/// <returns>A long.</returns>
long HExists(string hashId, byte[] key);
/// <summary>Lens.</summary>
///
/// <param name="hashId">Identifier for the hash.</param>
///
/// <returns>A long.</returns>
long HLen(string hashId);
/// <summary>Keys.</summary>
///
/// <param name="hashId">Identifier for the hash.</param>
///
/// <returns>A byte[][].</returns>
byte[][] HKeys(string hashId);
/// <summary>Vals.</summary>
///
/// <param name="hashId">Identifier for the hash.</param>
///
/// <returns>A byte[][].</returns>
byte[][] HVals(string hashId);
/// <summary>Gets all.</summary>
///
/// <param name="hashId">Identifier for the hash.</param>
///
/// <returns>An array of byte[].</returns>
byte[][] HGetAll(string hashId);
/// <summary>Watches the given keys.</summary>
///
/// <param name="keys">The keys.</param>
void Watch(params string[] keys);
/// <summary>Un watch.</summary>
void UnWatch();
/// <summary>Publishes.</summary>
///
/// <param name="toChannel">to channel.</param>
/// <param name="message"> The message.</param>
///
/// <returns>A long.</returns>
long Publish(string toChannel, byte[] message);
/// <summary>Subscribes the given to channels.</summary>
///
/// <param name="toChannels">A variable-length parameters list containing to channels.</param>
///
/// <returns>A byte[][].</returns>
byte[][] Subscribe(params string[] toChannels);
/// <summary>Un subscribe.</summary>
///
/// <param name="toChannels">A variable-length parameters list containing to channels.</param>
///
/// <returns>A byte[][].</returns>
byte[][] UnSubscribe(params string[] toChannels);
/// <summary>Subscribes the given to channels matching patterns.</summary>
///
/// <param name="toChannelsMatchingPatterns">A variable-length parameters list containing to channels matching patterns.</param>
///
/// <returns>A byte[][].</returns>
byte[][] PSubscribe(params string[] toChannelsMatchingPatterns);
/// <summary>Un subscribe.</summary>
///
/// <param name="toChannelsMatchingPatterns">A variable-length parameters list containing to channels matching patterns.</param>
///
/// <returns>A byte[][].</returns>
byte[][] PUnSubscribe(params string[] toChannelsMatchingPatterns);
/// <summary>Receive messages.</summary>
///
/// <returns>A byte[][].</returns>
byte[][] ReceiveMessages();
/// <summary>Redis LUA support.</summary>
///
/// <param name="luaBody"> The lua body.</param>
/// <param name="numberOfKeys">Number of keys.</param>
/// <param name="keysAndArgs"> A variable-length parameters list containing keys and arguments.</param>
///
/// <returns>A long.</returns>
long EvalInt(string luaBody, int numberOfKeys, params byte[][] keysAndArgs);
/// <summary>Eval sha int.</summary>
///
/// <param name="sha1"> The first sha.</param>
/// <param name="numberOfKeys">Number of keys.</param>
/// <param name="keysAndArgs"> A variable-length parameters list containing keys and arguments.</param>
///
/// <returns>A long.</returns>
long EvalShaInt(string sha1, int numberOfKeys, params byte[][] keysAndArgs);
/// <summary>Eval string.</summary>
///
/// <param name="luaBody"> The lua body.</param>
/// <param name="numberOfKeys">Number of keys.</param>
/// <param name="keysAndArgs"> A variable-length parameters list containing keys and arguments.</param>
///
/// <returns>A string.</returns>
string EvalStr(string luaBody, int numberOfKeys, params byte[][] keysAndArgs);
/// <summary>Eval sha string.</summary>
///
/// <param name="sha1"> The first sha.</param>
/// <param name="numberOfKeys">Number of keys.</param>
/// <param name="keysAndArgs"> A variable-length parameters list containing keys and arguments.</param>
///
/// <returns>A string.</returns>
string EvalShaStr(string sha1, int numberOfKeys, params byte[][] keysAndArgs);
/// <summary>Evals.</summary>
///
/// <param name="luaBody"> The lua body.</param>
/// <param name="numberOfKeys">Number of keys.</param>
/// <param name="keysAndArgs"> A variable-length parameters list containing keys and arguments.</param>
///
/// <returns>A byte[][].</returns>
byte[][] Eval(string luaBody, int numberOfKeys, params byte[][] keysAndArgs);
/// <summary>Eval sha.</summary>
///
/// <param name="sha1"> The first sha.</param>
/// <param name="numberOfKeys">Number of keys.</param>
/// <param name="keysAndArgs"> A variable-length parameters list containing keys and arguments.</param>
///
/// <returns>A byte[][].</returns>
byte[][] EvalSha(string sha1, int numberOfKeys, params byte[][] keysAndArgs);
/// <summary>Calculates the sha 1.</summary>
///
/// <param name="luaBody">The lua body.</param>
///
/// <returns>The calculated sha 1.</returns>
string CalculateSha1(string luaBody);
/// <summary>Queries if a given script exists.</summary>
///
/// <param name="sha1Refs">A variable-length parameters list containing sha 1 references.</param>
///
/// <returns>A byte[][].</returns>
byte[][] ScriptExists(params byte[][] sha1Refs);
/// <summary>Script flush.</summary>
void ScriptFlush();
/// <summary>Script kill.</summary>
void ScriptKill();
/// <summary>Script load.</summary>
///
/// <param name="body">The body.</param>
///
/// <returns>A byte[].</returns>
byte[] ScriptLoad(string body);
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CocosSharp;
using System.Diagnostics;
using Microsoft.Xna.Framework.Graphics;
namespace tests
{
public class ParticleMainScene : CCScene
{
public ParticleMainScene() : base(AppDelegate.SharedWindow)
{
}
public virtual void initWithSubTest(int asubtest, int particles)
{
//srandom(0);
subtestNumber = asubtest;
CCSize s = Layer.VisibleBoundsWorldspace.Size;
lastRenderedCount = 0;
quantityParticles = particles;
CCMenuItemFont.FontSize = 64;
CCMenuItemFont.FontName = "arial";
CCMenuItemFont decrease = new CCMenuItemFont(" - ", onDecrease);
decrease.Color = new CCColor3B(0, 200, 20);
CCMenuItemFont increase = new CCMenuItemFont(" + ", onIncrease);
increase.Color = new CCColor3B(0, 200, 20);
CCMenu menu = new CCMenu(decrease, increase);
menu.AlignItemsHorizontally();
menu.Position = new CCPoint(s.Width / 2, s.Height / 2 + 15);
AddChild(menu, 1);
CCLabelTtf infoLabel = new CCLabelTtf("0 nodes", "Marker Felt", 30);
infoLabel.Color = new CCColor3B(0, 200, 20);
infoLabel.Position = new CCPoint(s.Width / 2, s.Height - 90);
AddChild(infoLabel, 1, PerformanceParticleTest.kTagInfoLayer);
// particles on stage
CCLabelAtlas labelAtlas = new CCLabelAtlas("0000", "Images/fps_Images", 12, 32, '.');
AddChild(labelAtlas, 0, PerformanceParticleTest.kTagLabelAtlas);
labelAtlas.Position = new CCPoint(s.Width - 66, 50);
// Next Prev Test
ParticleMenuLayer pMenu = new ParticleMenuLayer(true, PerformanceParticleTest.TEST_COUNT, PerformanceParticleTest.s_nParCurIdx);
AddChild(pMenu, 1, PerformanceParticleTest.kTagMenuLayer);
// Sub Tests
CCMenuItemFont.FontSize = 38;
CCMenuItemFont.FontName = "arial";
CCMenu pSubMenu = new CCMenu(null);
for (int i = 1; i <= 6; ++i)
{
//char str[10] = {0};
string str;
//sprintf(str, "%d ", i);
str = string.Format("{0:G}", i);
CCMenuItemFont itemFont = new CCMenuItemFont(str, testNCallback);
itemFont.Tag = i;
pSubMenu.AddChild(itemFont, 10);
if (i <= 3)
{
itemFont.Color = new CCColor3B(200, 20, 20);
}
else
{
itemFont.Color = new CCColor3B(0, 200, 20);
}
}
pSubMenu.AlignItemsHorizontally();
pSubMenu.Position = new CCPoint(s.Width / 2, 80);
AddChild(pSubMenu, 2);
CCLabelTtf label = new CCLabelTtf(title(), "arial", 38);
AddChild(label, 1);
label.Position = new CCPoint(s.Width / 2, s.Height - 32);
label.Color = new CCColor3B(255, 255, 40);
updateQuantityLabel();
createParticleSystem();
Schedule(step);
}
public virtual string title()
{
return "No title";
}
public void step(float dt)
{
CCLabelAtlas atlas = (CCLabelAtlas)GetChildByTag(PerformanceParticleTest.kTagLabelAtlas);
CCParticleSystem emitter = (CCParticleSystem)GetChildByTag(PerformanceParticleTest.kTagParticleSystem);
var str = string.Format("{0:0000}", emitter.ParticleCount);
atlas.Text = (str);
}
public void createParticleSystem()
{
CCParticleSystem particleSystem = null;
/*
* Tests:
* 1: Point Particle System using 32-bit textures (PNG)
* 2: Point Particle System using 16-bit textures (PNG)
* 3: Point Particle System using 8-bit textures (PNG)
* 4: Point Particle System using 4-bit textures (PVRTC)
* 5: Quad Particle System using 32-bit textures (PNG)
* 6: Quad Particle System using 16-bit textures (PNG)
* 7: Quad Particle System using 8-bit textures (PNG)
* 8: Quad Particle System using 4-bit textures (PVRTC)
*/
RemoveChildByTag(PerformanceParticleTest.kTagParticleSystem, true);
// remove the "fire.png" from the TextureCache cache.
CCTexture2D texture = CCTextureCache.SharedTextureCache.AddImage("Images/fire");
CCTextureCache.SharedTextureCache.RemoveTexture(texture);
particleSystem = new CCParticleSystemQuad(quantityParticles);
switch (subtestNumber)
{
case 1:
CCTexture2D.DefaultAlphaPixelFormat = CCSurfaceFormat.Color;
particleSystem.Texture = CCTextureCache.SharedTextureCache.AddImage("Images/fire");
break;
case 2:
CCTexture2D.DefaultAlphaPixelFormat = CCSurfaceFormat.Bgra4444;
particleSystem.Texture = CCTextureCache.SharedTextureCache.AddImage("Images/fire");
break;
case 3:
CCTexture2D.DefaultAlphaPixelFormat = CCSurfaceFormat.Alpha8;
particleSystem.Texture = CCTextureCache.SharedTextureCache.AddImage("Images/fire");
break;
// case 4:
// particleSystem->initWithTotalParticles(quantityParticles);
// ////---- particleSystem.texture = [[CCTextureCache sharedTextureCache] addImage:@"fire.pvr"];
// particleSystem->setTexture(CCTextureCache::sharedTextureCache()->addImage("Images/fire.png"));
// break;
case 4:
CCTexture2D.DefaultAlphaPixelFormat = CCSurfaceFormat.Color;
particleSystem.Texture = CCTextureCache.SharedTextureCache.AddImage("Images/fire");
break;
case 5:
CCTexture2D.DefaultAlphaPixelFormat = CCSurfaceFormat.Bgra4444;
particleSystem.Texture = CCTextureCache.SharedTextureCache.AddImage("Images/fire");
break;
case 6:
CCTexture2D.DefaultAlphaPixelFormat = CCSurfaceFormat.Alpha8;
particleSystem.Texture = CCTextureCache.SharedTextureCache.AddImage("Images/fire");
break;
// case 8:
// particleSystem->initWithTotalParticles(quantityParticles);
// ////---- particleSystem.texture = [[CCTextureCache sharedTextureCache] addImage:@"fire.pvr"];
// particleSystem->setTexture(CCTextureCache::sharedTextureCache()->addImage("Images/fire.png"));
// break;
default:
particleSystem = null;
CCLog.Log("Shall not happen!");
break;
}
AddChild(particleSystem, 0, PerformanceParticleTest.kTagParticleSystem);
doTest();
// restore the default pixel format
CCTexture2D.DefaultAlphaPixelFormat = CCSurfaceFormat.Color;
}
public void onDecrease(object pSender)
{
quantityParticles -= PerformanceParticleTest.kNodesIncrease;
if (quantityParticles < 0)
quantityParticles = 0;
updateQuantityLabel();
createParticleSystem();
}
public void onIncrease(object pSender)
{
quantityParticles += PerformanceParticleTest.kNodesIncrease;
if (quantityParticles > PerformanceParticleTest.kMaxParticles)
quantityParticles = PerformanceParticleTest.kMaxParticles;
updateQuantityLabel();
createParticleSystem();
}
public void testNCallback(object pSender)
{
subtestNumber = ((CCNode)pSender).Tag;
ParticleMenuLayer pMenu = (ParticleMenuLayer)GetChildByTag(PerformanceParticleTest.kTagMenuLayer);
pMenu.restartCallback(pSender);
}
public void updateQuantityLabel()
{
if (quantityParticles != lastRenderedCount)
{
CCLabelTtf infoLabel = (CCLabelTtf)GetChildByTag(PerformanceParticleTest.kTagInfoLayer);
string str = string.Format("{0} particles", quantityParticles);
infoLabel.Text = (str);
lastRenderedCount = quantityParticles;
}
}
public int getSubTestNum()
{
return subtestNumber;
}
public int getParticlesNum()
{
return quantityParticles;
}
public virtual void doTest()
{
throw new NotFiniteNumberException();
}
protected int lastRenderedCount;
protected int quantityParticles;
protected int subtestNumber;
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Apis.PolicyTroubleshooter.v1beta
{
/// <summary>The PolicyTroubleshooter Service.</summary>
public class PolicyTroubleshooterService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1beta";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public PolicyTroubleshooterService() : this(new Google.Apis.Services.BaseClientService.Initializer())
{
}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public PolicyTroubleshooterService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer)
{
Iam = new IamResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features => new string[0];
/// <summary>Gets the service name.</summary>
public override string Name => "policytroubleshooter";
/// <summary>Gets the service base URI.</summary>
public override string BaseUri =>
#if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45
BaseUriOverride ?? "https://policytroubleshooter.googleapis.com/";
#else
"https://policytroubleshooter.googleapis.com/";
#endif
/// <summary>Gets the service base path.</summary>
public override string BasePath => "";
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri => "https://policytroubleshooter.googleapis.com/batch";
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath => "batch";
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Policy Troubleshooter API.</summary>
public class Scope
{
/// <summary>
/// See, edit, configure, and delete your Google Cloud data and see the email address for your Google
/// Account.
/// </summary>
public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
}
/// <summary>Available OAuth 2.0 scope constants for use with the Policy Troubleshooter API.</summary>
public static class ScopeConstants
{
/// <summary>
/// See, edit, configure, and delete your Google Cloud data and see the email address for your Google
/// Account.
/// </summary>
public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
}
/// <summary>Gets the Iam resource.</summary>
public virtual IamResource Iam { get; }
}
/// <summary>A base abstract class for PolicyTroubleshooter requests.</summary>
public abstract class PolicyTroubleshooterBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
/// <summary>Constructs a new PolicyTroubleshooterBaseServiceRequest instance.</summary>
protected PolicyTroubleshooterBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1 = 0,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2 = 1,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json = 0,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media = 1,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto = 2,
}
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>
/// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required
/// unless you provide an OAuth 2.0 token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>
/// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a
/// user, but should not exceed 40 characters.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes PolicyTroubleshooter parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "iam" collection of methods.</summary>
public class IamResource
{
private const string Resource = "iam";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public IamResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>
/// Checks whether a member has a specific permission for a specific resource, and explains why the member does
/// or does not have that permission.
/// </summary>
/// <param name="body">The body of the request.</param>
public virtual TroubleshootRequest Troubleshoot(Google.Apis.PolicyTroubleshooter.v1beta.Data.GoogleCloudPolicytroubleshooterV1betaTroubleshootIamPolicyRequest body)
{
return new TroubleshootRequest(service, body);
}
/// <summary>
/// Checks whether a member has a specific permission for a specific resource, and explains why the member does
/// or does not have that permission.
/// </summary>
public class TroubleshootRequest : PolicyTroubleshooterBaseServiceRequest<Google.Apis.PolicyTroubleshooter.v1beta.Data.GoogleCloudPolicytroubleshooterV1betaTroubleshootIamPolicyResponse>
{
/// <summary>Constructs a new Troubleshoot request.</summary>
public TroubleshootRequest(Google.Apis.Services.IClientService service, Google.Apis.PolicyTroubleshooter.v1beta.Data.GoogleCloudPolicytroubleshooterV1betaTroubleshootIamPolicyRequest body) : base(service)
{
Body = body;
InitParameters();
}
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.PolicyTroubleshooter.v1beta.Data.GoogleCloudPolicytroubleshooterV1betaTroubleshootIamPolicyRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "troubleshoot";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta/iam:troubleshoot";
/// <summary>Initializes Troubleshoot parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
}
}
namespace Google.Apis.PolicyTroubleshooter.v1beta.Data
{
/// <summary>Information about the member, resource, and permission to check.</summary>
public class GoogleCloudPolicytroubleshooterV1betaAccessTuple : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Required. The full resource name that identifies the resource. For example,
/// `//compute.googleapis.com/projects/my-project/zones/us-central1-a/instances/my-instance`. For examples of
/// full resource names for Google Cloud services, see
/// https://cloud.google.com/iam/help/troubleshooter/full-resource-names.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("fullResourceName")]
public virtual string FullResourceName { get; set; }
/// <summary>
/// Required. The IAM permission to check for the specified member and resource. For a complete list of IAM
/// permissions, see https://cloud.google.com/iam/help/permissions/reference. For a complete list of predefined
/// IAM roles and the permissions in each role, see https://cloud.google.com/iam/help/roles/reference.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("permission")]
public virtual string Permission { get; set; }
/// <summary>
/// Required. The member, or principal, whose access you want to check, in the form of the email address that
/// represents that member. For example, `alice@example.com` or
/// `my-service-account@my-project.iam.gserviceaccount.com`. The member must be a Google Account or a service
/// account. Other types of members are not supported.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("principal")]
public virtual string Principal { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Details about how a binding in a policy affects a member's ability to use a permission.</summary>
public class GoogleCloudPolicytroubleshooterV1betaBindingExplanation : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Indicates whether _this binding_ provides the specified permission to the specified member for the specified
/// resource. This field does _not_ indicate whether the member actually has the permission for the resource.
/// There might be another binding that overrides this binding. To determine whether the member actually has the
/// permission, use the `access` field in the TroubleshootIamPolicyResponse.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("access")]
public virtual string Access { get; set; }
/// <summary>
/// A condition expression that prevents access unless the expression evaluates to `true`. To learn about IAM
/// Conditions, see http://cloud.google.com/iam/help/conditions/overview.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("condition")]
public virtual GoogleTypeExpr Condition { get; set; }
/// <summary>
/// Indicates whether each member in the binding includes the member specified in the request, either directly
/// or indirectly. Each key identifies a member in the binding, and each value indicates whether the member in
/// the binding includes the member in the request. For example, suppose that a binding includes the following
/// members: * `user:alice@example.com` * `group:product-eng@example.com` You want to troubleshoot access for
/// `user:bob@example.com`. This user is a member of the group `group:product-eng@example.com`. For the first
/// member in the binding, the key is `user:alice@example.com`, and the `membership` field in the value is set
/// to `MEMBERSHIP_NOT_INCLUDED`. For the second member in the binding, the key is
/// `group:product-eng@example.com`, and the `membership` field in the value is set to `MEMBERSHIP_INCLUDED`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("memberships")]
public virtual System.Collections.Generic.IDictionary<string, GoogleCloudPolicytroubleshooterV1betaBindingExplanationAnnotatedMembership> Memberships { get; set; }
/// <summary>The relevance of this binding to the overall determination for the entire policy.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("relevance")]
public virtual string Relevance { get; set; }
/// <summary>
/// The role that this binding grants. For example, `roles/compute.serviceAgent`. For a complete list of
/// predefined IAM roles, as well as the permissions in each role, see
/// https://cloud.google.com/iam/help/roles/reference.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("role")]
public virtual string Role { get; set; }
/// <summary>Indicates whether the role granted by this binding contains the specified permission.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("rolePermission")]
public virtual string RolePermission { get; set; }
/// <summary>
/// The relevance of the permission's existence, or nonexistence, in the role to the overall determination for
/// the entire policy.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("rolePermissionRelevance")]
public virtual string RolePermissionRelevance { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Details about whether the binding includes the member.</summary>
public class GoogleCloudPolicytroubleshooterV1betaBindingExplanationAnnotatedMembership : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Indicates whether the binding includes the member.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("membership")]
public virtual string Membership { get; set; }
/// <summary>The relevance of the member's status to the overall determination for the binding.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("relevance")]
public virtual string Relevance { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Details about how a specific IAM Policy contributed to the access check.</summary>
public class GoogleCloudPolicytroubleshooterV1betaExplainedPolicy : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Indicates whether _this policy_ provides the specified permission to the specified member for the specified
/// resource. This field does _not_ indicate whether the member actually has the permission for the resource.
/// There might be another policy that overrides this policy. To determine whether the member actually has the
/// permission, use the `access` field in the TroubleshootIamPolicyResponse.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("access")]
public virtual string Access { get; set; }
/// <summary>
/// Details about how each binding in the policy affects the member's ability, or inability, to use the
/// permission for the resource. If the sender of the request does not have access to the policy, this field is
/// omitted.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("bindingExplanations")]
public virtual System.Collections.Generic.IList<GoogleCloudPolicytroubleshooterV1betaBindingExplanation> BindingExplanations { get; set; }
/// <summary>
/// The full resource name that identifies the resource. For example,
/// `//compute.googleapis.com/projects/my-project/zones/us-central1-a/instances/my-instance`. If the sender of
/// the request does not have access to the policy, this field is omitted. For examples of full resource names
/// for Google Cloud services, see https://cloud.google.com/iam/help/troubleshooter/full-resource-names.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("fullResourceName")]
public virtual string FullResourceName { get; set; }
/// <summary>
/// The IAM policy attached to the resource. If the sender of the request does not have access to the policy,
/// this field is empty.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("policy")]
public virtual GoogleIamV1Policy Policy { get; set; }
/// <summary>
/// The relevance of this policy to the overall determination in the TroubleshootIamPolicyResponse. If the
/// sender of the request does not have access to the policy, this field is omitted.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("relevance")]
public virtual string Relevance { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request for TroubleshootIamPolicy.</summary>
public class GoogleCloudPolicytroubleshooterV1betaTroubleshootIamPolicyRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The information to use for checking whether a member has a permission for a resource.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("accessTuple")]
public virtual GoogleCloudPolicytroubleshooterV1betaAccessTuple AccessTuple { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response for TroubleshootIamPolicy.</summary>
public class GoogleCloudPolicytroubleshooterV1betaTroubleshootIamPolicyResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Indicates whether the member has the specified permission for the specified resource, based on evaluating
/// all of the applicable policies.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("access")]
public virtual string Access { get; set; }
/// <summary>
/// List of IAM policies that were evaluated to check the member's permissions, with annotations to indicate how
/// each policy contributed to the final result. The list of policies can include the policy for the resource
/// itself. It can also include policies that are inherited from higher levels of the resource hierarchy,
/// including the organization, the folder, and the project. To learn more about the resource hierarchy, see
/// https://cloud.google.com/iam/help/resource-hierarchy.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("explainedPolicies")]
public virtual System.Collections.Generic.IList<GoogleCloudPolicytroubleshooterV1betaExplainedPolicy> ExplainedPolicies { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Specifies the audit configuration for a service. The configuration determines which permission types are logged,
/// and what identities, if any, are exempted from logging. An AuditConfig must have one or more AuditLogConfigs. If
/// there are AuditConfigs for both `allServices` and a specific service, the union of the two AuditConfigs is used
/// for that service: the log_types specified in each AuditConfig are enabled, and the exempted_members in each
/// AuditLogConfig are exempted. Example Policy with multiple AuditConfigs: { "audit_configs": [ { "service":
/// "allServices", "audit_log_configs": [ { "log_type": "DATA_READ", "exempted_members": [ "user:jose@example.com" ]
/// }, { "log_type": "DATA_WRITE" }, { "log_type": "ADMIN_READ" } ] }, { "service": "sampleservice.googleapis.com",
/// "audit_log_configs": [ { "log_type": "DATA_READ" }, { "log_type": "DATA_WRITE", "exempted_members": [
/// "user:aliya@example.com" ] } ] } ] } For sampleservice, this policy enables DATA_READ, DATA_WRITE and ADMIN_READ
/// logging. It also exempts jose@example.com from DATA_READ logging, and aliya@example.com from DATA_WRITE logging.
/// </summary>
public class GoogleIamV1AuditConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The configuration for logging of each type of permission.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("auditLogConfigs")]
public virtual System.Collections.Generic.IList<GoogleIamV1AuditLogConfig> AuditLogConfigs { get; set; }
/// <summary>
/// Specifies a service that will be enabled for audit logging. For example, `storage.googleapis.com`,
/// `cloudsql.googleapis.com`. `allServices` is a special value that covers all services.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("service")]
public virtual string Service { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Provides the configuration for logging a type of permissions. Example: { "audit_log_configs": [ { "log_type":
/// "DATA_READ", "exempted_members": [ "user:jose@example.com" ] }, { "log_type": "DATA_WRITE" } ] } This enables
/// 'DATA_READ' and 'DATA_WRITE' logging, while exempting jose@example.com from DATA_READ logging.
/// </summary>
public class GoogleIamV1AuditLogConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Specifies the identities that do not cause logging for this type of permission. Follows the same format of
/// Binding.members.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("exemptedMembers")]
public virtual System.Collections.Generic.IList<string> ExemptedMembers { get; set; }
/// <summary>The log type that this config enables.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("logType")]
public virtual string LogType { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Associates `members` with a `role`.</summary>
public class GoogleIamV1Binding : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The condition that is associated with this binding. If the condition evaluates to `true`, then this binding
/// applies to the current request. If the condition evaluates to `false`, then this binding does not apply to
/// the current request. However, a different role binding might grant the same role to one or more of the
/// members in this binding. To learn which resources support conditions in their IAM policies, see the [IAM
/// documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("condition")]
public virtual GoogleTypeExpr Condition { get; set; }
/// <summary>
/// Specifies the identities requesting access for a Cloud Platform resource. `members` can have the following
/// values: * `allUsers`: A special identifier that represents anyone who is on the internet; with or without a
/// Google account. * `allAuthenticatedUsers`: A special identifier that represents anyone who is authenticated
/// with a Google account or a service account. * `user:{emailid}`: An email address that represents a specific
/// Google account. For example, `alice@example.com` . * `serviceAccount:{emailid}`: An email address that
/// represents a service account. For example, `my-other-app@appspot.gserviceaccount.com`. * `group:{emailid}`:
/// An email address that represents a Google group. For example, `admins@example.com`. *
/// `deleted:user:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a user that
/// has been recently deleted. For example, `alice@example.com?uid=123456789012345678901`. If the user is
/// recovered, this value reverts to `user:{emailid}` and the recovered user retains the role in the binding. *
/// `deleted:serviceAccount:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a
/// service account that has been recently deleted. For example,
/// `my-other-app@appspot.gserviceaccount.com?uid=123456789012345678901`. If the service account is undeleted,
/// this value reverts to `serviceAccount:{emailid}` and the undeleted service account retains the role in the
/// binding. * `deleted:group:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing
/// a Google group that has been recently deleted. For example, `admins@example.com?uid=123456789012345678901`.
/// If the group is recovered, this value reverts to `group:{emailid}` and the recovered group retains the role
/// in the binding. * `domain:{domain}`: The G Suite domain (primary) that represents all the users of that
/// domain. For example, `google.com` or `example.com`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("members")]
public virtual System.Collections.Generic.IList<string> Members { get; set; }
/// <summary>
/// Role that is assigned to `members`. For example, `roles/viewer`, `roles/editor`, or `roles/owner`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("role")]
public virtual string Role { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// An Identity and Access Management (IAM) policy, which specifies access controls for Google Cloud resources. A
/// `Policy` is a collection of `bindings`. A `binding` binds one or more `members` to a single `role`. Members can
/// be user accounts, service accounts, Google groups, and domains (such as G Suite). A `role` is a named list of
/// permissions; each `role` can be an IAM predefined role or a user-created custom role. For some types of Google
/// Cloud resources, a `binding` can also specify a `condition`, which is a logical expression that allows access to
/// a resource only if the expression evaluates to `true`. A condition can add constraints based on attributes of
/// the request, the resource, or both. To learn which resources support conditions in their IAM policies, see the
/// [IAM documentation](https://cloud.google.com/iam/help/conditions/resource-policies). **JSON example:** {
/// "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com",
/// "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] },
/// { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": {
/// "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time
/// &lt; timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 } **YAML example:**
/// bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com -
/// serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin -
/// members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable
/// access description: Does not grant access after Sep 2020 expression: request.time &lt;
/// timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3 For a description of IAM and its features,
/// see the [IAM documentation](https://cloud.google.com/iam/docs/).
/// </summary>
public class GoogleIamV1Policy : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Specifies cloud audit logging configuration for this policy.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("auditConfigs")]
public virtual System.Collections.Generic.IList<GoogleIamV1AuditConfig> AuditConfigs { get; set; }
/// <summary>
/// Associates a list of `members` to a `role`. Optionally, may specify a `condition` that determines how and
/// when the `bindings` are applied. Each of the `bindings` must contain at least one member. The `bindings` in
/// a `Policy` can refer to up to 1,500 members; up to 250 of these members can be Google groups. Each
/// occurrence of a member counts towards these limits. For example, if the `bindings` grant 50 different roles
/// to `user:alice@example.com`, and not to any other member, then you can add another 1,450 members to the
/// `bindings` in the `Policy`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("bindings")]
public virtual System.Collections.Generic.IList<GoogleIamV1Binding> Bindings { get; set; }
/// <summary>
/// `etag` is used for optimistic concurrency control as a way to help prevent simultaneous updates of a policy
/// from overwriting each other. It is strongly suggested that systems make use of the `etag` in the
/// read-modify-write cycle to perform policy updates in order to avoid race conditions: An `etag` is returned
/// in the response to `getIamPolicy`, and systems are expected to put that etag in the request to
/// `setIamPolicy` to ensure that their change will be applied to the same version of the policy. **Important:**
/// If you use IAM Conditions, you must include the `etag` field whenever you call `setIamPolicy`. If you omit
/// this field, then IAM allows you to overwrite a version `3` policy with a version `1` policy, and all of the
/// conditions in the version `3` policy are lost.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>
/// Specifies the format of the policy. Valid values are `0`, `1`, and `3`. Requests that specify an invalid
/// value are rejected. Any operation that affects conditional role bindings must specify version `3`. This
/// requirement applies to the following operations: * Getting a policy that includes a conditional role binding
/// * Adding a conditional role binding to a policy * Changing a conditional role binding in a policy * Removing
/// any role binding, with or without a condition, from a policy that includes conditions **Important:** If you
/// use IAM Conditions, you must include the `etag` field whenever you call `setIamPolicy`. If you omit this
/// field, then IAM allows you to overwrite a version `3` policy with a version `1` policy, and all of the
/// conditions in the version `3` policy are lost. If a policy does not include any conditions, operations on
/// that policy may specify any valid version or leave the field unset. To learn which resources support
/// conditions in their IAM policies, see the [IAM
/// documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("version")]
public virtual System.Nullable<int> Version { get; set; }
}
/// <summary>
/// Represents a textual expression in the Common Expression Language (CEL) syntax. CEL is a C-like expression
/// language. The syntax and semantics of CEL are documented at https://github.com/google/cel-spec. Example
/// (Comparison): title: "Summary size limit" description: "Determines if a summary is less than 100 chars"
/// expression: "document.summary.size() &lt; 100" Example (Equality): title: "Requestor is owner" description:
/// "Determines if requestor is the document owner" expression: "document.owner == request.auth.claims.email"
/// Example (Logic): title: "Public documents" description: "Determine whether the document should be publicly
/// visible" expression: "document.type != 'private' &amp;&amp; document.type != 'internal'" Example (Data
/// Manipulation): title: "Notification string" description: "Create a notification string with a timestamp."
/// expression: "'New message received at ' + string(document.create_time)" The exact variables and functions that
/// may be referenced within an expression are determined by the service that evaluates it. See the service
/// documentation for additional information.
/// </summary>
public class GoogleTypeExpr : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Optional. Description of the expression. This is a longer text which describes the expression, e.g. when
/// hovered over it in a UI.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("description")]
public virtual string Description { get; set; }
/// <summary>Textual representation of an expression in Common Expression Language syntax.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("expression")]
public virtual string Expression { get; set; }
/// <summary>
/// Optional. String indicating the location of the expression for error reporting, e.g. a file name and a
/// position in the file.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("location")]
public virtual string Location { get; set; }
/// <summary>
/// Optional. Title for the expression, i.e. a short string describing its purpose. This can be used e.g. in UIs
/// which allow to enter the expression.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("title")]
public virtual string Title { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Controllers
{
public class DefaultControllerFactoryTest
{
[Fact]
public void CreateController_UsesControllerActivatorToInstantiateController()
{
// Arrange
var expected = new MyController();
var actionDescriptor = new ControllerActionDescriptor
{
ControllerTypeInfo = typeof(MyController).GetTypeInfo()
};
var context = new ControllerContext()
{
ActionDescriptor = actionDescriptor,
HttpContext = new DefaultHttpContext()
{
RequestServices = GetServices(),
},
};
var activator = new Mock<IControllerActivator>();
activator.Setup(a => a.Create(context))
.Returns(expected)
.Verifiable();
var controllerFactory = CreateControllerFactory(activator.Object);
// Act
var result = controllerFactory.CreateController(context);
// Assert
var controller = Assert.IsType<MyController>(result);
Assert.Same(expected, controller);
activator.Verify();
}
[Fact]
public void CreateController_SetsPropertiesFromActionContextHierarchy()
{
// Arrange
var actionDescriptor = new ControllerActionDescriptor
{
ControllerTypeInfo = typeof(ControllerWithAttributes).GetTypeInfo()
};
var context = new ControllerContext()
{
ActionDescriptor = actionDescriptor,
HttpContext = new DefaultHttpContext()
{
RequestServices = GetServices(),
},
};
var factory = CreateControllerFactory(new DefaultControllerActivator(new TypeActivatorCache()));
// Act
var result = factory.CreateController(context);
// Assert
var controller = Assert.IsType<ControllerWithAttributes>(result);
Assert.Same(context, controller.ActionContext);
}
[Fact]
public void CreateController_SetsControllerContext()
{
// Arrange
var actionDescriptor = new ControllerActionDescriptor
{
ControllerTypeInfo = typeof(ControllerWithAttributes).GetTypeInfo()
};
var context = new ControllerContext()
{
ActionDescriptor = actionDescriptor,
HttpContext = new DefaultHttpContext()
{
RequestServices = GetServices(),
},
};
var factory = CreateControllerFactory(new DefaultControllerActivator(new TypeActivatorCache()));
// Act
var result = factory.CreateController(context);
// Assert
var controller = Assert.IsType<ControllerWithAttributes>(result);
Assert.Same(context, controller.ControllerContext);
}
[Fact]
public void CreateController_IgnoresPropertiesThatAreNotDecoratedWithAttribute()
{
// Arrange
var actionDescriptor = new ControllerActionDescriptor
{
ControllerTypeInfo = typeof(ControllerWithoutAttributes).GetTypeInfo()
};
var context = new ControllerContext()
{
ActionDescriptor = actionDescriptor,
HttpContext = new DefaultHttpContext()
{
RequestServices = GetServices(),
},
};
var factory = CreateControllerFactory(new DefaultControllerActivator(new TypeActivatorCache()));
// Act
var result = factory.CreateController(context);
// Assert
var controller = Assert.IsType<ControllerWithoutAttributes>(result);
Assert.Null(controller.ActionContext);
}
[Fact]
public void CreateController_IgnoresNonPublicProperties()
{
// Arrange
var actionDescriptor = new ControllerActionDescriptor
{
ControllerTypeInfo = typeof(ControllerWithNonVisibleProperties).GetTypeInfo()
};
var context = new ControllerContext()
{
ActionDescriptor = actionDescriptor,
HttpContext = new DefaultHttpContext()
{
RequestServices = GetServices(),
},
};
var factory = CreateControllerFactory(new DefaultControllerActivator(new TypeActivatorCache()));
// Act
var result = factory.CreateController(context);
// Assert
var controller = Assert.IsType<ControllerWithNonVisibleProperties>(result);
Assert.Null(controller.ActionContext);
Assert.Null(controller.ControllerContext);
}
[Fact]
public void CreateController_ThrowsIConstructorCannotBeActivated()
{
// Arrange
var actionDescriptor = new ControllerActionDescriptor
{
ControllerTypeInfo = typeof(ControllerThatCannotBeActivated).GetTypeInfo()
};
var context = new ControllerContext()
{
ActionDescriptor = actionDescriptor,
HttpContext = new DefaultHttpContext()
{
RequestServices = GetServices(),
},
};
var factory = CreateControllerFactory(new DefaultControllerActivator(new TypeActivatorCache()));
// Act and Assert
var exception = Assert.Throws<InvalidOperationException>(() => factory.CreateController(context));
Assert.Equal(
$"Unable to resolve service for type '{typeof(TestService).FullName}' while attempting to activate " +
$"'{typeof(ControllerThatCannotBeActivated).FullName}'.",
exception.Message);
}
[Fact]
public void DefaultControllerFactory_DelegatesDisposalToControllerActivator()
{
// Arrange
var activatorMock = new Mock<IControllerActivator>();
activatorMock.Setup(s => s.Release(It.IsAny<ControllerContext>(), It.IsAny<object>()));
var factory = CreateControllerFactory(activatorMock.Object);
var controller = new MyController();
// Act + Assert
factory.ReleaseController(new ControllerContext(), controller);
activatorMock.Verify();
}
[Fact]
public async Task DefaultControllerFactory_DelegatesAsyncDisposalToControllerActivatorAsync()
{
// Arrange
var activatorMock = new Mock<IControllerActivator>();
activatorMock.Setup(s => s.Release(It.IsAny<ControllerContext>(), It.IsAny<object>()));
var factory = CreateControllerFactory(activatorMock.Object);
var controller = new MyAsyncDisposableController();
// Act + Assert
await factory.ReleaseControllerAsync(new ControllerContext(), controller);
activatorMock.Verify();
}
private IServiceProvider GetServices()
{
var metadataProvider = new EmptyModelMetadataProvider();
var services = new Mock<IServiceProvider>();
services
.Setup(s => s.GetService(typeof(IUrlHelper)))
.Returns(Mock.Of<IUrlHelper>());
services
.Setup(s => s.GetService(typeof(IModelMetadataProvider)))
.Returns(metadataProvider);
services
.Setup(s => s.GetService(typeof(IObjectModelValidator)))
.Returns(new DefaultObjectValidator(
metadataProvider,
TestModelValidatorProvider.CreateDefaultProvider().ValidatorProviders,
new MvcOptions()));
return services.Object;
}
private static DefaultControllerFactory CreateControllerFactory(IControllerActivator controllerActivator = null)
{
var activatorMock = new Mock<IControllerActivator>();
controllerActivator = controllerActivator ?? activatorMock.Object;
var propertyActivators = new IControllerPropertyActivator[]
{
new DefaultControllerPropertyActivator(),
};
return new DefaultControllerFactory(controllerActivator, propertyActivators);
}
private class ControllerWithoutAttributes
{
public ActionContext ActionContext { get; set; }
public ControllerContext ControllerContext { get; set; }
}
public class ControllerWithNonVisibleProperties
{
internal ActionContext ActionContext { get; set; }
public ControllerContext ControllerContext { get; private set; }
}
private class ControllerWithAttributes
{
[ActionContext]
public ActionContext ActionContext { get; set; }
[ControllerContext]
public ControllerContext ControllerContext { get; set; }
}
private class MyController : IDisposable
{
public bool Disposed { get; set; }
public void Dispose()
{
Disposed = true;
}
}
private class MyAsyncDisposableController : IAsyncDisposable
{
public bool Disposed { get; set; }
public ValueTask DisposeAsync()
{
Disposed = true;
return default;
}
}
private class ControllerThatCannotBeActivated
{
public ControllerThatCannotBeActivated(TestService service)
{
Service = service;
}
public TestService Service { get; }
}
private class TestService
{
}
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Buffers;
using System.Threading.Tasks;
using System.Reflection;
using System.Collections.Generic;
using SuperSocket;
using SuperSocket.Command;
using SuperSocket.ProtoBase;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Xunit;
using Xunit.Abstractions;
using SuperSocket.Client;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using SuperSocket.Channel;
using SuperSocket.Tests.Command;
using System.Threading;
using Microsoft.Extensions.Logging.Abstractions;
namespace SuperSocket.Tests
{
[Trait("Category", "Client")]
public class ClientTest : TestClassBase
{
private static Random _rd = new Random();
public ClientTest(ITestOutputHelper outputHelper)
: base(outputHelper)
{
}
[Theory]
[Trait("Category", "Client.TestEcho")]
[InlineData(typeof(RegularHostConfigurator), false)]
[InlineData(typeof(SecureHostConfigurator), false)]
[InlineData(typeof(GzipHostConfigurator), false)]
[InlineData(typeof(GzipSecureHostConfigurator), false)]
[InlineData(typeof(RegularHostConfigurator), true)]
public async Task TestEcho(Type hostConfiguratorType, bool clientReadAsDemand)
{
var hostConfigurator = CreateObject<IHostConfigurator>(hostConfiguratorType);
using (var server = CreateSocketServerBuilder<TextPackageInfo, LinePipelineFilter>(hostConfigurator)
.UsePackageHandler(async (s, p) =>
{
await s.SendAsync(Utf8Encoding.GetBytes(p.Text + "\r\n"));
}).BuildAsServer())
{
Assert.Equal("TestServer", server.Name);
Assert.True(await server.StartAsync());
OutputHelper.WriteLine("Server started.");
var options = new ChannelOptions
{
Logger = NullLogger.Instance,
ReadAsDemand = clientReadAsDemand
};
var client = hostConfigurator.ConfigureEasyClient(new LinePipelineFilter(), options);
var connected = await client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, hostConfigurator.Listener.Port));
Assert.True(connected);
for (var i = 0; i < 100; i++)
{
var msg = Guid.NewGuid().ToString();
await client.SendAsync(Utf8Encoding.GetBytes(msg + "\r\n"));
var package = await client.ReceiveAsync();
Assert.NotNull(package);
Assert.Equal(msg, package.Text);
}
await client.CloseAsync();
await server.StopAsync();
}
}
[Theory]
[InlineData(typeof(RegularHostConfigurator))]
[InlineData(typeof(GzipHostConfigurator))]
[Trait("Category", "Client.TestBindLocalEndPoint")]
public async Task TestBindLocalEndPoint(Type hostConfiguratorType)
{
IAppSession session = default;
var hostConfigurator = CreateObject<IHostConfigurator>(hostConfiguratorType);
using (var server = CreateSocketServerBuilder<StringPackageInfo, CommandLinePipelineFilter>(hostConfigurator)
.UseSessionHandler(async s =>
{
session = s;
await Task.CompletedTask;
})
.BuildAsServer())
{
Assert.Equal("TestServer", server.Name);
Assert.True(await server.StartAsync());
OutputHelper.WriteLine("Server started.");
var pipelineFilter = new CommandLinePipelineFilter
{
Decoder = new DefaultStringPackageDecoder()
};
var options = new ChannelOptions
{
Logger = DefaultLoggerFactory.CreateLogger(nameof(TestBindLocalEndPoint))
};
var client = hostConfigurator.ConfigureEasyClient(pipelineFilter, options);
var connected = false;
var localPort = 0;
for (var i = 0; i < 3; i++)
{
localPort = _rd.Next(40000, 50000);
client.LocalEndPoint = new IPEndPoint(IPAddress.Loopback, localPort);
try
{
connected = await client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, hostConfigurator.Listener.Port));
}
catch (SocketException e)
{
if (e.SocketErrorCode == SocketError.AccessDenied || e.SocketErrorCode == SocketError.AddressAlreadyInUse)
continue;
throw e;
}
break;
}
Assert.True(connected);
await Task.Delay(500);
Assert.NotNull(session);
Assert.Equal(localPort, (session.RemoteEndPoint as IPEndPoint).Port);
await client.CloseAsync();
await server.StopAsync();
}
}
[Theory]
[InlineData(typeof(RegularHostConfigurator))]
[InlineData(typeof(SecureHostConfigurator))]
[InlineData(typeof(GzipSecureHostConfigurator))]
[InlineData(typeof(GzipHostConfigurator))]
public async Task TestCommandLine(Type hostConfiguratorType)
{
var hostConfigurator = CreateObject<IHostConfigurator>(hostConfiguratorType);
using (var server = CreateSocketServerBuilder<StringPackageInfo, CommandLinePipelineFilter>(hostConfigurator)
.UseCommand((options) =>
{
options.AddCommand<SORT>();
}).BuildAsServer())
{
Assert.Equal("TestServer", server.Name);
Assert.True(await server.StartAsync());
OutputHelper.WriteLine("Server started.");
var pipelineFilter = new CommandLinePipelineFilter
{
Decoder = new DefaultStringPackageDecoder()
};
var options = new ChannelOptions
{
Logger = DefaultLoggerFactory.CreateLogger(nameof(TestCommandLine))
};
var client = hostConfigurator.ConfigureEasyClient(pipelineFilter, options);
StringPackageInfo package = null;
client.PackageHandler += async (s, p) =>
{
package = p;
await Task.CompletedTask;
};
var connected = await client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, hostConfigurator.Listener.Port));
Assert.True(connected);
client.StartReceive();
await client.SendAsync(Utf8Encoding.GetBytes("SORT 10 7 3 8 6 43 23\r\n"));
await Task.Delay(1000);
Assert.NotNull(package);
Assert.Equal("SORT", package.Key);
Assert.Equal("3 6 7 8 10 23 43", package.Body);
await client.CloseAsync();
await server.StopAsync();
}
}
[Theory]
[InlineData(typeof(RegularHostConfigurator))]
[Trait("Category", "TestDetachableChannel")]
public async Task TestDetachableChannel(Type hostConfiguratorType)
{
var hostConfigurator = CreateObject<IHostConfigurator>(hostConfiguratorType);
using (var server = CreateSocketServerBuilder<TextPackageInfo, LinePipelineFilter>(hostConfigurator)
.UsePackageHandler(async (s, p) =>
{
await s.SendAsync(Utf8Encoding.GetBytes("PRE-" + p.Text + "\r\n"));
}).BuildAsServer())
{
Assert.Equal("TestServer", server.Name);
Assert.True(await server.StartAsync());
OutputHelper.WriteLine("Server started.");
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
await socket.ConnectAsync(hostConfigurator.GetServerEndPoint());
var stream = await hostConfigurator.GetClientStream(socket);
var channel = new StreamPipeChannel<TextPackageInfo>(stream, socket.RemoteEndPoint, socket.LocalEndPoint, new LinePipelineFilter(), new ChannelOptions
{
Logger = DefaultLoggerFactory.CreateLogger(nameof(TestDetachableChannel)),
ReadAsDemand = true
});
channel.Start();
var msg = Guid.NewGuid().ToString();
await channel.SendAsync(Utf8Encoding.GetBytes(msg + "\r\n"));
var round = 0;
await foreach (var package in channel.RunAsync())
{
Assert.NotNull(package);
Assert.Equal("PRE-" + msg, package.Text);
round++;
if (round >= 10)
break;
msg = Guid.NewGuid().ToString();
await channel.SendAsync(Utf8Encoding.GetBytes(msg + "\r\n"));
}
OutputHelper.WriteLine("Before DetachAsync");
await channel.DetachAsync();
// the connection is still alive in the server
Assert.Equal(1, server.SessionCount);
// socket.Connected is is still connected
Assert.True(socket.Connected);
var ns = stream as DerivedNetworkStream;
Assert.True(ns.Socket.Connected);
// the stream is still usable
using (var streamReader = new StreamReader(stream, Utf8Encoding, true))
using (var streamWriter = new StreamWriter(stream, Utf8Encoding, 1024 * 1024 * 4))
{
for (var i = 0; i < 10; i++)
{
var txt = Guid.NewGuid().ToString();
await streamWriter.WriteAsync(txt + "\r\n");
await streamWriter.FlushAsync();
OutputHelper.WriteLine($"Sent {(i + 1)} message over the detached network stream");
var line = await streamReader.ReadLineAsync();
Assert.Equal("PRE-" + txt, line);
OutputHelper.WriteLine($"Received {(i + 1)} message over the detached network stream");
}
}
await server.StopAsync();
}
}
}
}
| |
// 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.Buffers.Binary;
using System.Collections.Generic;
using Xunit;
namespace System.Security.Cryptography.RNG.Tests
{
public partial class RandomNumberGeneratorTests
{
[Theory]
[InlineData(10)]
[InlineData(256)]
[InlineData(65536)]
public static void DifferentSequential_Span(int arraySize)
{
// Ensure that the RNG doesn't produce a stable set of data.
var first = new byte[arraySize];
var second = new byte[arraySize];
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
rng.GetBytes((Span<byte>)first);
rng.GetBytes((Span<byte>)second);
}
// Random being random, there is a chance that it could produce the same sequence.
// The smallest test case that we have is 10 bytes.
// The probability that they are the same, given a Truly Random Number Generator is:
// Pmatch(byte0) * Pmatch(byte1) * Pmatch(byte2) * ... * Pmatch(byte9)
// = 1/256 * 1/256 * ... * 1/256
// = 1/(256^10)
// = 1/1,208,925,819,614,629,174,706,176
Assert.NotEqual(first, second);
}
[Fact]
public static void GetBytes_Span_ZeroCount()
{
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
var rand = new byte[1] { 1 };
rng.GetBytes(new Span<byte>(rand, 0, 0));
Assert.Equal(1, rand[0]);
}
}
[Fact]
public static void GetNonZeroBytes_Span()
{
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
var rand = new byte[65536];
rng.GetNonZeroBytes(new Span<byte>(rand));
Assert.Equal(-1, Array.IndexOf<byte>(rand, 0));
}
}
[Fact]
public static void Fill_ZeroLengthSpan()
{
byte[] rand = { 1 };
RandomNumberGenerator.Fill(new Span<byte>(rand, 0, 0));
Assert.Equal(1, rand[0]);
}
[Fact]
public static void Fill_SpanLength1()
{
byte[] rand = { 1 };
bool replacedValue = false;
for (int i = 0; i < 10; i++)
{
RandomNumberGenerator.Fill(rand);
if (rand[0] != 1)
{
replacedValue = true;
break;
}
}
Assert.True(replacedValue, "Fill eventually wrote a different byte");
}
[Fact]
public static void Fill_RandomDistribution()
{
byte[] random = new byte[2048];
RandomNumberGenerator.Fill(random);
RandomDataGenerator.VerifyRandomDistribution(random);
}
[Theory]
[InlineData(10, 10)]
[InlineData(10, 9)]
[InlineData(-10, -10)]
[InlineData(-10, -11)]
public static void GetInt32_LowerAndUpper_InvalidRange(int fromInclusive, int toExclusive)
{
Assert.Throws<ArgumentException>(() => RandomNumberGenerator.GetInt32(fromInclusive, toExclusive));
}
[Theory]
[InlineData(0)]
[InlineData(-10)]
public static void GetInt32_Upper_InvalidRange(int toExclusive)
{
Assert.Throws<ArgumentOutOfRangeException>(() => RandomNumberGenerator.GetInt32(toExclusive));
}
[Theory]
[InlineData(1 << 1)]
[InlineData(1 << 4)]
[InlineData(1 << 16)]
[InlineData(1 << 24)]
public static void GetInt32_PowersOfTwo(int toExclusive)
{
for (int i = 0; i < 10; i++)
{
int result = RandomNumberGenerator.GetInt32(toExclusive);
Assert.InRange(result, 0, toExclusive - 1);
}
}
[Theory]
[InlineData((1 << 1) + 1)]
[InlineData((1 << 4) + 1)]
[InlineData((1 << 16) + 1)]
[InlineData((1 << 24) + 1)]
public static void GetInt32_PowersOfTwoPlusOne(int toExclusive)
{
for (int i = 0; i < 10; i++)
{
int result = RandomNumberGenerator.GetInt32(toExclusive);
Assert.InRange(result, 0, toExclusive - 1);
}
}
[Fact]
public static void GetInt32_FullRange()
{
int result = RandomNumberGenerator.GetInt32(int.MinValue, int.MaxValue);
Assert.NotEqual(int.MaxValue, result);
}
[Fact]
public static void GetInt32_DoesNotProduceSameNumbers()
{
int result1 = RandomNumberGenerator.GetInt32(int.MinValue, int.MaxValue);
int result2 = RandomNumberGenerator.GetInt32(int.MinValue, int.MaxValue);
int result3 = RandomNumberGenerator.GetInt32(int.MinValue, int.MaxValue);
// The changes of this happening are (2^32 - 1) * 3.
Assert.False(result1 == result2 && result2 == result3, "Generated the same number three times in a row.");
}
[Fact]
public static void GetInt32_FullRange_DistributesBitsEvenly()
{
// This test should work since we are selecting random numbers that are a
// Power of two minus one so no bit should favored.
int numberToGenerate = 256;
byte[] bytes = new byte[numberToGenerate * 4];
Span<byte> bytesSpan = bytes.AsSpan();
for (int i = 0, j = 0; i < numberToGenerate; i++, j += 4)
{
int result = RandomNumberGenerator.GetInt32(int.MinValue, int.MaxValue);
Span<byte> slice = bytesSpan.Slice(j, 4);
BinaryPrimitives.WriteInt32LittleEndian(slice, result);
}
RandomDataGenerator.VerifyRandomDistribution(bytes);
}
[Fact]
public static void GetInt32_CoinFlipLowByte()
{
int numberToGenerate = 1024;
Span<int> generated = stackalloc int[numberToGenerate];
for (int i = 0; i < numberToGenerate; i++)
{
generated[i] = RandomNumberGenerator.GetInt32(0, 2);
}
VerifyAllInRange(generated, 0, 2);
VerifyDistribution(generated, 0.5);
}
[Fact]
public static void GetInt32_CoinFlipOverByteBoundary()
{
int numberToGenerate = 1024;
Span<int> generated = stackalloc int[numberToGenerate];
for (int i = 0; i < numberToGenerate; i++)
{
generated[i] = RandomNumberGenerator.GetInt32(255, 257);
}
VerifyAllInRange(generated, 255, 257);
VerifyDistribution(generated, 0.5);
}
[Fact]
public static void GetInt32_NegativeBounds1000d20()
{
int numberToGenerate = 1000;
Span<int> generated = stackalloc int[numberToGenerate];
for (int i = 0; i < numberToGenerate; i++)
{
generated[i] = RandomNumberGenerator.GetInt32(-4000, -3979);
}
VerifyAllInRange(generated, -4000, -3979);
VerifyDistribution(generated, 0.05);
}
[Fact]
public static void GetInt32_1000d6()
{
int numberToGenerate = 1000;
Span<int> generated = stackalloc int[numberToGenerate];
for (int i = 0; i < numberToGenerate; i++)
{
generated[i] = RandomNumberGenerator.GetInt32(1, 7);
}
VerifyAllInRange(generated, 1, 7);
VerifyDistribution(generated, 0.16);
}
[Theory]
[InlineData(int.MinValue, int.MinValue + 3)]
[InlineData(-257, -129)]
[InlineData(-100, 5)]
[InlineData(254, 512)]
[InlineData(-1_073_741_909, - 1_073_741_825)]
[InlineData(65_534, 65_539)]
[InlineData(16_777_214, 16_777_217)]
public static void GetInt32_MaskRangeCorrect(int fromInclusive, int toExclusive)
{
int numberToGenerate = 1000;
Span<int> generated = stackalloc int[numberToGenerate];
for (int i = 0; i < numberToGenerate; i++)
{
generated[i] = RandomNumberGenerator.GetInt32(fromInclusive, toExclusive);
}
double expectedDistribution = 1d / (toExclusive - fromInclusive);
VerifyAllInRange(generated, fromInclusive, toExclusive);
VerifyDistribution(generated, expectedDistribution);
}
private static void VerifyAllInRange(ReadOnlySpan<int> numbers, int fromInclusive, int toExclusive)
{
for (int i = 0; i < numbers.Length; i++)
{
Assert.InRange(numbers[i], fromInclusive, toExclusive - 1);
}
}
private static void VerifyDistribution(ReadOnlySpan<int> numbers, double expected)
{
var observedNumbers = new Dictionary<int, int>(numbers.Length);
for (int i = 0; i < numbers.Length; i++)
{
int number = numbers[i];
if (!observedNumbers.TryAdd(number, 1))
{
observedNumbers[number]++;
}
}
const double tolerance = 0.07;
foreach ((_, int occurences) in observedNumbers)
{
double percentage = occurences / (double)numbers.Length;
Assert.True(Math.Abs(expected - percentage) < tolerance, "Occurred number of times within threshold.");
}
}
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// 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.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1998
{
/// <summary>
/// Section 5.2.18. Identifies a unique event in a simulation via the combination of three values
/// </summary>
[Serializable]
[XmlRoot]
public partial class EventID
{
/// <summary>
/// The site ID
/// </summary>
private ushort _site;
/// <summary>
/// The application ID
/// </summary>
private ushort _application;
/// <summary>
/// the number of the event
/// </summary>
private ushort _eventNumber;
/// <summary>
/// Initializes a new instance of the <see cref="EventID"/> class.
/// </summary>
public EventID()
{
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(EventID left, EventID right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(EventID left, EventID right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public virtual int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize += 2; // this._site
marshalSize += 2; // this._application
marshalSize += 2; // this._eventNumber
return marshalSize;
}
/// <summary>
/// Gets or sets the The site ID
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "site")]
public ushort Site
{
get
{
return this._site;
}
set
{
this._site = value;
}
}
/// <summary>
/// Gets or sets the The application ID
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "application")]
public ushort Application
{
get
{
return this._application;
}
set
{
this._application = value;
}
}
/// <summary>
/// Gets or sets the the number of the event
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "eventNumber")]
public ushort EventNumber
{
get
{
return this._eventNumber;
}
set
{
this._eventNumber = value;
}
}
/// <summary>
/// Occurs when exception when processing PDU is caught.
/// </summary>
public event EventHandler<PduExceptionEventArgs> ExceptionOccured;
/// <summary>
/// Called when exception occurs (raises the <see cref="Exception"/> event).
/// </summary>
/// <param name="e">The exception.</param>
protected void RaiseExceptionOccured(Exception e)
{
if (Pdu.FireExceptionEvents && this.ExceptionOccured != null)
{
this.ExceptionOccured(this, new PduExceptionEventArgs(e));
}
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Marshal(DataOutputStream dos)
{
if (dos != null)
{
try
{
dos.WriteUnsignedShort((ushort)this._site);
dos.WriteUnsignedShort((ushort)this._application);
dos.WriteUnsignedShort((ushort)this._eventNumber);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Unmarshal(DataInputStream dis)
{
if (dis != null)
{
try
{
this._site = dis.ReadUnsignedShort();
this._application = dis.ReadUnsignedShort();
this._eventNumber = dis.ReadUnsignedShort();
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Reflection(StringBuilder sb)
{
sb.AppendLine("<EventID>");
try
{
sb.AppendLine("<site type=\"ushort\">" + this._site.ToString(CultureInfo.InvariantCulture) + "</site>");
sb.AppendLine("<application type=\"ushort\">" + this._application.ToString(CultureInfo.InvariantCulture) + "</application>");
sb.AppendLine("<eventNumber type=\"ushort\">" + this._eventNumber.ToString(CultureInfo.InvariantCulture) + "</eventNumber>");
sb.AppendLine("</EventID>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as EventID;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(EventID obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
if (this._site != obj._site)
{
ivarsEqual = false;
}
if (this._application != obj._application)
{
ivarsEqual = false;
}
if (this._eventNumber != obj._eventNumber)
{
ivarsEqual = false;
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ this._site.GetHashCode();
result = GenerateHash(result) ^ this._application.GetHashCode();
result = GenerateHash(result) ^ this._eventNumber.GetHashCode();
return result;
}
}
}
| |
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 WebApiContrib.Tracing.Slab.DemoApp.WithSignalR.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using Xunit;
using Tests.HashSet_HashSetTestSupport;
using Tests.HashSet_SetCollectionRelationshipTests;
using Tests.HashSet_SetCollectionComparerTests;
namespace Tests
{
public class HashSet_RemoveWhereTests
{
#region match matches a collection of items - tests 1-57
#region Set/Collection Relationship tests - tests 1-42
//Test 1: Set/Collection Relationship Test 1: other is null
[Fact]
public static void RemoveWhere_Test1()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest1(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(0, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(34), new Item(4), new Item(9999) }, hashSet.Comparer);
}
//Test 2: Set/Collection Relationship Test 2: other is empty and set is empty
[Fact]
public static void RemoveWhere_Test2()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest2(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(0, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[0], hashSet.Comparer);
}
//Test 3: Set/Collection Relationship Test 3: other is empty and set is single-item
[Fact]
public static void RemoveWhere_Test3()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest3(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(0, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(1) }, hashSet.Comparer);
}
//Test 4: Set/Collection Relationship Test 4: other is empty and set is multi-item
[Fact]
public static void RemoveWhere_Test4()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest4(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(0, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(1), new Item(3), new Item(-23) }, hashSet.Comparer);
}
//Test 5: Set/Collection Relationship Test 5: other is single-item and set is empty
[Fact]
public static void RemoveWhere_Test5()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest5(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(0, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[0], hashSet.Comparer);
}
//Test 6: Set/Collection Relationship Test 6: other is single-item and set is single-item with a different item
[Fact]
public static void RemoveWhere_Test6()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest6(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(0, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(34) }, hashSet.Comparer);
}
//Test 7: Set/Collection Relationship Test 7: other is single-item and set is single-item with the same item
[Fact]
public static void RemoveWhere_Test7()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest7(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(1, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[0], hashSet.Comparer);
}
//Test 8: Set/Collection Relationship Test 8: other is single-item and set is multi-item where set and other are disjoint
[Fact]
public static void RemoveWhere_Test8()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest8(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(0, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(-23), new Item(0), new Item(234) }, hashSet.Comparer);
}
//Test 9: Set/Collection Relationship Test 9: other is single-item and set is multi-item where set contains other
[Fact]
public static void RemoveWhere_Test9()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest9(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(1, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(-23), new Item(0) }, hashSet.Comparer);
}
//Test 10: Set/Collection Relationship Test 10: other is multi-item and set is empty
[Fact]
public static void RemoveWhere_Test10()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest10(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(0, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[0], hashSet.Comparer);
}
//Test 11: Set/Collection Relationship Test 11: other is multi-item and set is single-item and set and other are disjoint
[Fact]
public static void RemoveWhere_Test11()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest11(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(0, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(-222) }, hashSet.Comparer);
}
//Test 12: Set/Collection Relationship Test 12: other is multi-item and set is single-item and other contains set
[Fact]
public static void RemoveWhere_Test12()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest12(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(1, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[0], hashSet.Comparer);
}
//Test 13: Set/Collection Relationship Test 13: other is multi-item and set is multi-item and set and other disjoint
[Fact]
public static void RemoveWhere_Test13()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest13(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(0, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(23), new Item(222), new Item(322) }, hashSet.Comparer);
}
//Test 14: Set/Collection Relationship Test 14: other is multi-item and set is multi-item and set and other overlap but are non-comparable
[Fact]
public static void RemoveWhere_Test14()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest14(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(2, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(23), new Item(222) }, hashSet.Comparer);
}
//Test 15: Set/Collection Relationship Test 15: other is multi-item and set is multi-item and other is a proper subset of set
[Fact]
public static void RemoveWhere_Test15()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest15(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(3, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(23), new Item(222) }, hashSet.Comparer);
}
//Test 16: Set/Collection Relationship Test 16: other is multi-item and set is multi-item and set is a proper subset of other
[Fact]
public static void RemoveWhere_Test16()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest16(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(3, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[0], hashSet.Comparer);
}
//Test 17: Set/Collection Relationship Test 17: other is multi-item and set is multi-item and set and other are equal
[Fact]
public static void RemoveWhere_Test17()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest17(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(5, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[0], hashSet.Comparer);
}
//Test 18: Set/Collection Relationship Test 18: other is set and set is empty
[Fact]
public static void RemoveWhere_Test18()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest18(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(0, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[0], hashSet.Comparer);
}
//Test 19: Set/Collection Relationship Test 19: other is set and set is single-item and set contains set
[Fact]
public static void RemoveWhere_Test19()
{
HashSet<IEnumerable> hashSet;
IEnumerable<IEnumerable> other;
int ret;
SetCollectionRelationshipTests.SetupTest19(out hashSet, out other);
PredicateMatches<IEnumerable>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<IEnumerable>.Match);
Assert.Equal(1, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<IEnumerable>.VerifyHashSet(hashSet, new IEnumerable[0], hashSet.Comparer);
}
//Test 20: Set/Collection Relationship Test 20: other is set and set is single-item and set does not contain set
[Fact]
public static void RemoveWhere_Test20()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest20(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(1, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[0], hashSet.Comparer);
}
//Test 21: Set/Collection Relationship Test 21: other is set and set is multi-item and set contains set
[Fact]
public static void RemoveWhere_Test21()
{
HashSet<IEnumerable> hashSet;
IEnumerable<IEnumerable> other;
int ret;
SetCollectionRelationshipTests.SetupTest21(out hashSet, out other);
PredicateMatches<IEnumerable>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<IEnumerable>.Match);
Assert.Equal(3, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<IEnumerable>.VerifyHashSet(hashSet, new IEnumerable[0], hashSet.Comparer);
}
//Test 22: Set/Collection Relationship Test 22: other is set and set is multi-item and set does not contain set
[Fact]
public static void RemoveWhere_Test22()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest22(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(3, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[0], hashSet.Comparer);
}
//Test 23: Set/Collection Relationship Test 23: item is only item in other: Item is the set and item is in the set
[Fact]
public static void RemoveWhere_Test23()
{
List<int> item1 = new List<int>(new int[] { 1, 2 });
List<int> item2 = new List<int>(new int[] { 2, -1 });
HashSet<IEnumerable> hashSet;
IEnumerable<IEnumerable> other;
int ret;
SetCollectionRelationshipTests.SetupTest23(out hashSet, out other);
PredicateMatches<IEnumerable>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<IEnumerable>.Match);
Assert.Equal(1, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<IEnumerable>.VerifyHashSet(hashSet, new IEnumerable[] { item1, item2 }, hashSet.Comparer);
}
//Test 24: Set/Collection Relationship Test 24: item is only item in other: Item is the set and item is not in the set
[Fact]
public static void RemoveWhere_Test24()
{
List<int> item1 = new List<int>(new int[] { 1, 2 });
List<int> item2 = new List<int>(new int[] { 2, -1 });
HashSet<IEnumerable> hashSet;
IEnumerable<IEnumerable> other;
int ret;
SetCollectionRelationshipTests.SetupTest24(out hashSet, out other);
PredicateMatches<IEnumerable>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<IEnumerable>.Match);
Assert.Equal(0, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<IEnumerable>.VerifyHashSet(hashSet, new IEnumerable[] { item1, item2 }, hashSet.Comparer);
}
//Test 25: Set/Collection Relationship Test 25: item is only item in other: Item is Default<T> and in set. T is a numeric type
[Fact]
public static void RemoveWhere_Test25()
{
HashSet<int> hashSet;
IEnumerable<int> other;
int ret;
SetCollectionRelationshipTests.SetupTest25(out hashSet, out other);
PredicateMatches<int>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<int>.Match);
Assert.Equal(1, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<int>.VerifyHashSet(hashSet, new int[] { 1, 2, 3, 4, 6, 7 }, hashSet.Comparer);
}
//Test 26: Set/Collection Relationship Test 26: item is only item in other: Item is Default<T> and in set. T is a reference type
[Fact]
public static void RemoveWhere_Test26()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest26(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(1, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(-3), new Item(3) }, hashSet.Comparer);
}
//Test 27: Set/Collection Relationship Test 27: item is only item in other: Item is Default<T> and not in set. T is a numeric type
[Fact]
public static void RemoveWhere_Test27()
{
HashSet<int> hashSet;
IEnumerable<int> other;
int ret;
SetCollectionRelationshipTests.SetupTest27(out hashSet, out other);
PredicateMatches<int>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<int>.Match);
Assert.Equal(0, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<int>.VerifyHashSet(hashSet, new int[] { 1, 2, 3, 4, 6, 7, 5 }, hashSet.Comparer);
}
//Test 28: Set/Collection Relationship Test 28: item is only item in other: Item is Default<T> and not in set. T is a reference type
[Fact]
public static void RemoveWhere_Test28()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest28(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(0, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(-3), new Item(3) }, hashSet.Comparer);
}
//Test 29: Set/Collection Relationship Test 29: item is only item in other: Item is equal to an item in set but different.
[Fact]
public static void RemoveWhere_Test29()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest29(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(1, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(3), new Item(2) }, hashSet.Comparer);
}
//Test 30: Set/Collection Relationship Test 30: item is only item in other: Item shares hash value with unequal item in set
[Fact]
public static void RemoveWhere_Test30()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest30(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(0, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(1), new Item(3), new Item(2) }, hashSet.Comparer);
}
//Test 31: Set/Collection Relationship Test 31: item is only item in other: Item was previously in set but not currently
[Fact]
public static void RemoveWhere_Test31()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest31(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(0, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(3), new Item(2) }, hashSet.Comparer);
}
//Test 32: Set/Collection Relationship Test 32: item is only item in other: Item was previously removed from set but in it currently
[Fact]
public static void RemoveWhere_Test32()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest32(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(1, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(3), new Item(2) }, hashSet.Comparer);
}
//Test 33: Set/Collection Relationship Test 33: item is one of the items in other: Item is the set and item is in the set
[Fact]
public static void RemoveWhere_Test33()
{
List<int> item1 = new List<int>(new int[] { 1, 2 });
List<int> item2 = new List<int>(new int[] { 2, -1 });
HashSet<IEnumerable> hashSet;
IEnumerable<IEnumerable> other;
int ret;
SetCollectionRelationshipTests.SetupTest33(out hashSet, out other);
PredicateMatches<IEnumerable>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<IEnumerable>.Match);
Assert.Equal(1, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<IEnumerable>.VerifyHashSet(hashSet, new IEnumerable[] { item1, item2 }, hashSet.Comparer);
}
//Test 34: Set/Collection Relationship Test 34: item is one of the items in other: Item is the set and item is not in the set
[Fact]
public static void RemoveWhere_Test34()
{
List<int> item1 = new List<int>(new int[] { 1, 2 });
List<int> item2 = new List<int>(new int[] { 2, -1 });
HashSet<IEnumerable> hashSet;
IEnumerable<IEnumerable> other;
int ret;
SetCollectionRelationshipTests.SetupTest34(out hashSet, out other);
PredicateMatches<IEnumerable>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<IEnumerable>.Match);
Assert.Equal(0, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<IEnumerable>.VerifyHashSet(hashSet, new IEnumerable[] { item1, item2 }, hashSet.Comparer);
}
//Test 35: Set/Collection Relationship Test 35: item is one of the items in other: Item is Default<T> and in set. T is a numeric type
[Fact]
public static void RemoveWhere_Test35()
{
HashSet<int> hashSet;
IEnumerable<int> other;
int ret;
SetCollectionRelationshipTests.SetupTest35(out hashSet, out other);
PredicateMatches<int>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<int>.Match);
Assert.Equal(1, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<int>.VerifyHashSet(hashSet, new int[] { 1, 2, 3, 4, 6, 7 }, hashSet.Comparer);
}
//Test 36: Set/Collection Relationship Test 36: item is one of the items in other: Item is Default<T> and in set. T is a reference type
[Fact]
public static void RemoveWhere_Test36()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest36(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(1, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(-3), new Item(3) }, hashSet.Comparer);
}
//Test 37: Set/Collection Relationship Test 37: item is one of the items in other: Item is Default<T> and not in set. T is a numeric type
[Fact]
public static void RemoveWhere_Test37()
{
HashSet<int> hashSet;
IEnumerable<int> other;
int ret;
SetCollectionRelationshipTests.SetupTest37(out hashSet, out other);
PredicateMatches<int>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<int>.Match);
Assert.Equal(0, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<int>.VerifyHashSet(hashSet, new int[] { 1, 2, 3, 4, 6, 7, 5 }, hashSet.Comparer);
}
//Test 38: Set/Collection Relationship Test 38: item is one of the items in other: Item is Default<T> and not in set. T is a reference type
[Fact]
public static void RemoveWhere_Test38()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest38(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(0, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(-3), new Item(3) }, hashSet.Comparer);
}
//Test 39: Set/Collection Relationship Test 39: item is one of the items in other: Item is equal to an item in set but different.
[Fact]
public static void RemoveWhere_Test39()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest39(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(1, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(2), new Item(3) }, hashSet.Comparer);
}
//Test 40: Set/Collection Relationship Test 40: item is one of the items in other: Item shares hash value with unequal item in set
[Fact]
public static void RemoveWhere_Test40()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest40(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(0, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(1), new Item(2), new Item(3) }, hashSet.Comparer);
}
//Test 41: Set/Collection Relationship Test 41: item is one of the items in other: Item was previously in set but not currently
[Fact]
public static void RemoveWhere_Test41()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest41(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(0, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(2), new Item(3) }, hashSet.Comparer);
}
//Test 42: Set/Collection Relationship Test 42: item is one of the items in other: Item was previously removed from set but in it currently
[Fact]
public static void RemoveWhere_Test42()
{
HashSet<Item> hashSet;
IEnumerable<Item> other;
int ret;
SetCollectionRelationshipTests.SetupTest42(out hashSet, out other);
PredicateMatches<Item>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<Item>.Match);
Assert.Equal(1, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<Item>.VerifyHashSet(hashSet, new Item[] { new Item(2), new Item(3) }, hashSet.Comparer);
}
#endregion
#region Set/Collection Comparer Tests (tests 43-57)
//Test 43: Set/Collection Comparer Test 1: Item is in collection: item same as element in set by default comparer, different by sets comparer - set contains item that is equal by sets comparer
[Fact]
public static void RemoveWhere_Test43()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
int ret;
ValueItem item1 = new ValueItem(34, -5);
ValueItem item2 = new ValueItem(4, 4);
SetCollectionComparerTests.SetupTest1(out hashSet, out other);
PredicateMatches<ValueItem>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<ValueItem>.Match);
Assert.Equal(1, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2 }, hashSet.Comparer);
}
//Test 44: Set/Collection Comparer Test 2: Item is in collection: item same as element in set by default comparer, different by sets comparer - set does not contain item that is equal by sets comparer
[Fact]
public static void RemoveWhere_Test44()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
int ret;
ValueItem item1 = new ValueItem(34, -5);
ValueItem item2 = new ValueItem(4, 4);
ValueItem item3 = new ValueItem(9999, -20);
SetCollectionComparerTests.SetupTest2(out hashSet, out other);
PredicateMatches<ValueItem>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<ValueItem>.Match);
Assert.Equal(0, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2, item3 }, hashSet.Comparer);
}
//Test 45: Set/Collection Comparer Test 3: Item is in collection: item same as element in set by sets comparer, different by default comparer - set contains item that is equal by default comparer
[Fact]
public static void RemoveWhere_Test45()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
int ret;
ValueItem item1 = new ValueItem(34, -5);
ValueItem item2 = new ValueItem(4, 4);
SetCollectionComparerTests.SetupTest3(out hashSet, out other);
PredicateMatches<ValueItem>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<ValueItem>.Match);
Assert.Equal(1, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2 }, hashSet.Comparer);
}
//Test 46: Set/Collection Comparer Test 4: Item is in collection: item same as element in set by sets comparer, different by default comparer - set does not contain item that is equal by default comparer
[Fact]
public static void RemoveWhere_Test46()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
int ret;
ValueItem item1 = new ValueItem(340, -5);
ValueItem item2 = new ValueItem(4, 4);
SetCollectionComparerTests.SetupTest4(out hashSet, out other);
PredicateMatches<ValueItem>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<ValueItem>.Match);
Assert.Equal(1, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2 }, hashSet.Comparer);
}
//Test 48: Set/Collection Comparer Test 6: Item is only item in collection: item same as element in set by default comparer, different by sets comparer - set contains item that is equal by sets comparer
[Fact]
public static void RemoveWhere_Test48()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
int ret;
ValueItem item1 = new ValueItem(34, -5);
ValueItem item2 = new ValueItem(4, 4);
SetCollectionComparerTests.SetupTest6(out hashSet, out other);
PredicateMatches<ValueItem>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<ValueItem>.Match);
Assert.Equal(1, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2 }, hashSet.Comparer);
}
//Test 49: Set/Collection Comparer Test 7: Item is only item in collection: item same as element in set by default comparer, different by sets comparer - set does not contain item that is equal by sets comparer
[Fact]
public static void RemoveWhere_Test49()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
int ret;
ValueItem item1 = new ValueItem(34, -5);
ValueItem item2 = new ValueItem(4, 4);
ValueItem item3 = new ValueItem(9999, -20);
SetCollectionComparerTests.SetupTest7(out hashSet, out other);
PredicateMatches<ValueItem>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<ValueItem>.Match);
Assert.Equal(0, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2, item3 }, hashSet.Comparer);
}
//Test 50: Set/Collection Comparer Test 8: Item is only item in collection: item same as element in set by sets comparer, different by default comparer - set contains item that is equal by default comparer
[Fact]
public static void RemoveWhere_Test50()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
int ret;
ValueItem item1 = new ValueItem(34, -5);
ValueItem item2 = new ValueItem(4, 4);
SetCollectionComparerTests.SetupTest8(out hashSet, out other);
PredicateMatches<ValueItem>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<ValueItem>.Match);
Assert.Equal(1, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2 }, hashSet.Comparer);
}
//Test 51: Set/Collection Comparer Test 9: Item is only item in collection: item same as element in set by sets comparer, different by default comparer - set does not contain item that is equal by default comparer
[Fact]
public static void RemoveWhere_Test51()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
int ret;
ValueItem item1 = new ValueItem(340, -5);
ValueItem item2 = new ValueItem(4, 4);
SetCollectionComparerTests.SetupTest9(out hashSet, out other);
PredicateMatches<ValueItem>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<ValueItem>.Match);
Assert.Equal(1, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2 }, hashSet.Comparer);
}
//Test 52: Set/Collection Comparer Test 10: Item is only item in collection: item contains set and item in set with GetSetComparer<T> as comparer
[Fact]
public static void RemoveWhere_Test52()
{
ValueItem itemn4 = new ValueItem(-4, -4);
ValueItem itemn3 = new ValueItem(-3, -3);
ValueItem itemn2 = new ValueItem(-2, -2);
ValueItem itemn1 = new ValueItem(-1, -1);
ValueItem item1 = new ValueItem(1, 1);
ValueItem item2 = new ValueItem(2, 2);
ValueItem item3 = new ValueItem(3, 3);
ValueItem item4 = new ValueItem(4, 4);
HashSet<IEnumerable> itemhs1 = new HashSet<IEnumerable>(new ValueItem[] { item1, item2, item3, item4 });
HashSet<IEnumerable> itemhs2 = new HashSet<IEnumerable>(new ValueItem[] { itemn1, itemn2, itemn3, itemn4 });
HashSet<HashSet<IEnumerable>> hashSet;
IEnumerable<HashSet<IEnumerable>> other;
int ret;
SetCollectionComparerTests.SetupTest10(out hashSet, out other);
PredicateMatches<HashSet<IEnumerable>>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<HashSet<IEnumerable>>.Match);
HashSet<IEnumerable>[] expected = new HashSet<IEnumerable>[] { itemhs1, itemhs2 };
HashSet<IEnumerable>[] actual = new HashSet<IEnumerable>[2];
hashSet.CopyTo(actual, 0, 2);
Assert.Equal(1, ret); //"RemoveWhere returned the wrong value"
Assert.Equal(2, hashSet.Count); //"Expected count to be same."
HashSetTestSupport.HashSetContains(actual, expected);
}
//Test 53: Set/Collection Comparer Test 11: Item is collection: item same as element in set by default comparer, different by sets comparer - set contains item that is equal by sets comparer
[Fact]
public static void RemoveWhere_Test53()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
int ret;
ValueItem item1 = new ValueItem(34, -5);
ValueItem item2 = new ValueItem(4, 4);
SetCollectionComparerTests.SetupTest11(out hashSet, out other);
PredicateMatches<ValueItem>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<ValueItem>.Match);
Assert.Equal(1, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2 }, hashSet.Comparer);
}
//Test 54: Set/Collection Comparer Test 12: Item is collection: item same as element in set by default comparer, different by sets comparer - set does not contain item that is equal by sets comparer
[Fact]
public static void RemoveWhere_Test54()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
int ret;
ValueItem item1 = new ValueItem(34, -5);
ValueItem item2 = new ValueItem(4, 4);
ValueItem item3 = new ValueItem(9999, -20);
SetCollectionComparerTests.SetupTest12(out hashSet, out other);
PredicateMatches<ValueItem>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<ValueItem>.Match);
Assert.Equal(0, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2, item3 }, hashSet.Comparer);
}
//Test 55: Set/Collection Comparer Test 13: Item is collection: item same as element in set by sets comparer, different by default comparer - set contains item that is equal by default comparer
[Fact]
public static void RemoveWhere_Test55()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
int ret;
ValueItem item1 = new ValueItem(34, -5);
ValueItem item2 = new ValueItem(4, 4);
SetCollectionComparerTests.SetupTest13(out hashSet, out other);
PredicateMatches<ValueItem>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<ValueItem>.Match);
Assert.Equal(1, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2 }, hashSet.Comparer);
}
//Test 56: Set/Collection Comparer Test 14: Item is collection: item same as element in set by sets comparer, different by default comparer - set does not contain item that is equal by default comparer
[Fact]
public static void RemoveWhere_Test56()
{
HashSet<ValueItem> hashSet;
IEnumerable<ValueItem> other;
int ret;
ValueItem item1 = new ValueItem(340, -5);
ValueItem item2 = new ValueItem(4, 4);
SetCollectionComparerTests.SetupTest14(out hashSet, out other);
PredicateMatches<ValueItem>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<ValueItem>.Match);
Assert.Equal(1, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<ValueItem>.VerifyHashSet(hashSet, new ValueItem[] { item1, item2 }, hashSet.Comparer);
}
//Test 57: Set/Collection Comparer Test 15: Item is collection: item contains set and item in set with GetSetComparer<T> as comparer
[Fact]
public static void RemoveWhere_Test57()
{
HashSet<HashSet<IEnumerable>> hashSet;
IEnumerable<HashSet<IEnumerable>> other;
int ret;
SetCollectionComparerTests.SetupTest15(out hashSet, out other);
PredicateMatches<HashSet<IEnumerable>>.SetMatchOn(other, hashSet.Comparer);
ret = hashSet.RemoveWhere(PredicateMatches<HashSet<IEnumerable>>.Match);
Assert.Equal(3, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<HashSet<IEnumerable>>.VerifyHashSet(hashSet, new HashSet<IEnumerable>[0], hashSet.Comparer);
}
#endregion
#endregion
[Fact]
public static void RemoveWhere_Test58()
{
HashSet<Item> hashSet;
int ret;
//Test 58: match is null
hashSet = new HashSet<Item>();
Assert.Throws<ArgumentNullException>(() => { ret = hashSet.RemoveWhere(null); }); //"ArgumentNullException expected"
//Test 59: match throws exception
hashSet = new HashSet<Item>(new Item[] { new Item(0) });
Predicate<Item> exceptionPred = (Item item) => { throw new ArithmeticException("Arithmetic exception thrown. :D"); };
Assert.Throws<ArithmeticException>(() => { ret = hashSet.RemoveWhere(exceptionPred); }); //"ArithmeticException expected."
//Test 65: match modifies the set: adds a different item and returns false
HashSet<int> hashSet2 = new HashSet<int>(new int[] { -4, -3, -2, -1, 0, 1, 2, 3, 4 });
PredicateMatch.set = hashSet2;
Assert.Throws<OutOfMemoryException>(() => { ret = hashSet2.RemoveWhere(PredicateMatch.Match65); }); //"OutOfMemoryException expected."
}
//Test 60: match modifies the set: adds item being tested and returns true
[Fact]
public static void RemoveWhere_Test60()
{
HashSet<int> hashSet;
int ret;
hashSet = new HashSet<int>(new int[] { -4, -3, -2, -1, 0, 1, 2, 3, 4 });
PredicateMatch.set = hashSet;
ret = hashSet.RemoveWhere(PredicateMatch.Match60);
Assert.Equal(9, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<int>.VerifyHashSet(hashSet, new int[0], hashSet.Comparer);
}
//Test 61: match modifies the set: adds item being tested and returns false
[Fact]
public static void RemoveWhere_Test61()
{
HashSet<int> hashSet;
int ret;
hashSet = new HashSet<int>(new int[] { -4, -3, -2, -1, 0, 1, 2, 3, 4 });
PredicateMatch.set = hashSet;
ret = hashSet.RemoveWhere(PredicateMatch.Match61);
Assert.Equal(0, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<int>.VerifyHashSet(hashSet, new int[] { -4, -3, -2, -1, 0, 1, 2, 3, 4 }, hashSet.Comparer);
}
//Test 62: match modifies the set: removes item being tested and returns true
[Fact]
public static void RemoveWhere_Test62()
{
HashSet<int> hashSet;
int ret;
hashSet = new HashSet<int>(new int[] { -4, -3, -2, -1, 0, 1, 2, 3, 4 });
PredicateMatch.set = hashSet;
ret = hashSet.RemoveWhere(PredicateMatch.Match62);
Assert.Equal(0, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<int>.VerifyHashSet(hashSet, new int[0], hashSet.Comparer);
}
//Test 63: match modifies the set: removes item being tested and returns false
[Fact]
public static void RemoveWhere_Test63()
{
HashSet<int> hashSet;
int ret;
hashSet = new HashSet<int>(new int[] { -4, -3, -2, -1, 0, 1, 2, 3, 4 });
PredicateMatch.set = hashSet;
ret = hashSet.RemoveWhere(PredicateMatch.Match63);
Assert.Equal(0, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<int>.VerifyHashSet(hashSet, new int[0], hashSet.Comparer);
}
//Test 64: match modifies the set: adds a different item and returns true
[Fact]
public static void RemoveWhere_Test64()
{
HashSet<int> hashSet;
int ret;
hashSet = new HashSet<int>(new int[] { -4, -3, -2, -1, 0, 1, 2, 3, 4 });
PredicateMatch.set = hashSet;
ret = hashSet.RemoveWhere(PredicateMatch.Match64);
Assert.Equal(10, ret); //"RemoveWhere returned the wrong value"
HashSetTestSupport<int>.VerifyHashSet(hashSet, new int[] { 16, 7, 8, 9, 10, 11, 12, 13, 14 }, hashSet.Comparer);
}
//Test 66: match is non-stationary: independent of set
[Fact]
public static void RemoveWhere_Test66()
{
HashSet<int> hashSet;
HashSet<int> hashSet2;
int ret;
hashSet = new HashSet<int>(new int[] { -4, -3, -2, -1, 0, 1, 2, 3, 4 });
hashSet2 = new HashSet<int>(new int[] { -4, -3, -2, -1, 0, 1, 2, 3, 4 });
PredicateMatch.set = hashSet;
PredicateMatch.remove = true;
ret = hashSet.RemoveWhere(PredicateMatch.Match66);
Assert.Equal(5, ret); //"RemoveWhere returned the wrong value"
Assert.Equal(4, hashSet.Count); //"RemoveWhere removed wrong number of items"
Assert.True(hashSet.IsSubsetOf(hashSet2)); //"RemoveWhere left wrong items in set"
}
//Test 67: match is non-stationary: dependent on set
[Fact]
public static void RemoveWhere_Test67()
{
HashSet<int> hashSet;
HashSet<int> hashSet2;
int ret;
hashSet = new HashSet<int>(new int[] { -4, -3, -2, -1, 0, 1, 2, 3, 4 });
hashSet2 = new HashSet<int>(new int[] { -4, -3, -2, -1, 0, 1, 2, 3, 4 });
PredicateMatch.set = hashSet;
PredicateMatch.limit = 6;
ret = hashSet.RemoveWhere(PredicateMatch.Match67);
Assert.Equal(3, ret); //"RemoveWhere returned the wrong value"
Assert.Equal(6, hashSet.Count); //"RemoveWhere removed wrong number of items"
Assert.True(hashSet.IsSubsetOf(hashSet2)); //"RemoveWhere left wrong items in set"
}
#region Helper Classes
private class PredicateMatches<T>
{
private static IEnumerable<T> s_match;
private static IEqualityComparer<T> s_comparer;
public static void SetMatchOn(IEnumerable<T> match, IEqualityComparer<T> comparer)
{
s_match = match;
s_comparer = comparer;
}
public static bool Match(T item)
{
IEnumerator<T> e_match;
if (s_match == null) return false;
e_match = s_match.GetEnumerator();
while (e_match.MoveNext())
{
if (s_comparer.Equals(item, e_match.Current))
{
return true;
}
}
return false;
}
}
// contains a bunch of predicates for tests.
private class PredicateMatch
{
public static HashSet<int> set = null;
public static bool remove = true;
public static int limit = 0;
public static bool Match60(int item)
{
set.Add(item);
return true;
}
public static bool Match61(int item)
{
set.Add(item);
return false;
}
public static bool Match62(int item)
{
set.Remove(item);
return true;
}
public static bool Match63(int item)
{
set.Remove(item);
return false;
}
public static bool Match64(int item)
{
set.Add(item + 10);
return true;
}
public static bool Match65(int item)
{
set.Add(item + 10);
return false;
}
public static bool Match66(int item)
{
remove = !remove;
return !remove;
}
public static bool Match67(int item)
{
if (set == null) return false;
return (set.Count > limit);
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.TestingHost;
using UnitTests.GrainInterfaces;
using Xunit;
using Xunit.Abstractions;
namespace TestExtensions.Runners
{
public class GrainPersistenceTestsRunner : OrleansTestingBase
{
private readonly ITestOutputHelper output;
private readonly string grainNamespace;
private readonly BaseTestClusterFixture fixture;
protected readonly ILogger logger;
protected TestCluster HostedCluster { get; private set; }
public GrainPersistenceTestsRunner(ITestOutputHelper output, BaseTestClusterFixture fixture, string grainNamespace = "UnitTests.Grains")
{
this.output = output;
this.fixture = fixture;
this.grainNamespace = grainNamespace;
this.logger = fixture.Logger;
HostedCluster = fixture.HostedCluster;
}
public IGrainFactory GrainFactory => fixture.GrainFactory;
[Fact]
public async Task Grain_GrainStorage_Delete()
{
Guid id = Guid.NewGuid();
IGrainStorageTestGrain grain = this.GrainFactory.GetGrain<IGrainStorageTestGrain>(id, this.grainNamespace);
await grain.DoWrite(1);
await grain.DoDelete();
int val = await grain.GetValue(); // Should this throw instead?
Assert.Equal(0, val); // "Value after Delete"
await grain.DoWrite(2);
val = await grain.GetValue();
Assert.Equal(2, val); // "Value after Delete + New Write"
}
[Fact]
public async Task Grain_GrainStorage_Read()
{
Guid id = Guid.NewGuid();
IGrainStorageTestGrain grain = this.GrainFactory.GetGrain<IGrainStorageTestGrain>(id, this.grainNamespace);
int val = await grain.GetValue();
Assert.Equal(0, val); // "Initial value"
}
[Fact]
public async Task Grain_GuidKey_GrainStorage_Read_Write()
{
Guid id = Guid.NewGuid();
IGrainStorageTestGrain grain = this.GrainFactory.GetGrain<IGrainStorageTestGrain>(id, this.grainNamespace);
int val = await grain.GetValue();
Assert.Equal(0, val); // "Initial value"
await grain.DoWrite(1);
val = await grain.GetValue();
Assert.Equal(1, val); // "Value after Write-1"
await grain.DoWrite(2);
val = await grain.GetValue();
Assert.Equal(2, val); // "Value after Write-2"
val = await grain.DoRead();
Assert.Equal(2, val); // "Value after Re-Read"
}
[Fact]
public async Task Grain_LongKey_GrainStorage_Read_Write()
{
long id = random.Next();
IGrainStorageTestGrain_LongKey grain = this.GrainFactory.GetGrain<IGrainStorageTestGrain_LongKey>(id, this.grainNamespace);
int val = await grain.GetValue();
Assert.Equal(0, val); // "Initial value"
await grain.DoWrite(1);
val = await grain.GetValue();
Assert.Equal(1, val); // "Value after Write-1"
await grain.DoWrite(2);
val = await grain.GetValue();
Assert.Equal(2, val); // "Value after Write-2"
val = await grain.DoRead();
Assert.Equal(2, val); // "Value after Re-Read"
}
[Fact]
public async Task Grain_LongKeyExtended_GrainStorage_Read_Write()
{
long id = random.Next();
string extKey = random.Next().ToString(CultureInfo.InvariantCulture);
IGrainStorageTestGrain_LongExtendedKey
grain = this.GrainFactory.GetGrain<IGrainStorageTestGrain_LongExtendedKey>(id, extKey, this.grainNamespace);
int val = await grain.GetValue();
Assert.Equal(0, val); // "Initial value"
await grain.DoWrite(1);
val = await grain.GetValue();
Assert.Equal(1, val); // "Value after Write-1"
await grain.DoWrite(2);
val = await grain.GetValue();
Assert.Equal(2, val); // "Value after Write-2"
val = await grain.DoRead();
Assert.Equal(2, val); // "Value after DoRead"
val = await grain.GetValue();
Assert.Equal(2, val); // "Value after Re-Read"
string extKeyValue = await grain.GetExtendedKeyValue();
Assert.Equal(extKey, extKeyValue); // "Extended Key"
}
[Fact]
public async Task Grain_GuidKeyExtended_GrainStorage_Read_Write()
{
var id = Guid.NewGuid();
string extKey = random.Next().ToString(CultureInfo.InvariantCulture);
IGrainStorageTestGrain_GuidExtendedKey
grain = this.GrainFactory.GetGrain<IGrainStorageTestGrain_GuidExtendedKey>(id, extKey, this.grainNamespace);
int val = await grain.GetValue();
Assert.Equal(0, val); // "Initial value"
await grain.DoWrite(1);
val = await grain.GetValue();
Assert.Equal(1, val); // "Value after Write-1"
await grain.DoWrite(2);
val = await grain.GetValue();
Assert.Equal(2, val); // "Value after Write-2"
val = await grain.DoRead();
Assert.Equal(2, val); // "Value after DoRead"
val = await grain.GetValue();
Assert.Equal(2, val); // "Value after Re-Read"
string extKeyValue = await grain.GetExtendedKeyValue();
Assert.Equal(extKey, extKeyValue); // "Extended Key"
}
[Fact]
public async Task Grain_Generic_GrainStorage_Read_Write()
{
long id = random.Next();
IGrainStorageGenericGrain<int> grain = this.GrainFactory.GetGrain<IGrainStorageGenericGrain<int>>(id, this.grainNamespace);
int val = await grain.GetValue();
Assert.Equal(0, val); // "Initial value"
await grain.DoWrite(1);
val = await grain.GetValue();
Assert.Equal(1, val); // "Value after Write-1"
await grain.DoWrite(2);
val = await grain.GetValue();
Assert.Equal(2, val); // "Value after Write-2"
val = await grain.DoRead();
Assert.Equal(2, val); // "Value after Re-Read"
}
[Fact]
public async Task Grain_NestedGeneric_GrainStorage_Read_Write()
{
long id = random.Next();
IGrainStorageGenericGrain<List<int>> grain = this.GrainFactory.GetGrain<IGrainStorageGenericGrain<List<int>>>(id, this.grainNamespace);
var val = await grain.GetValue();
Assert.Null(val); // "Initial value"
await grain.DoWrite(new List<int> { 1 });
val = await grain.GetValue();
Assert.Equal(new List<int> { 1 }, val); // "Value after Write-1"
await grain.DoWrite(new List<int> { 1, 2 });
val = await grain.GetValue();
Assert.Equal(new List<int> { 1, 2 }, val); // "Value after Write-2"
val = await grain.DoRead();
Assert.Equal(new List<int> { 1, 2 }, val); // "Value after Re-Read"
}
[Fact]
public async Task Grain_Generic_GrainStorage_DiffTypes()
{
long id1 = random.Next();
long id2 = id1;
long id3 = id1;
IGrainStorageGenericGrain<int> grain1 = this.GrainFactory.GetGrain<IGrainStorageGenericGrain<int>>(id1, this.grainNamespace);
IGrainStorageGenericGrain<string> grain2 = this.GrainFactory.GetGrain<IGrainStorageGenericGrain<string>>(id2, this.grainNamespace);
IGrainStorageGenericGrain<double> grain3 = this.GrainFactory.GetGrain<IGrainStorageGenericGrain<double>>(id3, this.grainNamespace);
int val1 = await grain1.GetValue();
Assert.Equal(0, val1); // "Initial value - 1"
string val2 = await grain2.GetValue();
Assert.Null(val2); // "Initial value - 2"
double val3 = await grain3.GetValue();
Assert.Equal(0.0, val3); // "Initial value - 3"
int expected1 = 1;
await grain1.DoWrite(expected1);
val1 = await grain1.GetValue();
Assert.Equal(expected1, val1); // "Value after Write#1 - 1"
string expected2 = "Three";
await grain2.DoWrite(expected2);
val2 = await grain2.GetValue();
Assert.Equal(expected2, val2); // "Value after Write#1 - 2"
double expected3 = 5.1;
await grain3.DoWrite(expected3);
val3 = await grain3.GetValue();
Assert.Equal(expected3, val3); // "Value after Write#1 - 3"
val1 = await grain1.GetValue();
Assert.Equal(expected1, val1); // "Value before Write#2 - 1"
expected1 = 2;
await grain1.DoWrite(expected1);
val1 = await grain1.GetValue();
Assert.Equal(expected1, val1); // "Value after Write#2 - 1"
val1 = await grain1.DoRead();
Assert.Equal(expected1, val1); // "Value after Re-Read - 1"
val2 = await grain2.GetValue();
Assert.Equal(expected2, val2); // "Value before Write#2 - 2"
expected2 = "Four";
await grain2.DoWrite(expected2);
val2 = await grain2.GetValue();
Assert.Equal(expected2, val2); // "Value after Write#2 - 2"
val2 = await grain2.DoRead();
Assert.Equal(expected2, val2); // "Value after Re-Read - 2"
val3 = await grain3.GetValue();
Assert.Equal(expected3, val3); // "Value before Write#2 - 3"
expected3 = 6.2;
await grain3.DoWrite(expected3);
val3 = await grain3.GetValue();
Assert.Equal(expected3, val3); // "Value after Write#2 - 3"
val3 = await grain3.DoRead();
Assert.Equal(expected3, val3); // "Value after Re-Read - 3"
}
[Fact]
public async Task Grain_GrainStorage_SiloRestart()
{
var initialServiceId = fixture.GetClientServiceId();
output.WriteLine("ClusterId={0} ServiceId={1}", this.HostedCluster.Options.ClusterId, initialServiceId);
Guid id = Guid.NewGuid();
IGrainStorageTestGrain grain = this.GrainFactory.GetGrain<IGrainStorageTestGrain>(id, this.grainNamespace);
int val = await grain.GetValue();
Assert.Equal(0, val); // "Initial value"
await grain.DoWrite(1);
var serviceId = await this.GrainFactory.GetGrain<IServiceIdGrain>(Guid.Empty).GetServiceId();
Assert.Equal(initialServiceId, serviceId); // "ServiceId same before restart."
output.WriteLine("About to reset Silos");
foreach (var silo in this.HostedCluster.GetActiveSilos().ToList())
{
await this.HostedCluster.RestartSiloAsync(silo);
}
await this.HostedCluster.InitializeClientAsync();
output.WriteLine("Silos restarted");
serviceId = await this.GrainFactory.GetGrain<IServiceIdGrain>(Guid.Empty).GetServiceId();
grain = this.GrainFactory.GetGrain<IGrainStorageTestGrain>(id, this.grainNamespace);
output.WriteLine("ClusterId={0} ServiceId={1}", this.HostedCluster.Options.ClusterId, serviceId);
Assert.Equal(initialServiceId, serviceId); // "ServiceId same after restart."
val = await grain.GetValue();
Assert.Equal(1, val); // "Value after Write-1"
await grain.DoWrite(2);
val = await grain.GetValue();
Assert.Equal(2, val); // "Value after Write-2"
val = await grain.DoRead();
Assert.Equal(2, val); // "Value after Re-Read"
}
}
}
| |
/*
* Exchange Web Services Managed API
*
* 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.
*/
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml;
/// <summary>
/// EWS utilities
/// </summary>
internal static class EwsUtilities
{
#region Private members
/// <summary>
/// Map from XML element names to ServiceObject type and constructors.
/// </summary>
private static LazyMember<ServiceObjectInfo> serviceObjectInfo = new LazyMember<ServiceObjectInfo>(
delegate()
{
return new ServiceObjectInfo();
});
/// <summary>
/// Version of API binary.
/// </summary>
private static LazyMember<string> buildVersion = new LazyMember<string>(
delegate()
{
try
{
FileVersionInfo fileInfo = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location);
return fileInfo.FileVersion;
}
catch
{
// OM:2026839 When run in an environment with partial trust, fetching the build version blows up.
// Just return a hardcoded value on failure.
return "0.0";
}
});
/// <summary>
/// Dictionary of enum type to ExchangeVersion maps.
/// </summary>
private static LazyMember<Dictionary<Type, Dictionary<Enum, ExchangeVersion>>> enumVersionDictionaries = new LazyMember<Dictionary<Type, Dictionary<Enum, ExchangeVersion>>>(
() => new Dictionary<Type, Dictionary<Enum, ExchangeVersion>>()
{
{ typeof(WellKnownFolderName), BuildEnumDict(typeof(WellKnownFolderName)) },
{ typeof(ItemTraversal), BuildEnumDict(typeof(ItemTraversal)) },
{ typeof(ConversationQueryTraversal), BuildEnumDict(typeof(ConversationQueryTraversal)) },
{ typeof(FileAsMapping), BuildEnumDict(typeof(FileAsMapping)) },
{ typeof(EventType), BuildEnumDict(typeof(EventType)) },
{ typeof(MeetingRequestsDeliveryScope), BuildEnumDict(typeof(MeetingRequestsDeliveryScope)) },
{ typeof(ViewFilter), BuildEnumDict(typeof(ViewFilter)) },
});
/// <summary>
/// Dictionary of enum type to schema-name-to-enum-value maps.
/// </summary>
private static LazyMember<Dictionary<Type, Dictionary<string, Enum>>> schemaToEnumDictionaries = new LazyMember<Dictionary<Type, Dictionary<string, Enum>>>(
() => new Dictionary<Type, Dictionary<string, Enum>>
{
{ typeof(EventType), BuildSchemaToEnumDict(typeof(EventType)) },
{ typeof(MailboxType), BuildSchemaToEnumDict(typeof(MailboxType)) },
{ typeof(FileAsMapping), BuildSchemaToEnumDict(typeof(FileAsMapping)) },
{ typeof(RuleProperty), BuildSchemaToEnumDict(typeof(RuleProperty)) },
{ typeof(WellKnownFolderName), BuildSchemaToEnumDict(typeof(WellKnownFolderName)) },
});
/// <summary>
/// Dictionary of enum type to enum-value-to-schema-name maps.
/// </summary>
private static LazyMember<Dictionary<Type, Dictionary<Enum, string>>> enumToSchemaDictionaries = new LazyMember<Dictionary<Type, Dictionary<Enum, string>>>(
() => new Dictionary<Type, Dictionary<Enum, string>>
{
{ typeof(EventType), BuildEnumToSchemaDict(typeof(EventType)) },
{ typeof(MailboxType), BuildEnumToSchemaDict(typeof(MailboxType)) },
{ typeof(FileAsMapping), BuildEnumToSchemaDict(typeof(FileAsMapping)) },
{ typeof(RuleProperty), BuildEnumToSchemaDict(typeof(RuleProperty)) },
{ typeof(WellKnownFolderName), BuildEnumToSchemaDict(typeof(WellKnownFolderName)) },
});
/// <summary>
/// Dictionary to map from special CLR type names to their "short" names.
/// </summary>
private static LazyMember<Dictionary<string, string>> typeNameToShortNameMap = new LazyMember<Dictionary<string, string>>(
() => new Dictionary<string, string>
{
{ "Boolean", "bool" },
{ "Int16", "short" },
{ "Int32", "int" },
{ "String", "string" }
});
#endregion
#region Constants
internal const string XSFalse = "false";
internal const string XSTrue = "true";
internal const string EwsTypesNamespacePrefix = "t";
internal const string EwsMessagesNamespacePrefix = "m";
internal const string EwsErrorsNamespacePrefix = "e";
internal const string EwsSoapNamespacePrefix = "soap";
internal const string EwsXmlSchemaInstanceNamespacePrefix = "xsi";
internal const string PassportSoapFaultNamespacePrefix = "psf";
internal const string WSTrustFebruary2005NamespacePrefix = "wst";
internal const string WSAddressingNamespacePrefix = "wsa";
internal const string AutodiscoverSoapNamespacePrefix = "a";
internal const string WSSecurityUtilityNamespacePrefix = "wsu";
internal const string WSSecuritySecExtNamespacePrefix = "wsse";
internal const string EwsTypesNamespace = "http://schemas.microsoft.com/exchange/services/2006/types";
internal const string EwsMessagesNamespace = "http://schemas.microsoft.com/exchange/services/2006/messages";
internal const string EwsErrorsNamespace = "http://schemas.microsoft.com/exchange/services/2006/errors";
internal const string EwsSoapNamespace = "http://schemas.xmlsoap.org/soap/envelope/";
internal const string EwsSoap12Namespace = "http://www.w3.org/2003/05/soap-envelope";
internal const string EwsXmlSchemaInstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance";
internal const string PassportSoapFaultNamespace = "http://schemas.microsoft.com/Passport/SoapServices/SOAPFault";
internal const string WSTrustFebruary2005Namespace = "http://schemas.xmlsoap.org/ws/2005/02/trust";
internal const string WSAddressingNamespace = "http://www.w3.org/2005/08/addressing"; // "http://schemas.xmlsoap.org/ws/2004/08/addressing";
internal const string AutodiscoverSoapNamespace = "http://schemas.microsoft.com/exchange/2010/Autodiscover";
internal const string WSSecurityUtilityNamespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd";
internal const string WSSecuritySecExtNamespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
/// <summary>
/// Regular expression for legal domain names.
/// </summary>
internal const string DomainRegex = "^[-a-zA-Z0-9_.]+$";
#endregion
/// <summary>
/// Asserts that the specified condition if true.
/// </summary>
/// <param name="condition">Assertion.</param>
/// <param name="caller">The caller.</param>
/// <param name="message">The message to use if assertion fails.</param>
internal static void Assert(
bool condition,
string caller,
string message)
{
Debug.Assert(
condition,
string.Format("[{0}] {1}", caller, message));
}
/// <summary>
/// Gets the namespace prefix from an XmlNamespace enum value.
/// </summary>
/// <param name="xmlNamespace">The XML namespace.</param>
/// <returns>Namespace prefix string.</returns>
internal static string GetNamespacePrefix(XmlNamespace xmlNamespace)
{
switch (xmlNamespace)
{
case XmlNamespace.Types:
return EwsTypesNamespacePrefix;
case XmlNamespace.Messages:
return EwsMessagesNamespacePrefix;
case XmlNamespace.Errors:
return EwsErrorsNamespacePrefix;
case XmlNamespace.Soap:
case XmlNamespace.Soap12:
return EwsSoapNamespacePrefix;
case XmlNamespace.XmlSchemaInstance:
return EwsXmlSchemaInstanceNamespacePrefix;
case XmlNamespace.PassportSoapFault:
return PassportSoapFaultNamespacePrefix;
case XmlNamespace.WSTrustFebruary2005:
return WSTrustFebruary2005NamespacePrefix;
case XmlNamespace.WSAddressing:
return WSAddressingNamespacePrefix;
case XmlNamespace.Autodiscover:
return AutodiscoverSoapNamespacePrefix;
default:
return string.Empty;
}
}
/// <summary>
/// Gets the namespace URI from an XmlNamespace enum value.
/// </summary>
/// <param name="xmlNamespace">The XML namespace.</param>
/// <returns>Uri as string</returns>
internal static string GetNamespaceUri(XmlNamespace xmlNamespace)
{
switch (xmlNamespace)
{
case XmlNamespace.Types:
return EwsTypesNamespace;
case XmlNamespace.Messages:
return EwsMessagesNamespace;
case XmlNamespace.Errors:
return EwsErrorsNamespace;
case XmlNamespace.Soap:
return EwsSoapNamespace;
case XmlNamespace.Soap12:
return EwsSoap12Namespace;
case XmlNamespace.XmlSchemaInstance:
return EwsXmlSchemaInstanceNamespace;
case XmlNamespace.PassportSoapFault:
return PassportSoapFaultNamespace;
case XmlNamespace.WSTrustFebruary2005:
return WSTrustFebruary2005Namespace;
case XmlNamespace.WSAddressing:
return WSAddressingNamespace;
case XmlNamespace.Autodiscover:
return AutodiscoverSoapNamespace;
default:
return string.Empty;
}
}
/// <summary>
/// Gets the XmlNamespace enum value from a namespace Uri.
/// </summary>
/// <param name="namespaceUri">XML namespace Uri.</param>
/// <returns>XmlNamespace enum value.</returns>
internal static XmlNamespace GetNamespaceFromUri(string namespaceUri)
{
switch (namespaceUri)
{
case EwsErrorsNamespace:
return XmlNamespace.Errors;
case EwsTypesNamespace:
return XmlNamespace.Types;
case EwsMessagesNamespace:
return XmlNamespace.Messages;
case EwsSoapNamespace:
return XmlNamespace.Soap;
case EwsSoap12Namespace:
return XmlNamespace.Soap12;
case EwsXmlSchemaInstanceNamespace:
return XmlNamespace.XmlSchemaInstance;
case PassportSoapFaultNamespace:
return XmlNamespace.PassportSoapFault;
case WSTrustFebruary2005Namespace:
return XmlNamespace.WSTrustFebruary2005;
case WSAddressingNamespace:
return XmlNamespace.WSAddressing;
default:
return XmlNamespace.NotSpecified;
}
}
/// <summary>
/// Creates EWS object based on XML element name.
/// </summary>
/// <typeparam name="TServiceObject">The type of the service object.</typeparam>
/// <param name="service">The service.</param>
/// <param name="xmlElementName">Name of the XML element.</param>
/// <returns>Service object.</returns>
internal static TServiceObject CreateEwsObjectFromXmlElementName<TServiceObject>(ExchangeService service, string xmlElementName)
where TServiceObject : ServiceObject
{
Type itemClass;
if (EwsUtilities.serviceObjectInfo.Member.XmlElementNameToServiceObjectClassMap.TryGetValue(xmlElementName, out itemClass))
{
CreateServiceObjectWithServiceParam creationDelegate;
if (EwsUtilities.serviceObjectInfo.Member.ServiceObjectConstructorsWithServiceParam.TryGetValue(itemClass, out creationDelegate))
{
return (TServiceObject)creationDelegate(service);
}
else
{
throw new ArgumentException(Strings.NoAppropriateConstructorForItemClass);
}
}
else
{
return default(TServiceObject);
}
}
/// <summary>
/// Creates Item from Item class.
/// </summary>
/// <param name="itemAttachment">The item attachment.</param>
/// <param name="itemClass">The item class.</param>
/// <param name="isNew">If true, item attachment is new.</param>
/// <returns>New Item.</returns>
internal static Item CreateItemFromItemClass(
ItemAttachment itemAttachment,
Type itemClass,
bool isNew)
{
CreateServiceObjectWithAttachmentParam creationDelegate;
if (EwsUtilities.serviceObjectInfo.Member.ServiceObjectConstructorsWithAttachmentParam.TryGetValue(itemClass, out creationDelegate))
{
return (Item)creationDelegate(itemAttachment, isNew);
}
else
{
throw new ArgumentException(Strings.NoAppropriateConstructorForItemClass);
}
}
/// <summary>
/// Creates Item based on XML element name.
/// </summary>
/// <param name="itemAttachment">The item attachment.</param>
/// <param name="xmlElementName">Name of the XML element.</param>
/// <returns>New Item.</returns>
internal static Item CreateItemFromXmlElementName(ItemAttachment itemAttachment, string xmlElementName)
{
Type itemClass;
if (EwsUtilities.serviceObjectInfo.Member.XmlElementNameToServiceObjectClassMap.TryGetValue(xmlElementName, out itemClass))
{
return CreateItemFromItemClass(itemAttachment, itemClass, false);
}
else
{
return null;
}
}
/// <summary>
/// Gets the expected item type based on the local name.
/// </summary>
/// <param name="xmlElementName"></param>
/// <returns></returns>
internal static Type GetItemTypeFromXmlElementName(string xmlElementName)
{
Type itemClass = null;
EwsUtilities.serviceObjectInfo.Member.XmlElementNameToServiceObjectClassMap.TryGetValue(xmlElementName, out itemClass);
return itemClass;
}
/// <summary>
/// Finds the first item of type TItem (not a descendant type) in the specified collection.
/// </summary>
/// <typeparam name="TItem">The type of the item to find.</typeparam>
/// <param name="items">The collection.</param>
/// <returns>A TItem instance or null if no instance of TItem could be found.</returns>
internal static TItem FindFirstItemOfType<TItem>(IEnumerable<Item> items)
where TItem : Item
{
Type itemType = typeof(TItem);
foreach (Item item in items)
{
// We're looking for an exact class match here.
if (item.GetType() == itemType)
{
return (TItem)item;
}
}
return null;
}
#region Tracing routines
/// <summary>
/// Write trace start element.
/// </summary>
/// <param name="writer">The writer to write the start element to.</param>
/// <param name="traceTag">The trace tag.</param>
/// <param name="includeVersion">If true, include build version attribute.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Exchange.Usage", "EX0009:DoNotUseDateTimeNowOrFromFileTime", Justification = "Client API")]
private static void WriteTraceStartElement(
XmlWriter writer,
string traceTag,
bool includeVersion)
{
writer.WriteStartElement("Trace");
writer.WriteAttributeString("Tag", traceTag);
writer.WriteAttributeString("Tid", Thread.CurrentThread.ManagedThreadId.ToString());
writer.WriteAttributeString("Time", DateTime.UtcNow.ToString("u", DateTimeFormatInfo.InvariantInfo));
if (includeVersion)
{
writer.WriteAttributeString("Version", EwsUtilities.BuildVersion);
}
}
/// <summary>
/// Format log message.
/// </summary>
/// <param name="entryKind">Kind of the entry.</param>
/// <param name="logEntry">The log entry.</param>
/// <returns>XML log entry as a string.</returns>
internal static string FormatLogMessage(string entryKind, string logEntry)
{
StringBuilder sb = new StringBuilder();
using (StringWriter writer = new StringWriter(sb))
{
using (XmlTextWriter xmlWriter = new XmlTextWriter(writer))
{
xmlWriter.Formatting = Formatting.Indented;
EwsUtilities.WriteTraceStartElement(xmlWriter, entryKind, false);
xmlWriter.WriteWhitespace(Environment.NewLine);
xmlWriter.WriteValue(logEntry);
xmlWriter.WriteWhitespace(Environment.NewLine);
xmlWriter.WriteEndElement(); // Trace
xmlWriter.WriteWhitespace(Environment.NewLine);
}
}
return sb.ToString();
}
/// <summary>
/// Format the HTTP headers.
/// </summary>
/// <param name="sb">StringBuilder.</param>
/// <param name="headers">The HTTP headers.</param>
private static void FormatHttpHeaders(StringBuilder sb, WebHeaderCollection headers)
{
foreach (string key in headers.Keys)
{
sb.Append(
string.Format(
"{0}: {1}\n",
key,
headers[key]));
}
}
/// <summary>
/// Format request HTTP headers.
/// </summary>
/// <param name="request">The HTTP request.</param>
internal static string FormatHttpRequestHeaders(IEwsHttpWebRequest request)
{
StringBuilder sb = new StringBuilder();
sb.Append(string.Format("{0} {1} HTTP/1.1\n", request.Method, request.RequestUri.AbsolutePath));
EwsUtilities.FormatHttpHeaders(sb, request.Headers);
sb.Append("\n");
return sb.ToString();
}
/// <summary>
/// Format response HTTP headers.
/// </summary>
/// <param name="response">The HTTP response.</param>
internal static string FormatHttpResponseHeaders(IEwsHttpWebResponse response)
{
StringBuilder sb = new StringBuilder();
sb.Append(
string.Format(
"HTTP/{0} {1} {2}\n",
response.ProtocolVersion,
(int)response.StatusCode,
response.StatusDescription));
sb.Append(EwsUtilities.FormatHttpHeaders(response.Headers));
sb.Append("\n");
return sb.ToString();
}
/// <summary>
/// Format request HTTP headers.
/// </summary>
/// <param name="request">The HTTP request.</param>
internal static string FormatHttpRequestHeaders(HttpWebRequest request)
{
StringBuilder sb = new StringBuilder();
sb.Append(
string.Format(
"{0} {1} HTTP/{2}\n",
request.Method.ToUpperInvariant(),
request.RequestUri.AbsolutePath,
request.ProtocolVersion));
sb.Append(EwsUtilities.FormatHttpHeaders(request.Headers));
sb.Append("\n");
return sb.ToString();
}
/// <summary>
/// Formats HTTP headers.
/// </summary>
/// <param name="headers">The headers.</param>
/// <returns>Headers as a string</returns>
private static string FormatHttpHeaders(WebHeaderCollection headers)
{
StringBuilder sb = new StringBuilder();
foreach (string key in headers.Keys)
{
sb.Append(
string.Format(
"{0}: {1}\n",
key,
headers[key]));
}
return sb.ToString();
}
/// <summary>
/// Format XML content in a MemoryStream for message.
/// </summary>
/// <param name="entryKind">Kind of the entry.</param>
/// <param name="memoryStream">The memory stream.</param>
/// <returns>XML log entry as a string.</returns>
internal static string FormatLogMessageWithXmlContent(string entryKind, MemoryStream memoryStream)
{
StringBuilder sb = new StringBuilder();
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
settings.IgnoreComments = true;
settings.IgnoreWhitespace = true;
settings.CloseInput = false;
// Remember the current location in the MemoryStream.
long lastPosition = memoryStream.Position;
// Rewind the position since we want to format the entire contents.
memoryStream.Position = 0;
try
{
using (XmlReader reader = XmlReader.Create(memoryStream, settings))
{
using (StringWriter writer = new StringWriter(sb))
{
using (XmlTextWriter xmlWriter = new XmlTextWriter(writer))
{
xmlWriter.Formatting = Formatting.Indented;
EwsUtilities.WriteTraceStartElement(xmlWriter, entryKind, true);
while (!reader.EOF)
{
xmlWriter.WriteNode(reader, true);
}
xmlWriter.WriteEndElement(); // Trace
xmlWriter.WriteWhitespace(Environment.NewLine);
}
}
}
}
catch (XmlException)
{
// We tried to format the content as "pretty" XML. Apparently the content is
// not well-formed XML or isn't XML at all. Fallback and treat it as plain text.
sb.Length = 0;
memoryStream.Position = 0;
sb.Append(Encoding.UTF8.GetString(memoryStream.GetBuffer(), 0, (int)memoryStream.Length));
}
// Restore Position in the stream.
memoryStream.Position = lastPosition;
return sb.ToString();
}
#endregion
#region Stream routines
/// <summary>
/// Copies source stream to target.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="target">The target.</param>
internal static void CopyStream(Stream source, Stream target)
{
// See if this is a MemoryStream -- we can use WriteTo.
MemoryStream memContentStream = source as MemoryStream;
if (memContentStream != null)
{
memContentStream.WriteTo(target);
}
else
{
// Otherwise, copy data through a buffer
byte[] buffer = new byte[4096];
int bufferSize = buffer.Length;
int bytesRead = source.Read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
target.Write(buffer, 0, bytesRead);
bytesRead = source.Read(buffer, 0, bufferSize);
}
}
}
#endregion
/// <summary>
/// Gets the build version.
/// </summary>
/// <value>The build version.</value>
internal static string BuildVersion
{
get { return EwsUtilities.buildVersion.Member; }
}
#region Conversion routines
/// <summary>
/// Convert bool to XML Schema bool.
/// </summary>
/// <param name="value">Bool value.</param>
/// <returns>String representing bool value in XML Schema.</returns>
internal static string BoolToXSBool(bool value)
{
return value ? EwsUtilities.XSTrue : EwsUtilities.XSFalse;
}
/// <summary>
/// Parses an enum value list.
/// </summary>
/// <typeparam name="T">Type of value.</typeparam>
/// <param name="list">The list.</param>
/// <param name="value">The value.</param>
/// <param name="separators">The separators.</param>
internal static void ParseEnumValueList<T>(
IList<T> list,
string value,
params char[] separators)
where T : struct
{
EwsUtilities.Assert(
typeof(T).IsEnum,
"EwsUtilities.ParseEnumValueList",
"T is not an enum type.");
if (string.IsNullOrEmpty(value))
{
return;
}
string[] enumValues = value.Split(separators);
foreach (string enumValue in enumValues)
{
list.Add((T)Enum.Parse(typeof(T), enumValue, false));
}
}
/// <summary>
/// Converts an enum to a string, using the mapping dictionaries if appropriate.
/// </summary>
/// <param name="value">The enum value to be serialized</param>
/// <returns>String representation of enum to be used in the protocol</returns>
internal static string SerializeEnum(Enum value)
{
Dictionary<Enum, string> enumToStringDict;
string strValue;
if (enumToSchemaDictionaries.Member.TryGetValue(value.GetType(), out enumToStringDict) &&
enumToStringDict.TryGetValue(value, out strValue))
{
return strValue;
}
else
{
return value.ToString();
}
}
/// <summary>
/// Parses specified value based on type.
/// </summary>
/// <typeparam name="T">Type of value.</typeparam>
/// <param name="value">The value.</param>
/// <returns>Value of type T.</returns>
internal static T Parse<T>(string value)
{
if (typeof(T).IsEnum)
{
Dictionary<string, Enum> stringToEnumDict;
Enum enumValue;
if (schemaToEnumDictionaries.Member.TryGetValue(typeof(T), out stringToEnumDict) &&
stringToEnumDict.TryGetValue(value, out enumValue))
{
// This double-casting is ugly, but necessary. By this point, we know that T is an Enum
// (same as returned by the dictionary), but the compiler can't prove it. Thus, the
// up-cast before we can down-cast.
return (T)((object)enumValue);
}
else
{
return (T)Enum.Parse(typeof(T), value, false);
}
}
else
{
return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture);
}
}
/// <summary>
/// Tries to parses the specified value to the specified type.
/// </summary>
/// <typeparam name="T">The type into which to cast the provided value.</typeparam>
/// <param name="value">The value to parse.</param>
/// <param name="result">The value cast to the specified type, if TryParse succeeds. Otherwise, the value of result is indeterminate.</param>
/// <returns>True if value could be parsed; otherwise, false.</returns>
internal static bool TryParse<T>(string value, out T result)
{
try
{
result = EwsUtilities.Parse<T>(value);
return true;
}
//// Catch all exceptions here, we're not interested in the reason why TryParse failed.
catch (Exception)
{
result = default(T);
return false;
}
}
/// <summary>
/// Converts the specified date and time from one time zone to another.
/// </summary>
/// <param name="dateTime">The date time to convert.</param>
/// <param name="sourceTimeZone">The source time zone.</param>
/// <param name="destinationTimeZone">The destination time zone.</param>
/// <returns>A DateTime that holds the converted</returns>
internal static DateTime ConvertTime(
DateTime dateTime,
TimeZoneInfo sourceTimeZone,
TimeZoneInfo destinationTimeZone)
{
try
{
return TimeZoneInfo.ConvertTime(
dateTime,
sourceTimeZone,
destinationTimeZone);
}
catch (ArgumentException e)
{
throw new TimeZoneConversionException(
string.Format(
Strings.CannotConvertBetweenTimeZones,
EwsUtilities.DateTimeToXSDateTime(dateTime),
sourceTimeZone.DisplayName,
destinationTimeZone.DisplayName),
e);
}
}
/// <summary>
/// Reads the string as date time, assuming it is unbiased (e.g. 2009/01/01T08:00)
/// and scoped to service's time zone.
/// </summary>
/// <param name="dateString">The date string.</param>
/// <param name="service">The service.</param>
/// <returns>The string's value as a DateTime object.</returns>
internal static DateTime ParseAsUnbiasedDatetimescopedToServicetimeZone(string dateString, ExchangeService service)
{
// Convert the element's value to a DateTime with no adjustment.
DateTime tempDate = DateTime.Parse(dateString, CultureInfo.InvariantCulture);
// Set the kind according to the service's time zone
if (service.TimeZone == TimeZoneInfo.Utc)
{
return new DateTime(tempDate.Ticks, DateTimeKind.Utc);
}
else if (EwsUtilities.IsLocalTimeZone(service.TimeZone))
{
return new DateTime(tempDate.Ticks, DateTimeKind.Local);
}
else
{
return new DateTime(tempDate.Ticks, DateTimeKind.Unspecified);
}
}
/// <summary>
/// Determines whether the specified time zone is the same as the system's local time zone.
/// </summary>
/// <param name="timeZone">The time zone to check.</param>
/// <returns>
/// <c>true</c> if the specified time zone is the same as the system's local time zone; otherwise, <c>false</c>.
/// </returns>
internal static bool IsLocalTimeZone(TimeZoneInfo timeZone)
{
return (TimeZoneInfo.Local == timeZone) || (TimeZoneInfo.Local.Id == timeZone.Id && TimeZoneInfo.Local.HasSameRules(timeZone));
}
/// <summary>
/// Convert DateTime to XML Schema date.
/// </summary>
/// <param name="date">The date to be converted.</param>
/// <returns>String representation of DateTime.</returns>
internal static string DateTimeToXSDate(DateTime date)
{
// Depending on the current culture, DateTime formatter will
// translate dates from one culture to another (e.g. Gregorian to Lunar). The server
// however, considers all dates to be in Gregorian, so using the InvariantCulture will
// ensure this.
string format;
switch (date.Kind)
{
case DateTimeKind.Utc:
format = "yyyy-MM-ddZ";
break;
case DateTimeKind.Unspecified:
format = "yyyy-MM-dd";
break;
default: // DateTimeKind.Local is remaining
format = "yyyy-MM-ddzzz";
break;
}
return date.ToString(format, CultureInfo.InvariantCulture);
}
/// <summary>
/// Dates the DateTime into an XML schema date time.
/// </summary>
/// <param name="dateTime">The date time.</param>
/// <returns>String representation of DateTime.</returns>
internal static string DateTimeToXSDateTime(DateTime dateTime)
{
string format = "yyyy-MM-ddTHH:mm:ss.fff";
switch (dateTime.Kind)
{
case DateTimeKind.Utc:
format += "Z";
break;
case DateTimeKind.Local:
format += "zzz";
break;
default:
break;
}
// Depending on the current culture, DateTime formatter will replace ':' with
// the DateTimeFormatInfo.TimeSeparator property which may not be ':'. Force the proper string
// to be used by using the InvariantCulture.
return dateTime.ToString(format, CultureInfo.InvariantCulture);
}
/// <summary>
/// Convert EWS DayOfTheWeek enum to System.DayOfWeek.
/// </summary>
/// <param name="dayOfTheWeek">The day of the week.</param>
/// <returns>System.DayOfWeek value.</returns>
internal static DayOfWeek EwsToSystemDayOfWeek(DayOfTheWeek dayOfTheWeek)
{
if (dayOfTheWeek == DayOfTheWeek.Day ||
dayOfTheWeek == DayOfTheWeek.Weekday ||
dayOfTheWeek == DayOfTheWeek.WeekendDay)
{
throw new ArgumentException(
string.Format("Cannot convert {0} to System.DayOfWeek enum value", dayOfTheWeek),
"dayOfTheWeek");
}
else
{
return (DayOfWeek)dayOfTheWeek;
}
}
/// <summary>
/// Convert System.DayOfWeek type to EWS DayOfTheWeek.
/// </summary>
/// <param name="dayOfWeek">The dayOfWeek.</param>
/// <returns>EWS DayOfWeek value</returns>
internal static DayOfTheWeek SystemToEwsDayOfTheWeek(DayOfWeek dayOfWeek)
{
return (DayOfTheWeek)dayOfWeek;
}
/// <summary>
/// Takes a System.TimeSpan structure and converts it into an
/// xs:duration string as defined by the W3 Consortiums Recommendation
/// "XML Schema Part 2: Datatypes Second Edition",
/// http://www.w3.org/TR/xmlschema-2/#duration
/// </summary>
/// <param name="timeSpan">TimeSpan structure to convert</param>
/// <returns>xs:duration formatted string</returns>
internal static string TimeSpanToXSDuration(TimeSpan timeSpan)
{
// Optional '-' offset
string offsetStr = (timeSpan.TotalSeconds < 0) ? "-" : string.Empty;
// The TimeSpan structure does not have a Year or Month
// property, therefore we wouldn't be able to return an xs:duration
// string from a TimeSpan that included the nY or nM components.
return String.Format(
"{0}P{1}DT{2}H{3}M{4}S",
offsetStr,
Math.Abs(timeSpan.Days),
Math.Abs(timeSpan.Hours),
Math.Abs(timeSpan.Minutes),
Math.Abs(timeSpan.Seconds) + "." + Math.Abs(timeSpan.Milliseconds));
}
/// <summary>
/// Takes an xs:duration string as defined by the W3 Consortiums
/// Recommendation "XML Schema Part 2: Datatypes Second Edition",
/// http://www.w3.org/TR/xmlschema-2/#duration, and converts it
/// into a System.TimeSpan structure
/// </summary>
/// <remarks>
/// This method uses the following approximations:
/// 1 year = 365 days
/// 1 month = 30 days
/// Additionally, it only allows for four decimal points of
/// seconds precision.
/// </remarks>
/// <param name="xsDuration">xs:duration string to convert</param>
/// <returns>System.TimeSpan structure</returns>
internal static TimeSpan XSDurationToTimeSpan(string xsDuration)
{
Regex timeSpanParser = new Regex(
"(?<pos>-)?" +
"P" +
"((?<year>[0-9]+)Y)?" +
"((?<month>[0-9]+)M)?" +
"((?<day>[0-9]+)D)?" +
"(T" +
"((?<hour>[0-9]+)H)?" +
"((?<minute>[0-9]+)M)?" +
"((?<seconds>[0-9]+)(\\.(?<precision>[0-9]+))?S)?)?");
Match m = timeSpanParser.Match(xsDuration);
if (!m.Success)
{
throw new ArgumentException(Strings.XsDurationCouldNotBeParsed);
}
string token = m.Result("${pos}");
bool negative = false;
if (!String.IsNullOrEmpty(token))
{
negative = true;
}
// Year
token = m.Result("${year}");
int year = 0;
if (!String.IsNullOrEmpty(token))
{
year = Int32.Parse(token);
}
// Month
token = m.Result("${month}");
int month = 0;
if (!String.IsNullOrEmpty(token))
{
month = Int32.Parse(token);
}
// Day
token = m.Result("${day}");
int day = 0;
if (!String.IsNullOrEmpty(token))
{
day = Int32.Parse(token);
}
// Hour
token = m.Result("${hour}");
int hour = 0;
if (!String.IsNullOrEmpty(token))
{
hour = Int32.Parse(token);
}
// Minute
token = m.Result("${minute}");
int minute = 0;
if (!String.IsNullOrEmpty(token))
{
minute = Int32.Parse(token);
}
// Seconds
token = m.Result("${seconds}");
int seconds = 0;
if (!String.IsNullOrEmpty(token))
{
seconds = Int32.Parse(token);
}
int milliseconds = 0;
token = m.Result("${precision}");
// Only allowed 4 digits of precision
if (token.Length > 4)
{
token = token.Substring(0, 4);
}
if (!String.IsNullOrEmpty(token))
{
milliseconds = Int32.Parse(token);
}
// Apply conversions of year and months to days.
// Year = 365 days
// Month = 30 days
day = day + (year * 365) + (month * 30);
TimeSpan retval = new TimeSpan(day, hour, minute, seconds, milliseconds);
if (negative)
{
retval = -retval;
}
return retval;
}
/// <summary>
/// Converts the specified time span to its XSD representation.
/// </summary>
/// <param name="timeSpan">The time span.</param>
/// <returns>The XSD representation of the specified time span.</returns>
public static string TimeSpanToXSTime(TimeSpan timeSpan)
{
return string.Format(
"{0:00}:{1:00}:{2:00}",
timeSpan.Hours,
timeSpan.Minutes,
timeSpan.Seconds);
}
#endregion
#region Type Name utilities
/// <summary>
/// Gets the printable name of a CLR type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>Printable name.</returns>
public static string GetPrintableTypeName(Type type)
{
if (type.IsGenericType)
{
// Convert generic type to printable form (e.g. List<Item>)
string genericPrefix = type.Name.Substring(0, type.Name.IndexOf('`'));
StringBuilder nameBuilder = new StringBuilder(genericPrefix);
// Note: building array of generic parameters is done recursively. Each parameter could be any type.
string[] genericArgs = type.GetGenericArguments().ToList<Type>().ConvertAll<string>(t => GetPrintableTypeName(t)).ToArray<string>();
nameBuilder.Append("<");
nameBuilder.Append(string.Join(",", genericArgs));
nameBuilder.Append(">");
return nameBuilder.ToString();
}
else if (type.IsArray)
{
// Convert array type to printable form.
string arrayPrefix = type.Name.Substring(0, type.Name.IndexOf('['));
StringBuilder nameBuilder = new StringBuilder(EwsUtilities.GetSimplifiedTypeName(arrayPrefix));
for (int rank = 0; rank < type.GetArrayRank(); rank++)
{
nameBuilder.Append("[]");
}
return nameBuilder.ToString();
}
else
{
return EwsUtilities.GetSimplifiedTypeName(type.Name);
}
}
/// <summary>
/// Gets the printable name of a simple CLR type.
/// </summary>
/// <param name="typeName">The type name.</param>
/// <returns>Printable name.</returns>
private static string GetSimplifiedTypeName(string typeName)
{
// If type has a shortname (e.g. int for Int32) map to the short name.
string name;
return typeNameToShortNameMap.Member.TryGetValue(typeName, out name) ? name : typeName;
}
#endregion
#region EmailAddress parsing
/// <summary>
/// Gets the domain name from an email address.
/// </summary>
/// <param name="emailAddress">The email address.</param>
/// <returns>Domain name.</returns>
internal static string DomainFromEmailAddress(string emailAddress)
{
string[] emailAddressParts = emailAddress.Split('@');
if (emailAddressParts.Length != 2 || string.IsNullOrEmpty(emailAddressParts[1]))
{
throw new FormatException(Strings.InvalidEmailAddress);
}
return emailAddressParts[1];
}
#endregion
#region Method parameters validation routines
/// <summary>
/// Validates parameter (and allows null value).
/// </summary>
/// <param name="param">The param.</param>
/// <param name="paramName">Name of the param.</param>
internal static void ValidateParamAllowNull(object param, string paramName)
{
ISelfValidate selfValidate = param as ISelfValidate;
if (selfValidate != null)
{
try
{
selfValidate.Validate();
}
catch (ServiceValidationException e)
{
throw new ArgumentException(
Strings.ValidationFailed,
paramName,
e);
}
}
ServiceObject ewsObject = param as ServiceObject;
if (ewsObject != null)
{
if (ewsObject.IsNew)
{
throw new ArgumentException(Strings.ObjectDoesNotHaveId, paramName);
}
}
}
/// <summary>
/// Validates parameter (null value not allowed).
/// </summary>
/// <param name="param">The param.</param>
/// <param name="paramName">Name of the param.</param>
internal static void ValidateParam(object param, string paramName)
{
bool isValid;
string strParam = param as string;
if (strParam != null)
{
isValid = !string.IsNullOrEmpty(strParam);
}
else
{
isValid = param != null;
}
if (!isValid)
{
throw new ArgumentNullException(paramName);
}
ValidateParamAllowNull(param, paramName);
}
/// <summary>
/// Validates parameter collection.
/// </summary>
/// <param name="collection">The collection.</param>
/// <param name="paramName">Name of the param.</param>
internal static void ValidateParamCollection(IEnumerable collection, string paramName)
{
ValidateParam(collection, paramName);
int count = 0;
foreach (object obj in collection)
{
try
{
ValidateParam(obj, string.Format("collection[{0}]", count));
}
catch (ArgumentException e)
{
throw new ArgumentException(
string.Format("The element at position {0} is invalid", count),
paramName,
e);
}
count++;
}
if (count == 0)
{
throw new ArgumentException(Strings.CollectionIsEmpty, paramName);
}
}
/// <summary>
/// Validates string parameter to be non-empty string (null value allowed).
/// </summary>
/// <param name="param">The string parameter.</param>
/// <param name="paramName">Name of the parameter.</param>
internal static void ValidateNonBlankStringParamAllowNull(string param, string paramName)
{
if (param != null)
{
// Non-empty string has at least one character which is *not* a whitespace character
if (param.Length == param.CountMatchingChars((c) => Char.IsWhiteSpace(c)))
{
throw new ArgumentException(Strings.ArgumentIsBlankString, paramName);
}
}
}
/// <summary>
/// Validates string parameter to be non-empty string (null value not allowed).
/// </summary>
/// <param name="param">The string parameter.</param>
/// <param name="paramName">Name of the parameter.</param>
internal static void ValidateNonBlankStringParam(string param, string paramName)
{
if (param == null)
{
throw new ArgumentNullException(paramName);
}
ValidateNonBlankStringParamAllowNull(param, paramName);
}
/// <summary>
/// Validates the enum value against the request version.
/// </summary>
/// <param name="enumValue">The enum value.</param>
/// <param name="requestVersion">The request version.</param>
/// <exception cref="ServiceVersionException">Raised if this enum value requires a later version of Exchange.</exception>
internal static void ValidateEnumVersionValue(Enum enumValue, ExchangeVersion requestVersion)
{
Type enumType = enumValue.GetType();
Dictionary<Enum, ExchangeVersion> enumVersionDict = enumVersionDictionaries.Member[enumType];
ExchangeVersion enumVersion = enumVersionDict[enumValue];
if (requestVersion < enumVersion)
{
throw new ServiceVersionException(
string.Format(
Strings.EnumValueIncompatibleWithRequestVersion,
enumValue.ToString(),
enumType.Name,
enumVersion));
}
}
/// <summary>
/// Validates service object version against the request version.
/// </summary>
/// <param name="serviceObject">The service object.</param>
/// <param name="requestVersion">The request version.</param>
/// <exception cref="ServiceVersionException">Raised if this service object type requires a later version of Exchange.</exception>
internal static void ValidateServiceObjectVersion(ServiceObject serviceObject, ExchangeVersion requestVersion)
{
ExchangeVersion minimumRequiredServerVersion = serviceObject.GetMinimumRequiredServerVersion();
if (requestVersion < minimumRequiredServerVersion)
{
throw new ServiceVersionException(
string.Format(
Strings.ObjectTypeIncompatibleWithRequestVersion,
serviceObject.GetType().Name,
minimumRequiredServerVersion));
}
}
/// <summary>
/// Validates property version against the request version.
/// </summary>
/// <param name="service">The Exchange service.</param>
/// <param name="minimumServerVersion">The minimum server version that supports the property.</param>
/// <param name="propertyName">Name of the property.</param>
internal static void ValidatePropertyVersion(
ExchangeService service,
ExchangeVersion minimumServerVersion,
string propertyName)
{
if (service.RequestedServerVersion < minimumServerVersion)
{
throw new ServiceVersionException(
string.Format(
Strings.PropertyIncompatibleWithRequestVersion,
propertyName,
minimumServerVersion));
}
}
/// <summary>
/// Validates method version against the request version.
/// </summary>
/// <param name="service">The Exchange service.</param>
/// <param name="minimumServerVersion">The minimum server version that supports the method.</param>
/// <param name="methodName">Name of the method.</param>
internal static void ValidateMethodVersion(
ExchangeService service,
ExchangeVersion minimumServerVersion,
string methodName)
{
if (service.RequestedServerVersion < minimumServerVersion)
{
throw new ServiceVersionException(
string.Format(
Strings.MethodIncompatibleWithRequestVersion,
methodName,
minimumServerVersion));
}
}
/// <summary>
/// Validates class version against the request version.
/// </summary>
/// <param name="service">The Exchange service.</param>
/// <param name="minimumServerVersion">The minimum server version that supports the method.</param>
/// <param name="className">Name of the class.</param>
internal static void ValidateClassVersion(
ExchangeService service,
ExchangeVersion minimumServerVersion,
string className)
{
if (service.RequestedServerVersion < minimumServerVersion)
{
throw new ServiceVersionException(
string.Format(
Strings.ClassIncompatibleWithRequestVersion,
className,
minimumServerVersion));
}
}
/// <summary>
/// Validates domain name (null value allowed)
/// </summary>
/// <param name="domainName">Domain name.</param>
/// <param name="paramName">Parameter name.</param>
internal static void ValidateDomainNameAllowNull(string domainName, string paramName)
{
if (domainName != null)
{
Regex regex = new Regex(DomainRegex);
if (!regex.IsMatch(domainName))
{
throw new ArgumentException(string.Format(Strings.InvalidDomainName, domainName), paramName);
}
}
}
/// <summary>
/// Gets version for enum member.
/// </summary>
/// <param name="enumType">Type of the enum.</param>
/// <param name="enumName">The enum name.</param>
/// <returns>Exchange version in which the enum value was first defined.</returns>
private static ExchangeVersion GetEnumVersion(Type enumType, string enumName)
{
MemberInfo[] memberInfo = enumType.GetMember(enumName);
EwsUtilities.Assert(
(memberInfo != null) && (memberInfo.Length > 0),
"EwsUtilities.GetEnumVersion",
"Enum member " + enumName + " not found in " + enumType);
object[] attrs = memberInfo[0].GetCustomAttributes(typeof(RequiredServerVersionAttribute), false);
if (attrs != null && attrs.Length > 0)
{
return ((RequiredServerVersionAttribute)attrs[0]).Version;
}
else
{
return ExchangeVersion.Exchange2007_SP1;
}
}
/// <summary>
/// Builds the enum to version mapping dictionary.
/// </summary>
/// <param name="enumType">Type of the enum.</param>
/// <returns>Dictionary of enum values to versions.</returns>
private static Dictionary<Enum, ExchangeVersion> BuildEnumDict(Type enumType)
{
Dictionary<Enum, ExchangeVersion> dict = new Dictionary<Enum, ExchangeVersion>();
string[] names = Enum.GetNames(enumType);
foreach (string name in names)
{
Enum value = (Enum)Enum.Parse(enumType, name, false);
ExchangeVersion version = GetEnumVersion(enumType, name);
dict.Add(value, version);
}
return dict;
}
/// <summary>
/// Gets the schema name for enum member.
/// </summary>
/// <param name="enumType">Type of the enum.</param>
/// <param name="enumName">The enum name.</param>
/// <returns>The name for the enum used in the protocol, or null if it is the same as the enum's ToString().</returns>
private static string GetEnumSchemaName(Type enumType, string enumName)
{
MemberInfo[] memberInfo = enumType.GetMember(enumName);
EwsUtilities.Assert(
(memberInfo != null) && (memberInfo.Length > 0),
"EwsUtilities.GetEnumSchemaName",
"Enum member " + enumName + " not found in " + enumType);
object[] attrs = memberInfo[0].GetCustomAttributes(typeof(EwsEnumAttribute), false);
if (attrs != null && attrs.Length > 0)
{
return ((EwsEnumAttribute)attrs[0]).SchemaName;
}
else
{
return null;
}
}
/// <summary>
/// Builds the schema to enum mapping dictionary.
/// </summary>
/// <param name="enumType">Type of the enum.</param>
/// <returns>The mapping from enum to schema name</returns>
private static Dictionary<string, Enum> BuildSchemaToEnumDict(Type enumType)
{
Dictionary<string, Enum> dict = new Dictionary<string, Enum>();
string[] names = Enum.GetNames(enumType);
foreach (string name in names)
{
Enum value = (Enum)Enum.Parse(enumType, name, false);
string schemaName = EwsUtilities.GetEnumSchemaName(enumType, name);
if (!String.IsNullOrEmpty(schemaName))
{
dict.Add(schemaName, value);
}
}
return dict;
}
/// <summary>
/// Builds the enum to schema mapping dictionary.
/// </summary>
/// <param name="enumType">Type of the enum.</param>
/// <returns>The mapping from enum to schema name</returns>
private static Dictionary<Enum, string> BuildEnumToSchemaDict(Type enumType)
{
Dictionary<Enum, string> dict = new Dictionary<Enum, string>();
string[] names = Enum.GetNames(enumType);
foreach (string name in names)
{
Enum value = (Enum)Enum.Parse(enumType, name, false);
string schemaName = EwsUtilities.GetEnumSchemaName(enumType, name);
if (!String.IsNullOrEmpty(schemaName))
{
dict.Add(value, schemaName);
}
}
return dict;
}
#endregion
#region IEnumerable utility methods
/// <summary>
/// Gets the enumerated object count.
/// </summary>
/// <param name="objects">The objects.</param>
/// <returns>Count of objects in IEnumerable.</returns>
internal static int GetEnumeratedObjectCount(IEnumerable objects)
{
int count = 0;
foreach (object obj in objects)
{
count++;
}
return count;
}
/// <summary>
/// Gets enumerated object at index.
/// </summary>
/// <param name="objects">The objects.</param>
/// <param name="index">The index.</param>
/// <returns>Object at index.</returns>
internal static object GetEnumeratedObjectAt(IEnumerable objects, int index)
{
int count = 0;
foreach (object obj in objects)
{
if (count == index)
{
return obj;
}
count++;
}
throw new ArgumentOutOfRangeException("index", Strings.IEnumerableDoesNotContainThatManyObject);
}
#endregion
#region Extension methods
/// <summary>
/// Count characters in string that match a condition.
/// </summary>
/// <param name="str">The string.</param>
/// <param name="charPredicate">Predicate to evaluate for each character in the string.</param>
/// <returns>Count of characters that match condition expressed by predicate.</returns>
internal static int CountMatchingChars(this string str, Predicate<char> charPredicate)
{
int count = 0;
foreach (char ch in str)
{
if (charPredicate(ch))
{
count++;
}
}
return count;
}
/// <summary>
/// Determines whether every element in the collection matches the conditions defined by the specified predicate.
/// </summary>
/// <typeparam name="T">Entry type.</typeparam>
/// <param name="collection">The collection.</param>
/// <param name="predicate">Predicate that defines the conditions to check against the elements.</param>
/// <returns>True if every element in the collection matches the conditions defined by the specified predicate; otherwise, false.</returns>
internal static bool TrueForAll<T>(this IEnumerable<T> collection, Predicate<T> predicate)
{
foreach (T entry in collection)
{
if (!predicate(entry))
{
return false;
}
}
return true;
}
/// <summary>
/// Call an action for each member of a collection.
/// </summary>
/// <param name="collection">The collection.</param>
/// <param name="action">The action to apply.</param>
/// <typeparam name="T">Collection element type.</typeparam>
internal static void ForEach<T>(this IEnumerable<T> collection, Action<T> action)
{
foreach (T entry in collection)
{
action(entry);
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using LocalSecurity.Areas.HelpPage.ModelDescriptions;
using LocalSecurity.Areas.HelpPage.Models;
namespace LocalSecurity.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Reflection;
using OpenMetaverse;
using log4net;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using System.Collections.Generic;
using System.Xml;
namespace OpenSim.Region.Framework.Scenes
{
public partial class SceneObjectGroup : EntityBase
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Force all task inventories of prims in the scene object to persist
/// </summary>
public void ForceInventoryPersistence()
{
lock (m_parts)
{
foreach (SceneObjectPart part in m_parts.Values)
{
part.Inventory.ForceInventoryPersistence();
}
}
}
/// <summary>
/// Start the scripts contained in all the prims in this group.
/// </summary>
public void CreateScriptInstances(int startParam, bool postOnRez,
string engine, int stateSource)
{
// Don't start scripts if they're turned off in the region!
if (!m_scene.RegionInfo.RegionSettings.DisableScripts)
{
foreach (SceneObjectPart part in m_parts.Values)
{
part.Inventory.CreateScriptInstances(startParam, postOnRez, engine, stateSource);
}
}
}
/// <summary>
/// Stop the scripts contained in all the prims in this group
/// </summary>
public void RemoveScriptInstances()
{
lock (m_parts)
{
foreach (SceneObjectPart part in m_parts.Values)
{
part.Inventory.RemoveScriptInstances();
}
}
}
/// <summary>
///
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="localID"></param>
public bool GetPartInventoryFileName(IClientAPI remoteClient, uint localID)
{
SceneObjectPart part = GetChildPart(localID);
if (part != null)
{
return part.Inventory.GetInventoryFileName(remoteClient, localID);
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Couldn't find part {0} in object group {1}, {2} to retreive prim inventory",
localID, Name, UUID);
}
return false;
}
/// <summary>
/// Return serialized inventory metadata for the given constituent prim
/// </summary>
/// <param name="localID"></param>
/// <param name="xferManager"></param>
public void RequestInventoryFile(IClientAPI client, uint localID, IXfer xferManager)
{
SceneObjectPart part = GetChildPart(localID);
if (part != null)
{
part.Inventory.RequestInventoryFile(client, xferManager);
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Couldn't find part {0} in object group {1}, {2} to request inventory data",
localID, Name, UUID);
}
}
/// <summary>
/// Add an inventory item to a prim in this group.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="localID"></param>
/// <param name="item"></param>
/// <param name="copyItemID">The item UUID that should be used by the new item.</param>
/// <returns></returns>
public bool AddInventoryItem(IClientAPI remoteClient, uint localID,
InventoryItemBase item, UUID copyItemID)
{
UUID newItemId = (copyItemID != UUID.Zero) ? copyItemID : item.ID;
SceneObjectPart part = GetChildPart(localID);
if (part != null)
{
TaskInventoryItem taskItem = new TaskInventoryItem();
taskItem.ItemID = newItemId;
taskItem.AssetID = item.AssetID;
taskItem.Name = item.Name;
taskItem.Description = item.Description;
taskItem.OwnerID = part.OwnerID; // Transfer ownership
taskItem.CreatorID = item.CreatorIdAsUuid;
taskItem.Type = item.AssetType;
taskItem.InvType = item.InvType;
if (remoteClient != null &&
remoteClient.AgentId != part.OwnerID &&
m_scene.Permissions.PropagatePermissions())
{
taskItem.BasePermissions = item.BasePermissions &
item.NextPermissions;
taskItem.CurrentPermissions = item.CurrentPermissions &
item.NextPermissions;
taskItem.EveryonePermissions = item.EveryOnePermissions &
item.NextPermissions;
taskItem.GroupPermissions = item.GroupPermissions &
item.NextPermissions;
taskItem.NextPermissions = item.NextPermissions;
taskItem.CurrentPermissions |= 8;
} else {
taskItem.BasePermissions = item.BasePermissions;
taskItem.CurrentPermissions = item.CurrentPermissions;
taskItem.CurrentPermissions |= 8;
taskItem.EveryonePermissions = item.EveryOnePermissions;
taskItem.GroupPermissions = item.GroupPermissions;
taskItem.NextPermissions = item.NextPermissions;
}
taskItem.Flags = item.Flags;
// TODO: These are pending addition of those fields to TaskInventoryItem
// taskItem.SalePrice = item.SalePrice;
// taskItem.SaleType = item.SaleType;
taskItem.CreationDate = (uint)item.CreationDate;
bool addFromAllowedDrop = false;
if (remoteClient!=null)
{
addFromAllowedDrop = remoteClient.AgentId != part.OwnerID;
}
part.Inventory.AddInventoryItem(taskItem, addFromAllowedDrop);
return true;
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Couldn't find prim local ID {0} in group {1}, {2} to add inventory item ID {3}",
localID, Name, UUID, newItemId);
}
return false;
}
/// <summary>
/// Returns an existing inventory item. Returns the original, so any changes will be live.
/// </summary>
/// <param name="primID"></param>
/// <param name="itemID"></param>
/// <returns>null if the item does not exist</returns>
public TaskInventoryItem GetInventoryItem(uint primID, UUID itemID)
{
SceneObjectPart part = GetChildPart(primID);
if (part != null)
{
return part.Inventory.GetInventoryItem(itemID);
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Couldn't find prim local ID {0} in prim {1}, {2} to get inventory item ID {3}",
primID, part.Name, part.UUID, itemID);
}
return null;
}
/// <summary>
/// Update an existing inventory item.
/// </summary>
/// <param name="item">The updated item. An item with the same id must already exist
/// in this prim's inventory</param>
/// <returns>false if the item did not exist, true if the update occurred succesfully</returns>
public bool UpdateInventoryItem(TaskInventoryItem item)
{
SceneObjectPart part = GetChildPart(item.ParentPartID);
if (part != null)
{
part.Inventory.UpdateInventoryItem(item);
return true;
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Couldn't find prim ID {0} to update item {1}, {2}",
item.ParentPartID, item.Name, item.ItemID);
}
return false;
}
public int RemoveInventoryItem(uint localID, UUID itemID)
{
SceneObjectPart part = GetChildPart(localID);
if (part != null)
{
int type = part.Inventory.RemoveInventoryItem(itemID);
return type;
}
return -1;
}
public uint GetEffectivePermissions()
{
uint perms=(uint)(PermissionMask.Modify |
PermissionMask.Copy |
PermissionMask.Move |
PermissionMask.Transfer) | 7;
uint ownerMask = 0x7ffffff;
foreach (SceneObjectPart part in m_parts.Values)
{
ownerMask &= part.OwnerMask;
perms &= part.Inventory.MaskEffectivePermissions();
}
if ((ownerMask & (uint)PermissionMask.Modify) == 0)
perms &= ~(uint)PermissionMask.Modify;
if ((ownerMask & (uint)PermissionMask.Copy) == 0)
perms &= ~(uint)PermissionMask.Copy;
if ((ownerMask & (uint)PermissionMask.Transfer) == 0)
perms &= ~(uint)PermissionMask.Transfer;
if ((ownerMask & RootPart.NextOwnerMask & (uint)PermissionMask.Modify) == 0)
perms &= ~((uint)PermissionMask.Modify >> 13);
if ((ownerMask & RootPart.NextOwnerMask & (uint)PermissionMask.Copy) == 0)
perms &= ~((uint)PermissionMask.Copy >> 13);
if ((ownerMask & RootPart.NextOwnerMask & (uint)PermissionMask.Transfer) == 0)
perms &= ~((uint)PermissionMask.Transfer >> 13);
return perms;
}
public void ApplyNextOwnerPermissions()
{
foreach (SceneObjectPart part in m_parts.Values)
{
part.ApplyNextOwnerPermissions();
}
}
public string GetStateSnapshot()
{
//m_log.Debug(" >>> GetStateSnapshot <<<");
List<string> assemblies = new List<string>();
Dictionary<UUID, string> states = new Dictionary<UUID, string>();
foreach (SceneObjectPart part in m_parts.Values)
{
foreach (string a in part.Inventory.GetScriptAssemblies())
{
if (a != "" && !assemblies.Contains(a))
assemblies.Add(a);
}
foreach (KeyValuePair<UUID, string> s in part.Inventory.GetScriptStates())
{
states[s.Key] = s.Value;
}
}
if (states.Count < 1 || assemblies.Count < 1)
return "";
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ScriptData",
"");
xmldoc.AppendChild(rootElement);
XmlElement wrapper = xmldoc.CreateElement("", "Assemblies",
"");
rootElement.AppendChild(wrapper);
foreach (string assembly in assemblies)
{
string fn = Path.GetFileName(assembly);
if (fn == String.Empty)
continue;
String filedata = String.Empty;
if (File.Exists(assembly+".text"))
{
FileInfo tfi = new FileInfo(assembly+".text");
if (tfi == null)
continue;
Byte[] tdata = new Byte[tfi.Length];
try
{
FileStream tfs = File.Open(assembly+".text", FileMode.Open, FileAccess.Read);
tfs.Read(tdata, 0, tdata.Length);
tfs.Close();
}
catch (Exception e)
{
m_log.DebugFormat("[SOG]: Unable to open script textfile {0}, reason: {1}", assembly+".text", e.Message);
}
filedata = new System.Text.ASCIIEncoding().GetString(tdata);
}
else
{
FileInfo fi = new FileInfo(assembly);
if (fi == null)
continue;
Byte[] data = new Byte[fi.Length];
try
{
FileStream fs = File.Open(assembly, FileMode.Open, FileAccess.Read);
fs.Read(data, 0, data.Length);
fs.Close();
}
catch (Exception e)
{
m_log.DebugFormat("[SOG]: Unable to open script assembly {0}, reason: {1}", assembly, e.Message);
}
filedata = System.Convert.ToBase64String(data);
}
XmlElement assemblyData = xmldoc.CreateElement("", "Assembly", "");
XmlAttribute assemblyName = xmldoc.CreateAttribute("", "Filename", "");
assemblyName.Value = fn;
assemblyData.Attributes.Append(assemblyName);
assemblyData.InnerText = filedata;
wrapper.AppendChild(assemblyData);
}
wrapper = xmldoc.CreateElement("", "ScriptStates",
"");
rootElement.AppendChild(wrapper);
foreach (KeyValuePair<UUID, string> state in states)
{
XmlElement stateData = xmldoc.CreateElement("", "State", "");
XmlAttribute stateID = xmldoc.CreateAttribute("", "UUID", "");
stateID.Value = state.Key.ToString();
stateData.Attributes.Append(stateID);
XmlDocument sdoc = new XmlDocument();
sdoc.LoadXml(state.Value);
XmlNodeList rootL = sdoc.GetElementsByTagName("ScriptState");
XmlNode rootNode = rootL[0];
XmlNode newNode = xmldoc.ImportNode(rootNode, true);
stateData.AppendChild(newNode);
wrapper.AppendChild(stateData);
}
return xmldoc.InnerXml;
}
public void SetState(string objXMLData, UUID RegionID)
{
if (objXMLData == String.Empty)
return;
XmlDocument doc = new XmlDocument();
try
{
doc.LoadXml(objXMLData);
}
catch (Exception) // (System.Xml.XmlException)
{
// We will get here if the XML is invalid or in unit
// tests. Really should determine which it is and either
// fail silently or log it
// Fail silently, for now.
// TODO: Fix this
//
return;
}
XmlNodeList rootL = doc.GetElementsByTagName("ScriptData");
if (rootL.Count == 1)
{
XmlNode rootNode = rootL[0];
if (rootNode != null)
{
XmlNodeList partL = rootNode.ChildNodes;
foreach (XmlNode part in partL)
{
XmlNodeList nodeL = part.ChildNodes;
switch (part.Name)
{
case "Assemblies":
foreach (XmlNode asm in nodeL)
{
string fn = asm.Attributes.GetNamedItem("Filename").Value;
Byte[] filedata = Convert.FromBase64String(asm.InnerText);
string path = Path.Combine("ScriptEngines", RegionID.ToString());
path = Path.Combine(path, fn);
if (!File.Exists(path))
{
FileStream fs = File.Create(path);
fs.Write(filedata, 0, filedata.Length);
fs.Close();
Byte[] textbytes = new System.Text.ASCIIEncoding().GetBytes(asm.InnerText);
fs = File.Create(path+".text");
fs.Write(textbytes, 0, textbytes.Length);
fs.Close();
}
}
break;
case "ScriptStates":
foreach (XmlNode st in nodeL)
{
string id = st.Attributes.GetNamedItem("UUID").Value;
UUID uuid = new UUID(id);
XmlNode state = st.ChildNodes[0];
XmlDocument sdoc = new XmlDocument();
XmlNode sxmlnode = sdoc.CreateNode(
XmlNodeType.XmlDeclaration,
"", "");
sdoc.AppendChild(sxmlnode);
XmlNode newnode = sdoc.ImportNode(state, true);
sdoc.AppendChild(newnode);
string spath = Path.Combine("ScriptEngines", RegionID.ToString());
spath = Path.Combine(spath, uuid.ToString());
FileStream sfs = File.Create(spath + ".state");
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
Byte[] buf = enc.GetBytes(sdoc.InnerXml);
sfs.Write(buf, 0, buf.Length);
sfs.Close();
}
break;
}
}
}
}
}
}
}
| |
namespace android.app
{
[global::MonoJavaBridge.JavaClass(typeof(global::android.app.LauncherActivity_))]
public abstract partial class LauncherActivity : android.app.ListActivity
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected LauncherActivity(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass()]
public partial class IconResizer : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected IconResizer(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public virtual global::android.graphics.drawable.Drawable createIconThumbnail(android.graphics.drawable.Drawable arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.LauncherActivity.IconResizer.staticClass, "createIconThumbnail", "(Landroid/graphics/drawable/Drawable;)Landroid/graphics/drawable/Drawable;", ref global::android.app.LauncherActivity.IconResizer._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.graphics.drawable.Drawable;
}
private static global::MonoJavaBridge.MethodId _m1;
public IconResizer(android.app.LauncherActivity arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.app.LauncherActivity.IconResizer._m1.native == global::System.IntPtr.Zero)
global::android.app.LauncherActivity.IconResizer._m1 = @__env.GetMethodIDNoThrow(global::android.app.LauncherActivity.IconResizer.staticClass, "<init>", "(Landroid/app/LauncherActivity;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.app.LauncherActivity.IconResizer.staticClass, global::android.app.LauncherActivity.IconResizer._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
static IconResizer()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.app.LauncherActivity.IconResizer.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/app/LauncherActivity$IconResizer"));
}
}
[global::MonoJavaBridge.JavaClass()]
public partial class ListItem : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected ListItem(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public ListItem() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.app.LauncherActivity.ListItem._m0.native == global::System.IntPtr.Zero)
global::android.app.LauncherActivity.ListItem._m0 = @__env.GetMethodIDNoThrow(global::android.app.LauncherActivity.ListItem.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.app.LauncherActivity.ListItem.staticClass, global::android.app.LauncherActivity.ListItem._m0);
Init(@__env, handle);
}
internal static global::MonoJavaBridge.FieldId _resolveInfo1354;
public global::android.content.pm.ResolveInfo resolveInfo
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetObjectField(this.JvmHandle, _resolveInfo1354)) as android.content.pm.ResolveInfo;
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _label1355;
public global::java.lang.CharSequence label
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.GetObjectField(this.JvmHandle, _label1355)) as java.lang.CharSequence;
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _icon1356;
public global::android.graphics.drawable.Drawable icon
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetObjectField(this.JvmHandle, _icon1356)) as android.graphics.drawable.Drawable;
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _packageName1357;
public global::java.lang.String packageName
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.GetObjectField(this.JvmHandle, _packageName1357)) as java.lang.String;
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _className1358;
public global::java.lang.String className
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.GetObjectField(this.JvmHandle, _className1358)) as java.lang.String;
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _extras1359;
public global::android.os.Bundle extras
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.os.Bundle>(@__env.GetObjectField(this.JvmHandle, _extras1359)) as android.os.Bundle;
}
set
{
}
}
static ListItem()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.app.LauncherActivity.ListItem.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/app/LauncherActivity$ListItem"));
global::android.app.LauncherActivity.ListItem._resolveInfo1354 = @__env.GetFieldIDNoThrow(global::android.app.LauncherActivity.ListItem.staticClass, "resolveInfo", "Landroid/content/pm/ResolveInfo;");
global::android.app.LauncherActivity.ListItem._label1355 = @__env.GetFieldIDNoThrow(global::android.app.LauncherActivity.ListItem.staticClass, "label", "Ljava/lang/CharSequence;");
global::android.app.LauncherActivity.ListItem._icon1356 = @__env.GetFieldIDNoThrow(global::android.app.LauncherActivity.ListItem.staticClass, "icon", "Landroid/graphics/drawable/Drawable;");
global::android.app.LauncherActivity.ListItem._packageName1357 = @__env.GetFieldIDNoThrow(global::android.app.LauncherActivity.ListItem.staticClass, "packageName", "Ljava/lang/String;");
global::android.app.LauncherActivity.ListItem._className1358 = @__env.GetFieldIDNoThrow(global::android.app.LauncherActivity.ListItem.staticClass, "className", "Ljava/lang/String;");
global::android.app.LauncherActivity.ListItem._extras1359 = @__env.GetFieldIDNoThrow(global::android.app.LauncherActivity.ListItem.staticClass, "extras", "Landroid/os/Bundle;");
}
}
private static global::MonoJavaBridge.MethodId _m0;
protected override void onCreate(android.os.Bundle arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.LauncherActivity.staticClass, "onCreate", "(Landroid/os/Bundle;)V", ref global::android.app.LauncherActivity._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m1;
protected virtual void onSetContentView()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.LauncherActivity.staticClass, "onSetContentView", "()V", ref global::android.app.LauncherActivity._m1);
}
private static global::MonoJavaBridge.MethodId _m2;
protected override void onListItemClick(android.widget.ListView arg0, android.view.View arg1, int arg2, long arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.LauncherActivity.staticClass, "onListItemClick", "(Landroid/widget/ListView;Landroid/view/View;IJ)V", ref global::android.app.LauncherActivity._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m3;
protected virtual global::android.content.Intent intentForPosition(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.LauncherActivity.staticClass, "intentForPosition", "(I)Landroid/content/Intent;", ref global::android.app.LauncherActivity._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.content.Intent;
}
private static global::MonoJavaBridge.MethodId _m4;
protected virtual global::android.app.LauncherActivity.ListItem itemForPosition(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.LauncherActivity.staticClass, "itemForPosition", "(I)Landroid/app/LauncherActivity$ListItem;", ref global::android.app.LauncherActivity._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.app.LauncherActivity.ListItem;
}
private static global::MonoJavaBridge.MethodId _m5;
protected virtual global::android.content.Intent getTargetIntent()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.LauncherActivity.staticClass, "getTargetIntent", "()Landroid/content/Intent;", ref global::android.app.LauncherActivity._m5) as android.content.Intent;
}
private static global::MonoJavaBridge.MethodId _m6;
protected virtual global::java.util.List onQueryPackageManager(android.content.Intent arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.List>(this, global::android.app.LauncherActivity.staticClass, "onQueryPackageManager", "(Landroid/content/Intent;)Ljava/util/List;", ref global::android.app.LauncherActivity._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.util.List;
}
private static global::MonoJavaBridge.MethodId _m7;
public virtual global::java.util.List makeListItems()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.List>(this, global::android.app.LauncherActivity.staticClass, "makeListItems", "()Ljava/util/List;", ref global::android.app.LauncherActivity._m7) as java.util.List;
}
private static global::MonoJavaBridge.MethodId _m8;
public LauncherActivity() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.app.LauncherActivity._m8.native == global::System.IntPtr.Zero)
global::android.app.LauncherActivity._m8 = @__env.GetMethodIDNoThrow(global::android.app.LauncherActivity.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.app.LauncherActivity.staticClass, global::android.app.LauncherActivity._m8);
Init(@__env, handle);
}
static LauncherActivity()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.app.LauncherActivity.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/app/LauncherActivity"));
}
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.app.LauncherActivity))]
internal sealed partial class LauncherActivity_ : android.app.LauncherActivity
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal LauncherActivity_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
static LauncherActivity_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.app.LauncherActivity_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/app/LauncherActivity"));
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="Chord.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <disclaimer>
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
// PURPOSE.
// </disclaimer>
//------------------------------------------------------------------------------
using Microsoft.Research.Joins;
using Microsoft.Research.Joins.Patterns;
using System.Threading;
using System;
using System.Collections.Generic;
using Microsoft.Research.Joins.ArgCounts;
using Microsoft.Research.Joins.BitMasks;
namespace Microsoft.Research.Joins.ArgCounts {
public abstract class S<n> { }
public abstract class Z { }
}
namespace Microsoft.Research.Joins {
#warning "TODO: inline me, I no longer add value"
internal static class ChordFactory {
internal static ActionChord<Z,Unit> FromChannel(Join join, Synchronous.Channel ch) {
return new ActionChord<Z,Unit>(join, AtomFactory.FromChannel(ch));
}
internal static ActionChord<S<Z>, A> FromChannel<A>(Join join, Synchronous.Channel<A> ch) {
return new ActionChord<S<Z>, A>(join, AtomFactory.FromChannel(ch));
}
internal static FuncChord<Z,Unit,R> FromChannel<R>(Join join, Synchronous<R>.Channel ch) {
return new FuncChord<Z,Unit,R>(join, AtomFactory.FromChannel(ch));
}
internal static FuncChord<S<Z>, A, R> FromChannel<A, R>(Join join, Synchronous<R>.Channel<A> ch) {
return new FuncChord<S<Z>, A, R>(join, AtomFactory.FromChannel(ch));
}
internal static ActionChord<Z,Unit> FromChannel(Join join, Asynchronous.Channel ch) {
return new ActionChord<Z,Unit>(join, AtomFactory.FromChannel(ch));
}
internal static ActionChord<S<Z>, A> FromChannel<A>(Join join, Asynchronous.Channel<A> ch) {
return new ActionChord<S<Z>, A>(join, AtomFactory.FromChannel(ch));
}
internal static ActionChord<Z,Unit> FromChannels(Join join, Asynchronous.Channel[] ch) {
return new ActionChord<Z,Unit>(join, VectorFactory.FromChannels(ch));
}
internal static ActionChord<S<Z>, A[]> FromChannels<A>(Join join, Asynchronous.Channel<A>[] ch) {
return new ActionChord<S<Z>, A[]>(join, VectorFactory.FromChannels(ch));
}
internal static ActionChord<S<Z>, A[]> FromChannels<A>(Join join, Synchronous.Channel<A>[] ch) {
return new ActionChord<S<Z>, A[]>(join, VectorFactory.FromChannels(ch));
}
internal static FuncChord<Z,Unit,R> FromChannels<R>(Join join, Synchronous<R>.Channel[] ch) {
return new FuncChord<Z,Unit,R>(join, VectorFactory.FromChannels(ch));
}
internal static FuncChord<S<Z>, A[], R> FromChannels<A,R>(Join join, Synchronous<R>.Channel<A>[] ch) {
return new FuncChord<S<Z>, A[], R>(join, VectorFactory.FromChannels(ch));
}
internal static ActionChord<Z, Unit> FromChannels(Join join, Synchronous.Channel[] ch) {
return new ActionChord<Z, Unit>(join, VectorFactory.FromChannels(ch));
}
}
#if MONO
public static class MonoWorkaround {
// weird workaround for Mono...
public static void DoPair<P0, P1, R>(this FuncChord<S<S<Z>>, Pair<P0, P1>,R> chord, Func<P0, P1, R> continuation) {
chord.mJoin.Register(chord, continuation);
}
public static void DoSing<P0, R>(this FuncChord<S<Z>, P0,R> chord, Func<P0, R> continuation) {
chord.mJoin.Register(chord, continuation);
}
}
#endif
public abstract partial class Chord {
internal abstract Pattern GetPattern();
internal readonly Join mJoin; // made public for mono workaround
#if CONTINUATIONATTRIBUTES
internal ContinuationAttribute mContinuationAttribute;
#endif
internal void SetContinuationAttribute(Delegate continuation) {
#if CONTINUATIONATTRIBUTES
mContinuationAttribute = ContinuationAttribute.GetContinuationAttribute(continuation);
#endif
}
internal Chord(Join join) {
mJoin = join;
}
}
public abstract partial class Chord<R> : Chord {
internal Chord(Join join)
: base(join) { }
}
public partial class Chord<A, R> : Chord<R>
{
internal Func<A, R> mContinuation;
internal readonly Pattern<A> mPattern;
internal override Pattern GetPattern() { return mPattern; }
internal Chord(Join join, Pattern<A> pat)
: base(join) {
mPattern = pat;
}
internal Chord(Join join, Pattern<A> pat, Delegate del, Func<A,R> continuation )
: base(join) {
mPattern = pat;
mContinuation = continuation;
#if CONTINUATIONATTRIBUTES
mContinuationAttribute = ContinuationAttribute.GetContinuationAttribute(del);
#endif
}
}
public class FuncChord<n, A, R> : Chord<A, R> {
internal FuncChord(Join join, Pattern<A> pat)
: base(join, pat) { }
/// <summary>
/// Extends this pattern to wait for one message on <paramref name="channel"/>.
/// </summary>
/// <param name="channel"> the additional channel to wait on.</param>
/// <exception cref="JoinException"> thrown when <paramref name="channel"/> is null.</exception>
/// <returns>A new chord taking a continuation with the same shape.</returns>
public FuncChord<n, A, R> And(Asynchronous.Channel channel) {
return new FuncChord<n, A, R>(mJoin, new And<A>(mPattern, AtomFactory.FromChannel(channel)));
}
/// <summary>
/// Extends this pattern to wait for one message on each channel in the array <paramref name="channels"/>.
/// </summary>
/// <param name="channels"> the array of additional channels to wait on.</param>
/// <exception cref="JoinException"> thrown when <paramref name="channels"/> is null or contains a null channel.</exception>
/// <returns>A new chord taking a continuation with the same shape.</returns>
public FuncChord<n, A, R> And(Asynchronous.Channel[] channels) {
return new FuncChord<n, A, R>(mJoin, new And<A>(mPattern, VectorFactory.FromChannels(channels)));
}
/// <summary>
/// Extends this pattern to wait for one message on <paramref name="channel"/>.
/// </summary>
/// <param name="channel"> the additional channel to wait on.</param>
/// <exception cref="JoinException"> thrown when <paramref name="channel"/> is null.</exception>
/// <returns>A new chord taking a continuation with the same shape.</returns>
public FuncChord<n, A, R> And(Synchronous<R>.Channel channel) {
return new FuncChord<n, A, R>(mJoin, new And<A>(mPattern, AtomFactory.FromChannel(channel)));
}
/// <summary>
/// Extends this pattern to wait for one message on each channel in the array <paramref name="channels"/>.
/// </summary>
/// <param name="channels"> the array of additional channels to wait on.</param>
/// <exception cref="JoinException"> thrown when <paramref name="channels"/> is null or contains a null channel.</exception>
/// <returns>A new chord taking a continuation with the same shape.</returns>
public FuncChord<n, A, R> And(Synchronous<R>.Channel[] channels) {
return new FuncChord<n, A, R>(mJoin, new And<A>(mPattern, VectorFactory.FromChannels(channels)));
}
}
public static class FuncChordExtensions {
/// <summary>
/// Extends this pattern to wait for one message on <paramref name="channel"/>.
/// </summary>
/// <typeparam name="B"> the type of the channel and additional continuation argument.</typeparam>
/// <typeparam name="R"> the return type of pattern's continuation.</typeparam>
/// <param name="chord"> the chord to extend.</param>
/// <param name="channel"> the additional channel to wait on.</param>
/// <exception cref="JoinException"> thrown when <paramref name="channel"/> is null.</exception>
/// <returns>A new chord taking a continuation with one additional parameter of type <c>B</c>.</returns>
public static FuncChord<S<Z>, B, R> And<B,R>(this FuncChord<Z,Unit,R> chord, Asynchronous.Channel<B> channel) {
return new FuncChord<S<Z>,B, R>(chord.mJoin, new And<B>(AtomFactory.FromChannel(channel),chord.mPattern));
}
/// <summary>
/// Extends this pattern to wait for one message on <paramref name="channel"/>.
/// </summary>
/// <typeparam name="n"> an auxilliary type counting continuation arguments.</typeparam>
/// <typeparam name="A"> the current (encoded) argument type of the chord.</typeparam>
/// <typeparam name="B"> the type of the channel and additional continuation argument.</typeparam>
/// <typeparam name="R"> the return type of the chord and additional continuation argument.</typeparam>
/// <param name="chord"> the chord to extend.</param>
/// <param name="channel"> the additional channel to wait on.</param>
/// <exception cref="JoinException"> thrown when <paramref name="channel"/> is null.</exception>
/// <returns>A new chord taking a continuation with one additional parameter of type <c>B</c>.</returns>
public static FuncChord<S<S<n>>, Pair<A,B>, R> And<n,A,B,R>(this FuncChord<S<n>,A,R> chord, Asynchronous.Channel<B> channel) {
return new FuncChord<S<S<n>>, Pair<A, B>, R>(chord.mJoin, new And<A, B>(chord.mPattern, AtomFactory.FromChannel(channel)));
}
/// <summary>
/// Extends this pattern to wait for one message on each channel in the array <paramref name="channels"/>.
/// </summary>
/// <typeparam name="B"> the argument type of each channel in <paramref name="channels"/> and the element type of the new continuation's array argument.</typeparam>
/// <typeparam name="R"> the return type of the chord and additional continuation argument.</typeparam>
/// <param name="chord"> the chord to extend.</param>
/// <param name="channels"> the array of additional channels to wait on.</param>
/// <exception cref="JoinException"> thrown when <paramref name="channels"/> is null or contains a null channel.</exception>
/// <returns>A new pattern taking a continuation with one additional argument <c>b</c> of type <c>B[]</c>, with <c>b[i]</c>
/// containing the value consumed from channel <c>channels[i]</c>.</returns>
public static FuncChord<S<Z>, B[], R> And<B,R>(this FuncChord<Z,Unit,R> chord, Asynchronous.Channel<B>[] channels) {
return new FuncChord<S<Z>, B[], R>(chord.mJoin, new And<B[]>(VectorFactory.FromChannels(channels), chord.mPattern));
}
/// <summary>
/// Extends this pattern to wait for one message on each channel in the array <paramref name="channels"/>.
/// </summary>
/// <typeparam name="n"> an auxilliary type counting continuation arguments.</typeparam>
/// <typeparam name="A"> the current (encoded) argument type of the chord.</typeparam>
/// <typeparam name="B"> the argument type of each channel in <paramref name="channels"/> and the element type of the new continuation's array argument.</typeparam>
/// <typeparam name="R"> the return type of the chord and additional continuation argument.</typeparam>
/// <param name="chord"> the chord to extend.</param>
/// <param name="channels"> the array of additional channels to wait on.</param>
/// <exception cref="JoinException"> thrown when <paramref name="channels"/> is null or contains a null channel.</exception>
/// <returns>A new pattern taking a continuation with one additional argument <c>b</c> of type <c>B[]</c>, with <c>b[i]</c>
/// containing the value consumed from channel <c>channels[i]</c>.</returns>
public static FuncChord<S<S<n>>, Pair<A, B[]>, R> And<n,A,B,R>(this FuncChord<S<n>,A,R> chord, Asynchronous.Channel<B>[] channels) {
return new FuncChord<S<S<n>>, Pair<A, B[]>, R>(chord.mJoin, new And<A, B[]>(chord.mPattern, VectorFactory.FromChannels(channels)));
}
/// <summary>
/// Extends this pattern to wait for one message on each channel in the array <paramref name="channels"/>.
/// </summary>
/// <typeparam name="B"> the argument type of each channel in <paramref name="channels"/> and the element type of the new continuation's array argument.</typeparam>
/// <typeparam name="R"> the return type of the chord and additional continuation argument.</typeparam>
/// <param name="chord"> the chord to extend.</param>
/// <param name="channels"> the array of additional channels to wait on.</param>
/// <exception cref="JoinException"> thrown when <paramref name="channels"/> is null or contains a null channel.</exception>
/// <returns>A new pattern taking a continuation with one additional argument <c>b</c> of type <c>B[]</c>, with <c>b[i]</c>
/// containing the value consumed from channel <c>channels[i]</c>.</returns>
public static FuncChord<S<Z>, B[], R> And<B,R>(this FuncChord<Z,Unit,R> chord, Synchronous<R>.Channel<B>[] channels) {
return new FuncChord<S<Z>, B[], R>(chord.mJoin, new And<B[]>(VectorFactory.FromChannels(channels), chord.mPattern));
}
/// <summary>
/// Extends this pattern to wait for one message on each channel in the array <paramref name="channels"/>.
/// </summary>
/// <typeparam name="n"> an auxilliary type counting continuation arguments.</typeparam>
/// <typeparam name="A"> the current (encoded) argument type of the chord.</typeparam>
/// <typeparam name="B"> the argument type of each channel in <paramref name="channels"/> and the element type of the new continuation's array argument.</typeparam>
/// <typeparam name="R"> the return type of the channels and additional continuation argument.</typeparam>
/// <param name="chord"> the chord to extend.</param>
/// <param name="channels"> the array of additional channels to wait on.</param>
/// <exception cref="JoinException"> thrown when <paramref name="channels"/> is null or contains a null channel.</exception>
/// <returns>A new pattern taking a continuation with one additional argument <c>b</c> of type <c>B[]</c>, with <c>b[i]</c>
/// containing the value consumed from channel <c>channels[i]</c>.</returns>
public static FuncChord<S<S<n>>, Pair<A, B[]>, R> And<n,A,B,R>(this FuncChord<S<n>,A,R> chord, Synchronous<R>.Channel<B>[] channels) {
return new FuncChord<S<S<n>>, Pair<A, B[]>, R>(chord.mJoin, new And<A, B[]>(chord.mPattern, VectorFactory.FromChannels(channels)));
}
/// <summary>
/// Extends this pattern to wait for one message on <paramref name="channel"/>.
/// </summary>
/// <typeparam name="B"> the type of the channel and additional continuation argument.</typeparam>
/// <typeparam name="R"> the return type of the chord and additional continuation argument.</typeparam>
/// <param name="chord"> the chord to extend.</param>
/// <param name="channel"> the additional channel to wait on.</param>
/// <exception cref="JoinException"> thrown when <paramref name="channel"/> is null.</exception>
/// <returns>A new chord taking a continuation with one additional parameter of type <c>B</c>.</returns>
public static FuncChord<S<Z>, B, R> And<B,R>(this FuncChord<Z,Unit,R> chord, Synchronous<R>.Channel<B> channel) {
return new FuncChord<S<Z>,B, R>(chord.mJoin, new And<B>(AtomFactory.FromChannel(channel),chord.mPattern));
}
/// <summary>
/// Extends this pattern to wait for one message on <paramref name="channel"/>.
/// </summary>
/// <typeparam name="n"> an auxilliary type counting continuation arguments.</typeparam>
/// <typeparam name="A"> the current (encoded) argument type of the chord.</typeparam>
/// <typeparam name="B"> the type of the channel and additional continuation argument.</typeparam>
/// <typeparam name="R"> the return type of the channel and additional continuation argument.</typeparam>
/// <param name="chord"> the chord to extend.</param>
/// <param name="channel"> the additional channel to wait on.</param>
/// <exception cref="JoinException"> thrown when <paramref name="channel"/> is null.</exception>
/// <returns>A new chord taking a continuation with one additional parameter of type <c>B</c>.</returns>
public static FuncChord<S<S<n>>, Pair<A,B>, R> And<n,A,B,R>(this FuncChord<S<n>,A,R> chord, Synchronous<R>.Channel<B> channel) {
return new FuncChord<S<S<n>>, Pair<A, B>, R>(chord.mJoin, new And<A, B>(chord.mPattern, AtomFactory.FromChannel(channel)));
}
}
public class ActionChord<n, A> : Chord<A, Unit> {
internal ActionChord(Join join, Pattern<A> pat)
: base(join, pat) { }
/// <summary>
/// Extends this pattern to wait for one message on <paramref name="channel"/>.
/// </summary>
/// <param name="channel"> the additional channel to wait on.</param>
/// <exception cref="JoinException"> thrown when <paramref name="channel"/> is null.</exception>
/// <returns>A new chord taking a continuation with the same shape.</returns>
public ActionChord<n, A> And(Asynchronous.Channel channel) {
return new ActionChord<n, A>(mJoin, new And<A>(mPattern, AtomFactory.FromChannel(channel)));
}
/// <summary>
/// Extends this pattern to wait for one message on each channel in the array <paramref name="channels"/>.
/// </summary>
/// <param name="channels"> the array of additional channels to wait on.</param>
/// <exception cref="JoinException"> thrown when <paramref name="channels"/> is null or contains a null channel.</exception>
/// <returns>A new chord taking a continuation with the same shape.</returns>
public ActionChord<n, A> And(Asynchronous.Channel[] channels) {
return new ActionChord<n, A>(mJoin, new And<A>(mPattern, VectorFactory.FromChannels(channels)));
}
/// <summary>
/// Extends this pattern to wait for one message on <paramref name="channel"/>.
/// </summary>
/// <param name="channel"> the additional channel to wait on.</param>
/// <exception cref="JoinException"> thrown when <paramref name="channel"/> is null.</exception>
/// <returns>A new chord taking a continuation with the same shape.</returns>
public ActionChord<n, A> And(Synchronous.Channel channel) {
return new ActionChord<n, A>(mJoin, new And<A>(mPattern, AtomFactory.FromChannel(channel)));
}
/// <summary>
/// Extends this pattern to wait for one message on each channel in the array <paramref name="channels"/>.
/// </summary>
/// <param name="channels"> the array of additional channels to wait on.</param>
/// <exception cref="JoinException"> thrown when <paramref name="channels"/> is null or contains a null channel.</exception>
/// <returns>A new chord taking a continuation with the same shape.</returns>
public ActionChord<n, A> And(Synchronous.Channel[] channels) {
return new ActionChord<n, A>(mJoin, new And<A>(mPattern, VectorFactory.FromChannels(channels)));
}
}
public static class ActionChordExtensions {
/// <summary>
/// Extends this pattern to wait for one message on <paramref name="channel"/>.
/// </summary>
/// <typeparam name="B"> the type of the channel and additional continuation argument.</typeparam>
/// <param name="chord"> the chord to extend.</param>
/// <param name="channel"> the additional channel to wait on.</param>
/// <exception cref="JoinException"> thrown when <paramref name="channel"/> is null.</exception>
/// <returns>A new chord taking a continuation with one additional parameter of type <c>B</c>.</returns>
public static ActionChord<S<Z>, B> And<B>(this ActionChord<Z, Unit> chord, Asynchronous.Channel<B> channel) {
return new ActionChord<S<Z>, B>(chord.mJoin, new And<B>( AtomFactory.FromChannel(channel), chord.mPattern));
}
/// <summary>
/// Extends this pattern to wait for one message on <paramref name="channel"/>.
/// </summary>
/// <typeparam name="n"> an auxilliary type counting continuation arguments.</typeparam>
/// <typeparam name="A"> the current (encoded) argument type of the chord.</typeparam>
/// <typeparam name="B"> the type of the channel and additional continuation argument.</typeparam>
/// <param name="chord"> the chord to extend.</param>
/// <param name="channel"> the additional channel to wait on.</param>
/// <exception cref="JoinException"> thrown when <paramref name="channel"/> is null.</exception>
/// <returns>A new chord taking a continuation with one additional parameter of type <c>B</c>.</returns>
public static ActionChord<S<S<n>>, Pair<A, B>> And<n,A,B>(this ActionChord<S<n>, A> chord, Asynchronous.Channel<B> channel) {
return new ActionChord<S<S<n>>, Pair<A, B>>(chord.mJoin, new And<A, B>(chord.mPattern, AtomFactory.FromChannel(channel)));
}
/// <summary>
/// Extends this pattern to wait for one message on each channel in the array <paramref name="channels"/>.
/// </summary>
/// <typeparam name="B"> the argument type of each channel in <paramref name="channels"/> and the element type of the new continuation's array argument.</typeparam>
/// <param name="chord"> the chord to extend.</param>
/// <param name="channels"> the array of additional channels to wait on.</param>
/// <exception cref="JoinException"> thrown when <paramref name="channels"/> is null or contains a null channel.</exception>
/// <returns>A new pattern taking a continuation with one additional argument <c>b</c> of type <c>B[]</c>, with <c>b[i]</c>
/// containing the value consumed from channel <c>channels[i]</c>.</returns>
public static ActionChord<S<Z>, B[]> And<B>(this ActionChord<Z,Unit> chord, Asynchronous.Channel<B>[] channels) {
return new ActionChord<S<Z>,B[]>(chord.mJoin, new And<B[]>(VectorFactory.FromChannels(channels), chord.mPattern));
}
/// <summary>
/// Extends this pattern to wait for one message on each channel in the array <paramref name="channels"/>.
/// </summary>
/// <typeparam name="n"> an auxilliary type counting continuation arguments.</typeparam>
/// <typeparam name="A"> the current (encoded) argument type of the chord.</typeparam>
/// <typeparam name="B"> the argument type of each channel in <paramref name="channels"/> and the element type of the new continuation's array argument.</typeparam>
/// <param name="chord"> the chord to extend.</param>
/// <param name="channels"> the array of additional channels to wait on.</param>
/// <exception cref="JoinException"> thrown when <paramref name="channels"/> is null or contains a null channel.</exception>
/// <returns>A new pattern taking a continuation with one additional argument <c>b</c> of type <c>B[]</c>, with <c>b[i]</c>
/// containing the value consumed from channel <c>channels[i]</c>.</returns>
public static ActionChord<S<S<n>>, Pair<A, B[]>> And<n,A,B>(this ActionChord<S<n>,A> chord, Asynchronous.Channel<B>[] channels) {
return new ActionChord<S<S<n>>, Pair<A, B[]>>(chord.mJoin, new And<A,B[]>(chord.mPattern, VectorFactory.FromChannels(channels)));
}
/// <summary>
/// Extends this pattern to wait for one message on <paramref name="channel"/>.
/// </summary>
/// <typeparam name="B"> the type of the channel and additional continuation argument.</typeparam>
/// <param name="chord"> the chord to extend.</param>
/// <param name="channel"> the additional channel to wait on.</param>
/// <exception cref="JoinException"> thrown when <paramref name="channel"/> is null.</exception>
/// <returns>A new chord taking a continuation with one additional parameter of type <c>B</c>.</returns>
public static ActionChord<S<Z>, B> And<B>(this ActionChord<Z,Unit> chord, Synchronous.Channel<B> channel) {
return new ActionChord<S<Z>, B>(chord.mJoin, new And<B>(AtomFactory.FromChannel(channel), chord.mPattern));
}
/// <summary>
/// Extends this pattern to wait for one message on <paramref name="channel"/>.
/// </summary>
/// <typeparam name="n"> an auxilliary type counting continuation arguments.</typeparam>
/// <typeparam name="A"> the current (encoded) argument type of the chord.</typeparam>
/// <typeparam name="B"> the type of the channel and additional continuation argument.</typeparam>
/// <param name="chord"> the chord to extend.</param>
/// <param name="channel"> the additional channel to wait on.</param>
/// <exception cref="JoinException"> thrown when <paramref name="channel"/> is null.</exception>
/// <returns>A new chord taking a continuation with one additional parameter of type <c>B</c>.</returns>
public static ActionChord<S<S<n>>, Pair<A, B>> And<n,A,B>(this ActionChord<S<n>,A> chord,Synchronous.Channel<B> channel) {
return new ActionChord<S<S<n>>, Pair<A, B>>(chord.mJoin, new And<A, B>(chord.mPattern, AtomFactory.FromChannel(channel)));
}
/// <summary>
/// Extends this pattern to wait for one message on each channel in the array <paramref name="channels"/>.
/// </summary>
/// <typeparam name="B"> the argument type of each channel in <paramref name="channels"/> and the element type of the new continuation's array argument.</typeparam>
/// <param name="chord"> the chord to extend.</param>
/// <param name="channels"> the array of additional channels to wait on.</param>
/// <exception cref="JoinException"> thrown when <paramref name="channels"/> is null or contains a null channel.</exception>
/// <returns>A new pattern taking a continuation with one additional argument <c>b</c> of type <c>B[]</c>, with <c>b[i]</c>
/// containing the value consumed from channel <c>channels[i]</c>.</returns>
public static ActionChord<S<Z>, B[]> And<B>(this ActionChord<Z,Unit> chord, Synchronous.Channel<B>[] channels) {
return new ActionChord<S<Z>, B[]>(chord.mJoin, new And<B[]>(VectorFactory.FromChannels(channels),chord.mPattern));
}
/// <summary>
/// Extends this pattern to wait for one message on each channel in the array <paramref name="channels"/>.
/// </summary>
/// <typeparam name="n"> an auxilliary type counting continuation arguments.</typeparam>
/// <typeparam name="A"> the current (encoded) argument type of the chord.</typeparam>
/// <typeparam name="B"> the argument type of each channel in <paramref name="channels"/> and the element type of the new continuation's array argument.</typeparam>
/// <param name="chord"> the chord to extend.</param>
/// <param name="channels"> the array of additional channels to wait on.</param>
/// <exception cref="JoinException"> thrown when <paramref name="channels"/> is null or contains a null channel.</exception>
/// <returns>A new pattern taking a continuation with one additional argument <c>b</c> of type <c>B[]</c>, with <c>b[i]</c>
/// containing the value consumed from channel <c>channels[i]</c>.</returns>
public static ActionChord<S<S<n>>, Pair<A, B[]>> And<n,A,B>(this ActionChord<S<n>,A> chord, Synchronous.Channel<B>[] channels) {
return new ActionChord<S<S<n>>, Pair<A, B[]>>(chord.mJoin, new And<A, B[]>(chord.mPattern, VectorFactory.FromChannels(channels)));
}
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class QuestOutroController : MonoBehaviour
{
public Image CreepEncountersImage;
public Text CreepEncountersText;
public Image HeroEncountersImage;
public Text HeroEncountersText;
public Image GoldCollectedImage;
public Text GoldCollectedText;
public Image LivesLostImage;
public Text LivesLostText;
public Image ItemsCollectedImage;
public Text ItemsCollectedText;
public Button ViewItems;
public FillBarController XpBar;
public Image QuestIcon;
public Text QuestName;
public Image BG;
public Sprite winBG;
public Sprite loseBG;
public Button ReturnToHub;
public Image Mastery;
public Image LevelUp;
public Text LivesRemaining;
public Button TryAgain;
public Button BuyMoreLives;
public LevelUpOverlayController LevelUpPane;
public Transform WinGraphics;
public Transform LoseGraphics;
public TweenColor colorTweener;
void OnEnable()
{
PF_Bridge.OnPlayFabCallbackError += HandleCallbackError;
PF_Bridge.OnPlayfabCallbackSuccess += HandleCallbackSuccess;
}
void OnDisable()
{
PF_Bridge.OnPlayFabCallbackError -= HandleCallbackError;
PF_Bridge.OnPlayfabCallbackSuccess -= HandleCallbackSuccess;
}
public void HandleCallbackError(string details, PlayFabAPIMethods method, MessageDisplayStyle style)
{
}
public void HandleCallbackSuccess(string details, PlayFabAPIMethods method, MessageDisplayStyle style)
{
}
public void OnReturnToHubClick()
{
if (PF_GamePlay.QuestProgress.isQuestWon)
{
Dictionary<string, object> eventData = new Dictionary<string, object>()
{
{ "Current_Quest", PF_GamePlay.ActiveQuest.levelName },
{ "Character_ID", PF_PlayerData.activeCharacter.characterDetails.CharacterId }
};
PF_Bridge.LogCustomEvent(PF_Bridge.CustomEventTypes.Client_LevelComplete, eventData);
}
if (PF_PlayerData.activeCharacter.PlayerVitals.didLevelUp)
{
Dictionary<string, object> eventData = new Dictionary<string, object>()
{
{ "New_Level", PF_PlayerData.activeCharacter.characterData.CharacterLevel + 1 },
{ "Character_ID", PF_PlayerData.activeCharacter.characterDetails.CharacterId },
{ "Current_Quest", PF_GamePlay.ActiveQuest.levelName }
};
PF_Bridge.LogCustomEvent(PF_Bridge.CustomEventTypes.Client_LevelUp, eventData);
}
// Only save if the game has been won
// may want to add in some stats for missions failed / deaths
if (PF_GamePlay.QuestProgress.isQuestWon)
{
PF_GamePlay.SavePlayerData();
SaveStatistics();
if (PF_GamePlay.QuestProgress.areItemsAwarded == false)
{
PF_GamePlay.RetriveQuestItems();
}
}
var loadingDelay = .5f;
if (PF_GamePlay.UseRaidMode)
{
var eventData = new Dictionary<string, object>
{
{ "Killed_By", "Raid Mode" },
{ "Enemy_Health", "Raid Mode" },
{ "Current_Quest", PF_GamePlay.ActiveQuest.levelName },
{ "Character_ID", PF_PlayerData.activeCharacter.characterDetails.CharacterId }
};
for (var z = 0; z < PF_GamePlay.QuestProgress.Deaths; z++)
{
PF_PlayerData.SubtractLifeFromPlayer();
PF_Bridge.LogCustomEvent(PF_Bridge.CustomEventTypes.Client_PlayerDied, eventData);
}
}
GameController.Instance.sceneController.RequestSceneChange(SceneController.GameScenes.Profile, loadingDelay);
}
public void SaveStatistics()
{
var prefix = PF_GamePlay.ActiveQuest.levelData.StatsPrefix;
var charUpdates = new Dictionary<string, int>();
var damageDone = 0;
var bossesKilled = 0;
foreach (var item in PF_GamePlay.QuestProgress.CompletedEncounters)
{
if (item.Data.EncounterType == EncounterTypes.BossCreep)
{
bossesKilled++;
}
if (item.Data.EncounterType.ToString().Contains(GlobalStrings.ENCOUNTER_CREEP))
{
damageDone += item.Data.Vitals.MaxHealth;
}
}
// Character Statistics Section
charUpdates.Add(prefix + "Complete", PF_GamePlay.ActiveQuest.difficulty);
charUpdates.Add(prefix + "Deaths", PF_GamePlay.QuestProgress.Deaths);
charUpdates.Add(prefix + "DamageDone", damageDone);
charUpdates.Add(prefix + "EncountersCompleted", PF_GamePlay.QuestProgress.CompletedEncounters.Count);
charUpdates.Add(prefix + "UnicornsRescued", PF_GamePlay.QuestProgress.HeroRescues);
charUpdates.Add(prefix + "ItemsUsed", PF_GamePlay.QuestProgress.ItemsUsed);
charUpdates.Add(prefix + "XPGained", PF_GamePlay.QuestProgress.XpCollected);
charUpdates.Add(prefix + "ItemsFound", PF_GamePlay.QuestProgress.ItemsFound.Count);
charUpdates.Add(prefix + "GoldFound", PF_GamePlay.QuestProgress.GoldCollected);
charUpdates.Add("QuestsCompleted", 1);
charUpdates.Add("BossesKilled", bossesKilled);
PF_PlayerData.UpdateCharacterStatistics(PF_PlayerData.activeCharacter.characterDetails.CharacterId, charUpdates);
// User Statistics Section
Dictionary<string, int> userUpdates = new Dictionary<string, int>();
// Special calculation for the HighestCharacterLevel (we're pushing a delta, so we have to determine it)
var curLevel = PF_PlayerData.activeCharacter.characterData.CharacterLevel;
var savedLevel = 0;
PF_PlayerData.userStatistics.TryGetValue("HighestCharacterLevel", out savedLevel);
var levelUpdate = (Math.Max(curLevel, savedLevel) - savedLevel);
userUpdates.Add("Total_DamageDone", damageDone);
userUpdates.Add("Total_EncountersCompleted", PF_GamePlay.QuestProgress.CompletedEncounters.Count);
userUpdates.Add("Total_UnicornsRescued", PF_GamePlay.QuestProgress.HeroRescues);
userUpdates.Add("Total_ItemsUsed", PF_GamePlay.QuestProgress.ItemsUsed);
userUpdates.Add("Total_XPGained", PF_GamePlay.QuestProgress.XpCollected);
userUpdates.Add(prefix + "XPGained", PF_GamePlay.QuestProgress.XpCollected);
userUpdates.Add("Total_ItemsFound", PF_GamePlay.QuestProgress.ItemsFound.Count);
userUpdates.Add("Total_GoldFound", PF_GamePlay.QuestProgress.GoldCollected);
userUpdates.Add("Total_QuestsCompleted", 1);
userUpdates.Add("Total_BossesKilled", bossesKilled);
userUpdates.Add("HighestCharacterLevel", levelUpdate);
PF_PlayerData.UpdateUserStatistics(userUpdates);
}
public void UpdateQuestStats()
{
//TODO update mastery stars to reflect difficulty.
if (PF_GamePlay.QuestProgress != null)
{
CreepEncountersText.text = "x" + PF_GamePlay.QuestProgress.CreepEncounters;
GoldCollectedText.text = string.Format("+{0:n0}", PF_GamePlay.QuestProgress.GoldCollected);
ItemsCollectedText.text = string.Format("+{0}", PF_GamePlay.QuestProgress.ItemsFound.Count);
HeroEncountersText.text = "x" + PF_GamePlay.QuestProgress.HeroRescues;
LivesLostText.text = string.Format("- {0}", PF_GamePlay.QuestProgress.Deaths);
if (PF_GamePlay.QuestProgress.isQuestWon)
{
PF_GamePlay.IntroPane(WinGraphics.gameObject, .333f, null);
PF_GamePlay.OutroPane(LoseGraphics.gameObject, .01f, null);
colorTweener.from = Color.blue;
colorTweener.to = Color.magenta;
BG.overrideSprite = winBG;
}
else
{
PF_GamePlay.IntroPane(LoseGraphics.gameObject, .333f, null);
PF_GamePlay.OutroPane(WinGraphics.gameObject, .01f, null);
colorTweener.from = Color.red;
colorTweener.to = Color.yellow;
BG.overrideSprite = loseBG;
}
}
if (PF_PlayerData.activeCharacter != null && PF_GamePlay.ActiveQuest.levelIcon != null)
{
//PlayerIcon.overrideSprite = GameController.Instance.iconManager.GetIconById(PF_PlayerData.activeCharacter.baseClass.Icon);
QuestIcon.overrideSprite = PF_GamePlay.ActiveQuest.levelIcon;
QuestName.text = PF_GamePlay.ActiveQuest.levelName;
var balance = 0;
LivesRemaining.text = string.Format("{0}", PF_PlayerData.virtualCurrency.TryGetValue(GlobalStrings.HEART_CURRENCY, out balance) ? balance : -1);
var nextLevelStr = string.Format("{0}", PF_PlayerData.activeCharacter.characterData.CharacterLevel + 1);
if (PF_GameData.CharacterLevelRamp.ContainsKey(nextLevelStr) && PF_GamePlay.QuestProgress.isQuestWon)
{
XpBar.maxValue = PF_GameData.CharacterLevelRamp[nextLevelStr];
StartCoroutine(XpBar.UpdateBarWithCallback(PF_PlayerData.activeCharacter.characterData.ExpThisLevel + PF_GamePlay.QuestProgress.XpCollected, false, EvaluateLevelUp));
ViewItems.interactable = true;
// PlayerLevel.text = "" + PF_PlayerData.activeCharacter.characterData.CharacterLevel;
// PlayerName.text = PF_PlayerData.activeCharacter.characterDetails.CharacterName;
}
}
}
void EvaluateLevelUp()
{
if (XpBar.maxValue < PF_PlayerData.activeCharacter.characterData.ExpThisLevel + PF_GamePlay.QuestProgress.XpCollected)
{
// Level Up!!!
PF_PlayerData.activeCharacter.PlayerVitals.didLevelUp = true;
PF_GamePlay.IntroPane(LevelUp.gameObject, .333f, null);
LevelUpPane.Init();
StartCoroutine(PF_GamePlay.Wait(1.5f, () => { PF_GamePlay.IntroPane(LevelUpPane.gameObject, .333f, null); }));
}
}
public void AcceptLevelupInput(int spellNumber)
{
PF_PlayerData.activeCharacter.PlayerVitals.skillSelected = spellNumber;
PF_GamePlay.OutroPane(LevelUpPane.gameObject, .333f, null);
}
public void OnTryAgainClick()
{
//Debug.Log("Try Again not implemented");
int hearts;
PF_PlayerData.virtualCurrency.TryGetValue(GlobalStrings.HEART_CURRENCY, out hearts);
if (hearts > 0)
{
// decrement HT currency
hearts -= 1;
PF_PlayerData.virtualCurrency[GlobalStrings.HEART_CURRENCY] = hearts;
PF_PlayerData.SubtractLifeFromPlayer();
// will need to trigger Cloud Script to tick this on the server side
PF_PlayerData.activeCharacter.RefillVitals();
PF_GamePlay.OutroPane(gameObject, .333f, null);
GameplayController.RaiseGameplayEvent(GlobalStrings.PLAYER_RESPAWN_EVENT, PF_GamePlay.GameplayEventTypes.EnemyTurnEnds);
}
}
public void ShowItemsFound()
{
DialogCanvasController.RequestItemViewer(PF_GamePlay.QuestProgress.ItemsFound);
}
public void OnBuyMoreLivesClick()
{
Debug.Log("Buy More Lives not implemented");
//throw an error?
}
}
| |
using System;
namespace CatLib._3rd.ICSharpCode.SharpZipLib.Zip.Compression
{
/// <summary>
/// This is the DeflaterHuffman class.
///
/// This class is <i>not</i> thread safe. This is inherent in the API, due
/// to the split of Deflate and SetInput.
///
/// author of the original java version : Jochen Hoenicke
/// </summary>
public class DeflaterHuffman
{
const int BUFSIZE = 1 << (DeflaterConstants.DEFAULT_MEM_LEVEL + 6);
const int LITERAL_NUM = 286;
// Number of distance codes
const int DIST_NUM = 30;
// Number of codes used to transfer bit lengths
const int BITLEN_NUM = 19;
// repeat previous bit length 3-6 times (2 bits of repeat count)
const int REP_3_6 = 16;
// repeat a zero length 3-10 times (3 bits of repeat count)
const int REP_3_10 = 17;
// repeat a zero length 11-138 times (7 bits of repeat count)
const int REP_11_138 = 18;
const int EOF_SYMBOL = 256;
// The lengths of the bit length codes are sent in order of decreasing
// probability, to avoid transmitting the lengths for unused bit length codes.
static readonly int[] BL_ORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
static readonly byte[] bit4Reverse = {
0,
8,
4,
12,
2,
10,
6,
14,
1,
9,
5,
13,
3,
11,
7,
15
};
static short[] staticLCodes;
static byte[] staticLLength;
static short[] staticDCodes;
static byte[] staticDLength;
class Tree
{
#region Instance Fields
public short[] freqs;
public byte[] length;
public int minNumCodes;
public int numCodes;
short[] codes;
readonly int[] bl_counts;
readonly int maxLength;
DeflaterHuffman dh;
#endregion
#region Constructors
public Tree(DeflaterHuffman dh, int elems, int minCodes, int maxLength)
{
this.dh = dh;
this.minNumCodes = minCodes;
this.maxLength = maxLength;
freqs = new short[elems];
bl_counts = new int[maxLength];
}
#endregion
/// <summary>
/// Resets the internal state of the tree
/// </summary>
public void Reset()
{
for (int i = 0; i < freqs.Length; i++) {
freqs[i] = 0;
}
codes = null;
length = null;
}
public void WriteSymbol(int code)
{
// if (DeflaterConstants.DEBUGGING) {
// freqs[code]--;
// // Console.Write("writeSymbol("+freqs.length+","+code+"): ");
// }
dh.pending.WriteBits(codes[code] & 0xffff, length[code]);
}
/// <summary>
/// Check that all frequencies are zero
/// </summary>
/// <exception cref="SharpZipBaseException">
/// At least one frequency is non-zero
/// </exception>
public void CheckEmpty()
{
bool empty = true;
for (int i = 0; i < freqs.Length; i++) {
empty &= freqs[i] == 0;
}
if (!empty) {
throw new SharpZipBaseException("!Empty");
}
}
/// <summary>
/// Set static codes and length
/// </summary>
/// <param name="staticCodes">new codes</param>
/// <param name="staticLengths">length for new codes</param>
public void SetStaticCodes(short[] staticCodes, byte[] staticLengths)
{
codes = staticCodes;
length = staticLengths;
}
/// <summary>
/// Build dynamic codes and lengths
/// </summary>
public void BuildCodes()
{
int numSymbols = freqs.Length;
int[] nextCode = new int[maxLength];
int code = 0;
codes = new short[freqs.Length];
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("buildCodes: "+freqs.Length);
// }
for (int bits = 0; bits < maxLength; bits++) {
nextCode[bits] = code;
code += bl_counts[bits] << (15 - bits);
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("bits: " + ( bits + 1) + " count: " + bl_counts[bits]
// +" nextCode: "+code);
// }
}
#if DebugDeflation
if ( DeflaterConstants.DEBUGGING && (code != 65536) )
{
throw new SharpZipBaseException("Inconsistent bl_counts!");
}
#endif
for (int i = 0; i < numCodes; i++) {
int bits = length[i];
if (bits > 0) {
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("codes["+i+"] = rev(" + nextCode[bits-1]+"),
// +bits);
// }
codes[i] = BitReverse(nextCode[bits - 1]);
nextCode[bits - 1] += 1 << (16 - bits);
}
}
}
public void BuildTree()
{
int numSymbols = freqs.Length;
/* heap is a priority queue, sorted by frequency, least frequent
* nodes first. The heap is a binary tree, with the property, that
* the parent node is smaller than both child nodes. This assures
* that the smallest node is the first parent.
*
* The binary tree is encoded in an array: 0 is root node and
* the nodes 2*n+1, 2*n+2 are the child nodes of node n.
*/
int[] heap = new int[numSymbols];
int heapLen = 0;
int maxCode = 0;
for (int n = 0; n < numSymbols; n++) {
int freq = freqs[n];
if (freq != 0) {
// Insert n into heap
int pos = heapLen++;
int ppos;
while (pos > 0 && freqs[heap[ppos = (pos - 1) / 2]] > freq) {
heap[pos] = heap[ppos];
pos = ppos;
}
heap[pos] = n;
maxCode = n;
}
}
/* We could encode a single literal with 0 bits but then we
* don't see the literals. Therefore we force at least two
* literals to avoid this case. We don't care about order in
* this case, both literals get a 1 bit code.
*/
while (heapLen < 2) {
int node = maxCode < 2 ? ++maxCode : 0;
heap[heapLen++] = node;
}
numCodes = Math.Max(maxCode + 1, minNumCodes);
int numLeafs = heapLen;
int[] childs = new int[4 * heapLen - 2];
int[] values = new int[2 * heapLen - 1];
int numNodes = numLeafs;
for (int i = 0; i < heapLen; i++) {
int node = heap[i];
childs[2 * i] = node;
childs[2 * i + 1] = -1;
values[i] = freqs[node] << 8;
heap[i] = i;
}
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
do {
int first = heap[0];
int last = heap[--heapLen];
// Propagate the hole to the leafs of the heap
int ppos = 0;
int path = 1;
while (path < heapLen) {
if (path + 1 < heapLen && values[heap[path]] > values[heap[path + 1]]) {
path++;
}
heap[ppos] = heap[path];
ppos = path;
path = path * 2 + 1;
}
/* Now propagate the last element down along path. Normally
* it shouldn't go too deep.
*/
int lastVal = values[last];
while ((path = ppos) > 0 && values[heap[ppos = (path - 1) / 2]] > lastVal) {
heap[path] = heap[ppos];
}
heap[path] = last;
int second = heap[0];
// Create a new node father of first and second
last = numNodes++;
childs[2 * last] = first;
childs[2 * last + 1] = second;
int mindepth = Math.Min(values[first] & 0xff, values[second] & 0xff);
values[last] = lastVal = values[first] + values[second] - mindepth + 1;
// Again, propagate the hole to the leafs
ppos = 0;
path = 1;
while (path < heapLen) {
if (path + 1 < heapLen && values[heap[path]] > values[heap[path + 1]]) {
path++;
}
heap[ppos] = heap[path];
ppos = path;
path = ppos * 2 + 1;
}
// Now propagate the new element down along path
while ((path = ppos) > 0 && values[heap[ppos = (path - 1) / 2]] > lastVal) {
heap[path] = heap[ppos];
}
heap[path] = last;
} while (heapLen > 1);
if (heap[0] != childs.Length / 2 - 1) {
throw new SharpZipBaseException("Heap invariant violated");
}
BuildLength(childs);
}
/// <summary>
/// Get encoded length
/// </summary>
/// <returns>Encoded length, the sum of frequencies * lengths</returns>
public int GetEncodedLength()
{
int len = 0;
for (int i = 0; i < freqs.Length; i++) {
len += freqs[i] * length[i];
}
return len;
}
/// <summary>
/// Scan a literal or distance tree to determine the frequencies of the codes
/// in the bit length tree.
/// </summary>
public void CalcBLFreq(Tree blTree)
{
int max_count; /* max repeat count */
int min_count; /* min repeat count */
int count; /* repeat count of the current code */
int curlen = -1; /* length of current code */
int i = 0;
while (i < numCodes) {
count = 1;
int nextlen = length[i];
if (nextlen == 0) {
max_count = 138;
min_count = 3;
} else {
max_count = 6;
min_count = 3;
if (curlen != nextlen) {
blTree.freqs[nextlen]++;
count = 0;
}
}
curlen = nextlen;
i++;
while (i < numCodes && curlen == length[i]) {
i++;
if (++count >= max_count) {
break;
}
}
if (count < min_count) {
blTree.freqs[curlen] += (short)count;
} else if (curlen != 0) {
blTree.freqs[REP_3_6]++;
} else if (count <= 10) {
blTree.freqs[REP_3_10]++;
} else {
blTree.freqs[REP_11_138]++;
}
}
}
/// <summary>
/// Write tree values
/// </summary>
/// <param name="blTree">Tree to write</param>
public void WriteTree(Tree blTree)
{
int max_count; // max repeat count
int min_count; // min repeat count
int count; // repeat count of the current code
int curlen = -1; // length of current code
int i = 0;
while (i < numCodes) {
count = 1;
int nextlen = length[i];
if (nextlen == 0) {
max_count = 138;
min_count = 3;
} else {
max_count = 6;
min_count = 3;
if (curlen != nextlen) {
blTree.WriteSymbol(nextlen);
count = 0;
}
}
curlen = nextlen;
i++;
while (i < numCodes && curlen == length[i]) {
i++;
if (++count >= max_count) {
break;
}
}
if (count < min_count) {
while (count-- > 0) {
blTree.WriteSymbol(curlen);
}
} else if (curlen != 0) {
blTree.WriteSymbol(REP_3_6);
dh.pending.WriteBits(count - 3, 2);
} else if (count <= 10) {
blTree.WriteSymbol(REP_3_10);
dh.pending.WriteBits(count - 3, 3);
} else {
blTree.WriteSymbol(REP_11_138);
dh.pending.WriteBits(count - 11, 7);
}
}
}
void BuildLength(int[] childs)
{
this.length = new byte[freqs.Length];
int numNodes = childs.Length / 2;
int numLeafs = (numNodes + 1) / 2;
int overflow = 0;
for (int i = 0; i < maxLength; i++) {
bl_counts[i] = 0;
}
// First calculate optimal bit lengths
int[] lengths = new int[numNodes];
lengths[numNodes - 1] = 0;
for (int i = numNodes - 1; i >= 0; i--) {
if (childs[2 * i + 1] != -1) {
int bitLength = lengths[i] + 1;
if (bitLength > maxLength) {
bitLength = maxLength;
overflow++;
}
lengths[childs[2 * i]] = lengths[childs[2 * i + 1]] = bitLength;
} else {
// A leaf node
int bitLength = lengths[i];
bl_counts[bitLength - 1]++;
this.length[childs[2 * i]] = (byte)lengths[i];
}
}
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("Tree "+freqs.Length+" lengths:");
// for (int i=0; i < numLeafs; i++) {
// //Console.WriteLine("Node "+childs[2*i]+" freq: "+freqs[childs[2*i]]
// + " len: "+length[childs[2*i]]);
// }
// }
if (overflow == 0) {
return;
}
int incrBitLen = maxLength - 1;
do {
// Find the first bit length which could increase:
while (bl_counts[--incrBitLen] == 0) {
}
// Move this node one down and remove a corresponding
// number of overflow nodes.
do {
bl_counts[incrBitLen]--;
bl_counts[++incrBitLen]++;
overflow -= 1 << (maxLength - 1 - incrBitLen);
} while (overflow > 0 && incrBitLen < maxLength - 1);
} while (overflow > 0);
/* We may have overshot above. Move some nodes from maxLength to
* maxLength-1 in that case.
*/
bl_counts[maxLength - 1] += overflow;
bl_counts[maxLength - 2] -= overflow;
/* Now recompute all bit lengths, scanning in increasing
* frequency. It is simpler to reconstruct all lengths instead of
* fixing only the wrong ones. This idea is taken from 'ar'
* written by Haruhiko Okumura.
*
* The nodes were inserted with decreasing frequency into the childs
* array.
*/
int nodePtr = 2 * numLeafs;
for (int bits = maxLength; bits != 0; bits--) {
int n = bl_counts[bits - 1];
while (n > 0) {
int childPtr = 2 * childs[nodePtr++];
if (childs[childPtr + 1] == -1) {
// We found another leaf
length[childs[childPtr]] = (byte)bits;
n--;
}
}
}
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("*** After overflow elimination. ***");
// for (int i=0; i < numLeafs; i++) {
// //Console.WriteLine("Node "+childs[2*i]+" freq: "+freqs[childs[2*i]]
// + " len: "+length[childs[2*i]]);
// }
// }
}
}
#region Instance Fields
/// <summary>
/// Pending buffer to use
/// </summary>
public DeflaterPending pending;
Tree literalTree;
Tree distTree;
Tree blTree;
// Buffer for distances
short[] d_buf;
byte[] l_buf;
int last_lit;
int extra_bits;
#endregion
static DeflaterHuffman()
{
// See RFC 1951 3.2.6
// Literal codes
staticLCodes = new short[LITERAL_NUM];
staticLLength = new byte[LITERAL_NUM];
int i = 0;
while (i < 144) {
staticLCodes[i] = BitReverse((0x030 + i) << 8);
staticLLength[i++] = 8;
}
while (i < 256) {
staticLCodes[i] = BitReverse((0x190 - 144 + i) << 7);
staticLLength[i++] = 9;
}
while (i < 280) {
staticLCodes[i] = BitReverse((0x000 - 256 + i) << 9);
staticLLength[i++] = 7;
}
while (i < LITERAL_NUM) {
staticLCodes[i] = BitReverse((0x0c0 - 280 + i) << 8);
staticLLength[i++] = 8;
}
// Distance codes
staticDCodes = new short[DIST_NUM];
staticDLength = new byte[DIST_NUM];
for (i = 0; i < DIST_NUM; i++) {
staticDCodes[i] = BitReverse(i << 11);
staticDLength[i] = 5;
}
}
/// <summary>
/// Construct instance with pending buffer
/// </summary>
/// <param name="pending">Pending buffer to use</param>
public DeflaterHuffman(DeflaterPending pending)
{
this.pending = pending;
literalTree = new Tree(this, LITERAL_NUM, 257, 15);
distTree = new Tree(this, DIST_NUM, 1, 15);
blTree = new Tree(this, BITLEN_NUM, 4, 7);
d_buf = new short[BUFSIZE];
l_buf = new byte[BUFSIZE];
}
/// <summary>
/// Reset internal state
/// </summary>
public void Reset()
{
last_lit = 0;
extra_bits = 0;
literalTree.Reset();
distTree.Reset();
blTree.Reset();
}
/// <summary>
/// Write all trees to pending buffer
/// </summary>
/// <param name="blTreeCodes">The number/rank of treecodes to send.</param>
public void SendAllTrees(int blTreeCodes)
{
blTree.BuildCodes();
literalTree.BuildCodes();
distTree.BuildCodes();
pending.WriteBits(literalTree.numCodes - 257, 5);
pending.WriteBits(distTree.numCodes - 1, 5);
pending.WriteBits(blTreeCodes - 4, 4);
for (int rank = 0; rank < blTreeCodes; rank++) {
pending.WriteBits(blTree.length[BL_ORDER[rank]], 3);
}
literalTree.WriteTree(blTree);
distTree.WriteTree(blTree);
#if DebugDeflation
if (DeflaterConstants.DEBUGGING) {
blTree.CheckEmpty();
}
#endif
}
/// <summary>
/// Compress current buffer writing data to pending buffer
/// </summary>
public void CompressBlock()
{
for (int i = 0; i < last_lit; i++) {
int litlen = l_buf[i] & 0xff;
int dist = d_buf[i];
if (dist-- != 0) {
// if (DeflaterConstants.DEBUGGING) {
// Console.Write("["+(dist+1)+","+(litlen+3)+"]: ");
// }
int lc = Lcode(litlen);
literalTree.WriteSymbol(lc);
int bits = (lc - 261) / 4;
if (bits > 0 && bits <= 5) {
pending.WriteBits(litlen & ((1 << bits) - 1), bits);
}
int dc = Dcode(dist);
distTree.WriteSymbol(dc);
bits = dc / 2 - 1;
if (bits > 0) {
pending.WriteBits(dist & ((1 << bits) - 1), bits);
}
} else {
// if (DeflaterConstants.DEBUGGING) {
// if (litlen > 32 && litlen < 127) {
// Console.Write("("+(char)litlen+"): ");
// } else {
// Console.Write("{"+litlen+"}: ");
// }
// }
literalTree.WriteSymbol(litlen);
}
}
#if DebugDeflation
if (DeflaterConstants.DEBUGGING) {
Console.Write("EOF: ");
}
#endif
literalTree.WriteSymbol(EOF_SYMBOL);
#if DebugDeflation
if (DeflaterConstants.DEBUGGING) {
literalTree.CheckEmpty();
distTree.CheckEmpty();
}
#endif
}
/// <summary>
/// Flush block to output with no compression
/// </summary>
/// <param name="stored">Data to write</param>
/// <param name="storedOffset">Index of first byte to write</param>
/// <param name="storedLength">Count of bytes to write</param>
/// <param name="lastBlock">True if this is the last block</param>
public void FlushStoredBlock(byte[] stored, int storedOffset, int storedLength, bool lastBlock)
{
#if DebugDeflation
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("Flushing stored block "+ storedLength);
// }
#endif
pending.WriteBits((DeflaterConstants.STORED_BLOCK << 1) + (lastBlock ? 1 : 0), 3);
pending.AlignToByte();
pending.WriteShort(storedLength);
pending.WriteShort(~storedLength);
pending.WriteBlock(stored, storedOffset, storedLength);
Reset();
}
/// <summary>
/// Flush block to output with compression
/// </summary>
/// <param name="stored">Data to flush</param>
/// <param name="storedOffset">Index of first byte to flush</param>
/// <param name="storedLength">Count of bytes to flush</param>
/// <param name="lastBlock">True if this is the last block</param>
public void FlushBlock(byte[] stored, int storedOffset, int storedLength, bool lastBlock)
{
literalTree.freqs[EOF_SYMBOL]++;
// Build trees
literalTree.BuildTree();
distTree.BuildTree();
// Calculate bitlen frequency
literalTree.CalcBLFreq(blTree);
distTree.CalcBLFreq(blTree);
// Build bitlen tree
blTree.BuildTree();
int blTreeCodes = 4;
for (int i = 18; i > blTreeCodes; i--) {
if (blTree.length[BL_ORDER[i]] > 0) {
blTreeCodes = i + 1;
}
}
int opt_len = 14 + blTreeCodes * 3 + blTree.GetEncodedLength() +
literalTree.GetEncodedLength() + distTree.GetEncodedLength() +
extra_bits;
int static_len = extra_bits;
for (int i = 0; i < LITERAL_NUM; i++) {
static_len += literalTree.freqs[i] * staticLLength[i];
}
for (int i = 0; i < DIST_NUM; i++) {
static_len += distTree.freqs[i] * staticDLength[i];
}
if (opt_len >= static_len) {
// Force static trees
opt_len = static_len;
}
if (storedOffset >= 0 && storedLength + 4 < opt_len >> 3) {
// Store Block
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("Storing, since " + storedLength + " < " + opt_len
// + " <= " + static_len);
// }
FlushStoredBlock(stored, storedOffset, storedLength, lastBlock);
} else if (opt_len == static_len) {
// Encode with static tree
pending.WriteBits((DeflaterConstants.STATIC_TREES << 1) + (lastBlock ? 1 : 0), 3);
literalTree.SetStaticCodes(staticLCodes, staticLLength);
distTree.SetStaticCodes(staticDCodes, staticDLength);
CompressBlock();
Reset();
} else {
// Encode with dynamic tree
pending.WriteBits((DeflaterConstants.DYN_TREES << 1) + (lastBlock ? 1 : 0), 3);
SendAllTrees(blTreeCodes);
CompressBlock();
Reset();
}
}
/// <summary>
/// Get value indicating if internal buffer is full
/// </summary>
/// <returns>true if buffer is full</returns>
public bool IsFull()
{
return last_lit >= BUFSIZE;
}
/// <summary>
/// Add literal to buffer
/// </summary>
/// <param name="literal">Literal value to add to buffer.</param>
/// <returns>Value indicating internal buffer is full</returns>
public bool TallyLit(int literal)
{
// if (DeflaterConstants.DEBUGGING) {
// if (lit > 32 && lit < 127) {
// //Console.WriteLine("("+(char)lit+")");
// } else {
// //Console.WriteLine("{"+lit+"}");
// }
// }
d_buf[last_lit] = 0;
l_buf[last_lit++] = (byte)literal;
literalTree.freqs[literal]++;
return IsFull();
}
/// <summary>
/// Add distance code and length to literal and distance trees
/// </summary>
/// <param name="distance">Distance code</param>
/// <param name="length">Length</param>
/// <returns>Value indicating if internal buffer is full</returns>
public bool TallyDist(int distance, int length)
{
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("[" + distance + "," + length + "]");
// }
d_buf[last_lit] = (short)distance;
l_buf[last_lit++] = (byte)(length - 3);
int lc = Lcode(length - 3);
literalTree.freqs[lc]++;
if (lc >= 265 && lc < 285) {
extra_bits += (lc - 261) / 4;
}
int dc = Dcode(distance - 1);
distTree.freqs[dc]++;
if (dc >= 4) {
extra_bits += dc / 2 - 1;
}
return IsFull();
}
/// <summary>
/// Reverse the bits of a 16 bit value.
/// </summary>
/// <param name="toReverse">Value to reverse bits</param>
/// <returns>Value with bits reversed</returns>
public static short BitReverse(int toReverse)
{
return (short)(bit4Reverse[toReverse & 0xF] << 12 |
bit4Reverse[(toReverse >> 4) & 0xF] << 8 |
bit4Reverse[(toReverse >> 8) & 0xF] << 4 |
bit4Reverse[toReverse >> 12]);
}
static int Lcode(int length)
{
if (length == 255) {
return 285;
}
int code = 257;
while (length >= 8) {
code += 4;
length >>= 1;
}
return code + length;
}
static int Dcode(int distance)
{
int code = 0;
while (distance >= 4) {
code += 2;
distance >>= 1;
}
return code + distance;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
namespace System.Globalization
{
// This abstract class represents a calendar. A calendar reckons time in
// divisions such as weeks, months and years. The number, length and start of
// the divisions vary in each calendar.
//
// Any instant in time can be represented as an n-tuple of numeric values using
// a particular calendar. For example, the next vernal equinox occurs at (0.0, 0
// , 46, 8, 20, 3, 1999) in the Gregorian calendar. An implementation of
// Calendar can map any DateTime value to such an n-tuple and vice versa. The
// DateTimeFormat class can map between such n-tuples and a textual
// representation such as "8:46 AM March 20th 1999 AD".
//
// Most calendars identify a year which begins the current era. There may be any
// number of previous eras. The Calendar class identifies the eras as enumerated
// integers where the current era (CurrentEra) has the value zero.
//
// For consistency, the first unit in each interval, e.g. the first month, is
// assigned the value one.
// The calculation of hour/minute/second is moved to Calendar from GregorianCalendar,
// since most of the calendars (or all?) have the same way of calcuating hour/minute/second.
[Serializable]
public abstract partial class Calendar : ICloneable
{
// Number of 100ns (10E-7 second) ticks per time unit
internal const long TicksPerMillisecond = 10000;
internal const long TicksPerSecond = TicksPerMillisecond * 1000;
internal const long TicksPerMinute = TicksPerSecond * 60;
internal const long TicksPerHour = TicksPerMinute * 60;
internal const long TicksPerDay = TicksPerHour * 24;
// Number of milliseconds per time unit
internal const int MillisPerSecond = 1000;
internal const int MillisPerMinute = MillisPerSecond * 60;
internal const int MillisPerHour = MillisPerMinute * 60;
internal const int MillisPerDay = MillisPerHour * 24;
// Number of days in a non-leap year
internal const int DaysPerYear = 365;
// Number of days in 4 years
internal const int DaysPer4Years = DaysPerYear * 4 + 1;
// Number of days in 100 years
internal const int DaysPer100Years = DaysPer4Years * 25 - 1;
// Number of days in 400 years
internal const int DaysPer400Years = DaysPer100Years * 4 + 1;
// Number of days from 1/1/0001 to 1/1/10000
internal const int DaysTo10000 = DaysPer400Years * 25 - 366;
internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay;
private int _currentEraValue = -1;
[OptionalField(VersionAdded = 2)]
private bool _isReadOnly = false;
#if CORECLR
internal const CalendarId CAL_HEBREW = CalendarId.HEBREW;
internal const CalendarId CAL_HIJRI = CalendarId.HIJRI;
internal const CalendarId CAL_JAPAN = CalendarId.JAPAN;
internal const CalendarId CAL_JULIAN = CalendarId.JULIAN;
internal const CalendarId CAL_TAIWAN = CalendarId.TAIWAN;
internal const CalendarId CAL_UMALQURA = CalendarId.UMALQURA;
internal const CalendarId CAL_PERSIAN = CalendarId.PERSIAN;
#endif
// The minimum supported DateTime range for the calendar.
public virtual DateTime MinSupportedDateTime
{
get
{
return (DateTime.MinValue);
}
}
// The maximum supported DateTime range for the calendar.
public virtual DateTime MaxSupportedDateTime
{
get
{
return (DateTime.MaxValue);
}
}
public virtual CalendarAlgorithmType AlgorithmType
{
get
{
return CalendarAlgorithmType.Unknown;
}
}
protected Calendar()
{
//Do-nothing constructor.
}
///
// This can not be abstract, otherwise no one can create a subclass of Calendar.
//
internal virtual CalendarId ID
{
get
{
return CalendarId.UNINITIALIZED_VALUE;
}
}
///
// Return the Base calendar ID for calendars that didn't have defined data in calendarData
//
internal virtual CalendarId BaseCalendarID
{
get { return ID; }
}
////////////////////////////////////////////////////////////////////////
//
// IsReadOnly
//
// Detect if the object is readonly.
//
////////////////////////////////////////////////////////////////////////
public bool IsReadOnly
{
get { return (_isReadOnly); }
}
////////////////////////////////////////////////////////////////////////
//
// Clone
//
// Is the implementation of ICloneable.
//
////////////////////////////////////////////////////////////////////////
public virtual object Clone()
{
object o = MemberwiseClone();
((Calendar)o).SetReadOnlyState(false);
return (o);
}
////////////////////////////////////////////////////////////////////////
//
// ReadOnly
//
// Create a cloned readonly instance or return the input one if it is
// readonly.
//
////////////////////////////////////////////////////////////////////////
public static Calendar ReadOnly(Calendar calendar)
{
if (calendar == null) { throw new ArgumentNullException(nameof(calendar)); }
Contract.EndContractBlock();
if (calendar.IsReadOnly) { return (calendar); }
Calendar clonedCalendar = (Calendar)(calendar.MemberwiseClone());
clonedCalendar.SetReadOnlyState(true);
return (clonedCalendar);
}
internal void VerifyWritable()
{
if (_isReadOnly)
{
throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
}
internal void SetReadOnlyState(bool readOnly)
{
_isReadOnly = readOnly;
}
/*=================================CurrentEraValue==========================
**Action: This is used to convert CurretEra(0) to an appropriate era value.
**Returns:
**Arguments:
**Exceptions:
**Notes:
** The value is from calendar.nlp.
============================================================================*/
internal virtual int CurrentEraValue
{
get
{
// The following code assumes that the current era value can not be -1.
if (_currentEraValue == -1)
{
Debug.Assert(BaseCalendarID != CalendarId.UNINITIALIZED_VALUE, "[Calendar.CurrentEraValue] Expected a real calendar ID");
_currentEraValue = CalendarData.GetCalendarData(BaseCalendarID).iCurrentEra;
}
return (_currentEraValue);
}
}
// The current era for a calendar.
public const int CurrentEra = 0;
internal int twoDigitYearMax = -1;
internal static void CheckAddResult(long ticks, DateTime minValue, DateTime maxValue)
{
if (ticks < minValue.Ticks || ticks > maxValue.Ticks)
{
throw new ArgumentException(
String.Format(CultureInfo.InvariantCulture, SR.Format(SR.Argument_ResultCalendarRange,
minValue, maxValue)));
}
Contract.EndContractBlock();
}
internal DateTime Add(DateTime time, double value, int scale)
{
// From ECMA CLI spec, Partition III, section 3.27:
//
// If overflow occurs converting a floating-point type to an integer, or if the floating-point value
// being converted to an integer is a NaN, the value returned is unspecified.
//
// Based upon this, this method should be performing the comparison against the double
// before attempting a cast. Otherwise, the result is undefined.
double tempMillis = (value * scale + (value >= 0 ? 0.5 : -0.5));
if (!((tempMillis > -(double)MaxMillis) && (tempMillis < (double)MaxMillis)))
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_AddValue);
}
long millis = (long)tempMillis;
long ticks = time.Ticks + millis * TicksPerMillisecond;
CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (new DateTime(ticks));
}
// Returns the DateTime resulting from adding the given number of
// milliseconds to the specified DateTime. The result is computed by rounding
// the number of milliseconds given by value to the nearest integer,
// and adding that interval to the specified DateTime. The value
// argument is permitted to be negative.
//
public virtual DateTime AddMilliseconds(DateTime time, double milliseconds)
{
return (Add(time, milliseconds, 1));
}
// Returns the DateTime resulting from adding a fractional number of
// days to the specified DateTime. The result is computed by rounding the
// fractional number of days given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddDays(DateTime time, int days)
{
return (Add(time, days, MillisPerDay));
}
// Returns the DateTime resulting from adding a fractional number of
// hours to the specified DateTime. The result is computed by rounding the
// fractional number of hours given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddHours(DateTime time, int hours)
{
return (Add(time, hours, MillisPerHour));
}
// Returns the DateTime resulting from adding a fractional number of
// minutes to the specified DateTime. The result is computed by rounding the
// fractional number of minutes given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddMinutes(DateTime time, int minutes)
{
return (Add(time, minutes, MillisPerMinute));
}
// Returns the DateTime resulting from adding the given number of
// months to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year and month parts of the specified DateTime by
// value months, and, if required, adjusting the day part of the
// resulting date downwards to the last day of the resulting month in the
// resulting year. The time-of-day part of the result is the same as the
// time-of-day part of the specified DateTime.
//
// In more precise terms, considering the specified DateTime to be of the
// form y / m / d + t, where y is the
// year, m is the month, d is the day, and t is the
// time-of-day, the result is y1 / m1 / d1 + t,
// where y1 and m1 are computed by adding value months
// to y and m, and d1 is the largest value less than
// or equal to d that denotes a valid day in month m1 of year
// y1.
//
public abstract DateTime AddMonths(DateTime time, int months);
// Returns the DateTime resulting from adding a number of
// seconds to the specified DateTime. The result is computed by rounding the
// fractional number of seconds given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddSeconds(DateTime time, int seconds)
{
return Add(time, seconds, MillisPerSecond);
}
// Returns the DateTime resulting from adding a number of
// weeks to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddWeeks(DateTime time, int weeks)
{
return (AddDays(time, weeks * 7));
}
// Returns the DateTime resulting from adding the given number of
// years to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year part of the specified DateTime by value
// years. If the month and day of the specified DateTime is 2/29, and if the
// resulting year is not a leap year, the month and day of the resulting
// DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
// parts of the result are the same as those of the specified DateTime.
//
public abstract DateTime AddYears(DateTime time, int years);
// Returns the day-of-month part of the specified DateTime. The returned
// value is an integer between 1 and 31.
//
public abstract int GetDayOfMonth(DateTime time);
// Returns the day-of-week part of the specified DateTime. The returned value
// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
public abstract DayOfWeek GetDayOfWeek(DateTime time);
// Returns the day-of-year part of the specified DateTime. The returned value
// is an integer between 1 and 366.
//
public abstract int GetDayOfYear(DateTime time);
// Returns the number of days in the month given by the year and
// month arguments.
//
public virtual int GetDaysInMonth(int year, int month)
{
return (GetDaysInMonth(year, month, CurrentEra));
}
// Returns the number of days in the month given by the year and
// month arguments for the specified era.
//
public abstract int GetDaysInMonth(int year, int month, int era);
// Returns the number of days in the year given by the year argument for the current era.
//
public virtual int GetDaysInYear(int year)
{
return (GetDaysInYear(year, CurrentEra));
}
// Returns the number of days in the year given by the year argument for the current era.
//
public abstract int GetDaysInYear(int year, int era);
// Returns the era for the specified DateTime value.
public abstract int GetEra(DateTime time);
/*=================================Eras==========================
**Action: Get the list of era values.
**Returns: The int array of the era names supported in this calendar.
** null if era is not used.
**Arguments: None.
**Exceptions: None.
============================================================================*/
public abstract int[] Eras
{
get;
}
// Returns the hour part of the specified DateTime. The returned value is an
// integer between 0 and 23.
//
public virtual int GetHour(DateTime time)
{
return ((int)((time.Ticks / TicksPerHour) % 24));
}
// Returns the millisecond part of the specified DateTime. The returned value
// is an integer between 0 and 999.
//
public virtual double GetMilliseconds(DateTime time)
{
return (double)((time.Ticks / TicksPerMillisecond) % 1000);
}
// Returns the minute part of the specified DateTime. The returned value is
// an integer between 0 and 59.
//
public virtual int GetMinute(DateTime time)
{
return ((int)((time.Ticks / TicksPerMinute) % 60));
}
// Returns the month part of the specified DateTime. The returned value is an
// integer between 1 and 12.
//
public abstract int GetMonth(DateTime time);
// Returns the number of months in the specified year in the current era.
public virtual int GetMonthsInYear(int year)
{
return (GetMonthsInYear(year, CurrentEra));
}
// Returns the number of months in the specified year and era.
public abstract int GetMonthsInYear(int year, int era);
// Returns the second part of the specified DateTime. The returned value is
// an integer between 0 and 59.
//
public virtual int GetSecond(DateTime time)
{
return ((int)((time.Ticks / TicksPerSecond) % 60));
}
/*=================================GetFirstDayWeekOfYear==========================
**Action: Get the week of year using the FirstDay rule.
**Returns: the week of year.
**Arguments:
** time
** firstDayOfWeek the first day of week (0=Sunday, 1=Monday, ... 6=Saturday)
**Notes:
** The CalendarWeekRule.FirstDay rule: Week 1 begins on the first day of the year.
** Assume f is the specifed firstDayOfWeek,
** and n is the day of week for January 1 of the specified year.
** Assign offset = n - f;
** Case 1: offset = 0
** E.g.
** f=1
** weekday 0 1 2 3 4 5 6 0 1
** date 1/1
** week# 1 2
** then week of year = (GetDayOfYear(time) - 1) / 7 + 1
**
** Case 2: offset < 0
** e.g.
** n=1 f=3
** weekday 0 1 2 3 4 5 6 0
** date 1/1
** week# 1 2
** This means that the first week actually starts 5 days before 1/1.
** So week of year = (GetDayOfYear(time) + (7 + offset) - 1) / 7 + 1
** Case 3: offset > 0
** e.g.
** f=0 n=2
** weekday 0 1 2 3 4 5 6 0 1 2
** date 1/1
** week# 1 2
** This means that the first week actually starts 2 days before 1/1.
** So Week of year = (GetDayOfYear(time) + offset - 1) / 7 + 1
============================================================================*/
internal int GetFirstDayWeekOfYear(DateTime time, int firstDayOfWeek)
{
int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
// Calculate the day of week for the first day of the year.
// dayOfWeek - (dayOfYear % 7) is the day of week for the first day of this year. Note that
// this value can be less than 0. It's fine since we are making it positive again in calculating offset.
int dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7);
int offset = (dayForJan1 - firstDayOfWeek + 14) % 7;
Debug.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0");
return ((dayOfYear + offset) / 7 + 1);
}
private int GetWeekOfYearFullDays(DateTime time, int firstDayOfWeek, int fullDays)
{
int dayForJan1;
int offset;
int day;
int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
//
// Calculate the number of days between the first day of year (1/1) and the first day of the week.
// This value will be a positive value from 0 ~ 6. We call this value as "offset".
//
// If offset is 0, it means that the 1/1 is the start of the first week.
// Assume the first day of the week is Monday, it will look like this:
// Sun Mon Tue Wed Thu Fri Sat
// 12/31 1/1 1/2 1/3 1/4 1/5 1/6
// +--> First week starts here.
//
// If offset is 1, it means that the first day of the week is 1 day ahead of 1/1.
// Assume the first day of the week is Monday, it will look like this:
// Sun Mon Tue Wed Thu Fri Sat
// 1/1 1/2 1/3 1/4 1/5 1/6 1/7
// +--> First week starts here.
//
// If offset is 2, it means that the first day of the week is 2 days ahead of 1/1.
// Assume the first day of the week is Monday, it will look like this:
// Sat Sun Mon Tue Wed Thu Fri Sat
// 1/1 1/2 1/3 1/4 1/5 1/6 1/7 1/8
// +--> First week starts here.
// Day of week is 0-based.
// Get the day of week for 1/1. This can be derived from the day of week of the target day.
// Note that we can get a negative value. It's ok since we are going to make it a positive value when calculating the offset.
dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7);
// Now, calculate the offset. Subtract the first day of week from the dayForJan1. And make it a positive value.
offset = (firstDayOfWeek - dayForJan1 + 14) % 7;
if (offset != 0 && offset >= fullDays)
{
//
// If the offset is greater than the value of fullDays, it means that
// the first week of the year starts on the week where Jan/1 falls on.
//
offset -= 7;
}
//
// Calculate the day of year for specified time by taking offset into account.
//
day = dayOfYear - offset;
if (day >= 0)
{
//
// If the day of year value is greater than zero, get the week of year.
//
return (day / 7 + 1);
}
//
// Otherwise, the specified time falls on the week of previous year.
// Call this method again by passing the last day of previous year.
//
// the last day of the previous year may "underflow" to no longer be a valid date time for
// this calendar if we just subtract so we need the subclass to provide us with
// that information
if (time <= MinSupportedDateTime.AddDays(dayOfYear))
{
return GetWeekOfYearOfMinSupportedDateTime(firstDayOfWeek, fullDays);
}
return (GetWeekOfYearFullDays(time.AddDays(-(dayOfYear + 1)), firstDayOfWeek, fullDays));
}
private int GetWeekOfYearOfMinSupportedDateTime(int firstDayOfWeek, int minimumDaysInFirstWeek)
{
int dayOfYear = GetDayOfYear(MinSupportedDateTime) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
int dayOfWeekOfFirstOfYear = (int)GetDayOfWeek(MinSupportedDateTime) - dayOfYear % 7;
// Calculate the offset (how many days from the start of the year to the start of the week)
int offset = (firstDayOfWeek + 7 - dayOfWeekOfFirstOfYear) % 7;
if (offset == 0 || offset >= minimumDaysInFirstWeek)
{
// First of year falls in the first week of the year
return 1;
}
int daysInYearBeforeMinSupportedYear = DaysInYearBeforeMinSupportedYear - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
int dayOfWeekOfFirstOfPreviousYear = dayOfWeekOfFirstOfYear - 1 - (daysInYearBeforeMinSupportedYear % 7);
// starting from first day of the year, how many days do you have to go forward
// before getting to the first day of the week?
int daysInInitialPartialWeek = (firstDayOfWeek - dayOfWeekOfFirstOfPreviousYear + 14) % 7;
int day = daysInYearBeforeMinSupportedYear - daysInInitialPartialWeek;
if (daysInInitialPartialWeek >= minimumDaysInFirstWeek)
{
// If the offset is greater than the minimum Days in the first week, it means that
// First of year is part of the first week of the year even though it is only a partial week
// add another week
day += 7;
}
return (day / 7 + 1);
}
// it would be nice to make this abstract but we can't since that would break previous implementations
protected virtual int DaysInYearBeforeMinSupportedYear
{
get
{
return 365;
}
}
// Returns the week of year for the specified DateTime. The returned value is an
// integer between 1 and 53.
//
public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
if ((int)firstDayOfWeek < 0 || (int)firstDayOfWeek > 6)
{
throw new ArgumentOutOfRangeException(
nameof(firstDayOfWeek), SR.Format(SR.ArgumentOutOfRange_Range,
DayOfWeek.Sunday, DayOfWeek.Saturday));
}
Contract.EndContractBlock();
switch (rule)
{
case CalendarWeekRule.FirstDay:
return (GetFirstDayWeekOfYear(time, (int)firstDayOfWeek));
case CalendarWeekRule.FirstFullWeek:
return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 7));
case CalendarWeekRule.FirstFourDayWeek:
return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 4));
}
throw new ArgumentOutOfRangeException(
nameof(rule), SR.Format(SR.ArgumentOutOfRange_Range,
CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek));
}
// Returns the year part of the specified DateTime. The returned value is an
// integer between 1 and 9999.
//
public abstract int GetYear(DateTime time);
// Checks whether a given day in the current era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public virtual bool IsLeapDay(int year, int month, int day)
{
return (IsLeapDay(year, month, day, CurrentEra));
}
// Checks whether a given day in the specified era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public abstract bool IsLeapDay(int year, int month, int day, int era);
// Checks whether a given month in the current era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public virtual bool IsLeapMonth(int year, int month)
{
return (IsLeapMonth(year, month, CurrentEra));
}
// Checks whether a given month in the specified era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public abstract bool IsLeapMonth(int year, int month, int era);
// Returns the leap month in a calendar year of the current era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
public virtual int GetLeapMonth(int year)
{
return (GetLeapMonth(year, CurrentEra));
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
public virtual int GetLeapMonth(int year, int era)
{
if (!IsLeapYear(year, era))
return 0;
int monthsCount = GetMonthsInYear(year, era);
for (int month = 1; month <= monthsCount; month++)
{
if (IsLeapMonth(year, month, era))
return month;
}
return 0;
}
// Checks whether a given year in the current era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public virtual bool IsLeapYear(int year)
{
return (IsLeapYear(year, CurrentEra));
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public abstract bool IsLeapYear(int year, int era);
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public virtual DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond)
{
return (ToDateTime(year, month, day, hour, minute, second, millisecond, CurrentEra));
}
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public abstract DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era);
internal virtual Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result)
{
result = DateTime.MinValue;
try
{
result = ToDateTime(year, month, day, hour, minute, second, millisecond, era);
return true;
}
catch (ArgumentException)
{
return false;
}
}
internal virtual bool IsValidYear(int year, int era)
{
return (year >= GetYear(MinSupportedDateTime) && year <= GetYear(MaxSupportedDateTime));
}
internal virtual bool IsValidMonth(int year, int month, int era)
{
return (IsValidYear(year, era) && month >= 1 && month <= GetMonthsInYear(year, era));
}
internal virtual bool IsValidDay(int year, int month, int day, int era)
{
return (IsValidMonth(year, month, era) && day >= 1 && day <= GetDaysInMonth(year, month, era));
}
// Returns and assigns the maximum value to represent a two digit year. This
// value is the upper boundary of a 100 year range that allows a two digit year
// to be properly translated to a four digit year. For example, if 2029 is the
// upper boundary, then a two digit value of 30 should be interpreted as 1930
// while a two digit value of 29 should be interpreted as 2029. In this example
// , the 100 year range would be from 1930-2029. See ToFourDigitYear().
public virtual int TwoDigitYearMax
{
get
{
return (twoDigitYearMax);
}
set
{
VerifyWritable();
twoDigitYearMax = value;
}
}
// Converts the year value to the appropriate century by using the
// TwoDigitYearMax property. For example, if the TwoDigitYearMax value is 2029,
// then a two digit value of 30 will get converted to 1930 while a two digit
// value of 29 will get converted to 2029.
public virtual int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
if (year < 100)
{
return ((TwoDigitYearMax / 100 - (year > TwoDigitYearMax % 100 ? 1 : 0)) * 100 + year);
}
// If the year value is above 100, just return the year value. Don't have to do
// the TwoDigitYearMax comparison.
return (year);
}
// Return the tick count corresponding to the given hour, minute, second.
// Will check the if the parameters are valid.
internal static long TimeToTicks(int hour, int minute, int second, int millisecond)
{
if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60)
{
if (millisecond < 0 || millisecond >= MillisPerSecond)
{
throw new ArgumentOutOfRangeException(
nameof(millisecond),
String.Format(
CultureInfo.InvariantCulture,
SR.Format(SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1)));
}
return InternalGloablizationHelper.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond;
}
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond);
}
internal static int GetSystemTwoDigitYearSetting(CalendarId CalID, int defaultYearValue)
{
int twoDigitYearMax = CalendarData.GetTwoDigitYearMax(CalID);
if (twoDigitYearMax < 0)
{
twoDigitYearMax = defaultYearValue;
}
return (twoDigitYearMax);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Shell;
using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
using IServiceProvider = System.IServiceProvider;
using ShellConstants = Microsoft.VisualStudio.Shell.Interop.Constants;
using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants;
using System.Diagnostics;
using System.ComponentModel.Design;
namespace Microsoft.VisualStudio.FSharp.LanguageService {
/// <summary>
/// This class View provides an abstract base class for simple editor views
/// that follow the VS simple embedding model.
/// </summary>
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class SimpleEditorView : IOleCommandTarget, IVsWindowPane, IVsToolboxUser, IVsStatusbarUser, IVsWindowPaneCommit, IOleComponent // for idle processing.
//IServiceProvider,
//IVsMultiViewDocumentView,
//IVsFindTarget,
//IVsWindowFrameNotify,
//IVsCodeWindow,
//IVsBroadcastMessageEvents,
//IVsDocOutlineProvider,
//IVsDebuggerEvents,
// ??? VxDTE::IExtensibleObject,
//IVsBackForwardNavigation
// ??? public ISelectionContainer,
{
IServiceProvider site;
IVsTextLines buffer;
IOleComponentManager componentManager;
uint componentID;
internal SimpleEditorView() {}
protected IServiceProvider Site {
get { return this.site; }
set { this.site = value; }
}
protected IVsTextLines Buffer {
get { return this.buffer; }
set { this.buffer = value; }
}
protected IOleComponentManager ComponentManager {
get { return this.componentManager; }
set { this.componentManager = value; }
}
protected uint ComponentId {
get { return this.componentID; }
set { this.componentID = value; }
}
protected SimpleEditorView(IVsTextLines buffer) {
this.buffer = buffer;
}
/// <summary>
/// Override this method to provide custom command status,
/// e.g. (int)OLECMDF.OLECMDF_SUPPORTED | (int)OLECMDF.OLECMDF_ENABLED
/// </summary>
protected virtual int QueryCommandStatus(ref Guid guidCmdGroup, uint cmdId) {
IServiceProvider sp = this.Site;
if (sp != null) {
// Delegate to menu command service just in case the child control registered some MenuCommands with it.
IMenuCommandService svc = sp.GetService(typeof(IMenuCommandService)) as IMenuCommandService;
if (svc != null) {
MenuCommand cmd = svc.FindCommand(new CommandID(guidCmdGroup, (int)cmdId));
if (cmd != null) {
return cmd.OleStatus;
}
}
}
return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED;
}
/// <summary>
/// Override this method to intercept the IOleCommandTarget::Exec call.
/// </summary>
/// <returns>Usually returns 0 if ok, or OLECMDERR_E_NOTSUPPORTED</returns>
protected virtual int ExecCommand(ref Guid guidCmdGroup, uint cmdId, uint cmdExecOptions, IntPtr pvaIn, IntPtr pvaOut) {
IServiceProvider sp = this.Site;
if (sp != null) {
// Delegate to menu command service just in case the child control registered some MenuCommands with it.
IMenuCommandService svc = sp.GetService(typeof(IMenuCommandService)) as IMenuCommandService;
if (svc != null) {
MenuCommand cmd = svc.FindCommand(new CommandID(guidCmdGroup, (int)cmdId));
if (cmd != null) {
cmd.Invoke();
}
}
}
return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED;
}
/// <summary>
/// This method is called when IOleCommandTarget.Exec is called with
/// nCmdexecopt equal to MAKELONG(OLECMDEXECOPT_SHOWHELP, VSCmdOptQueryParameterList).
/// </summary>
/// <returns>Usually returns 0 if ok, or OLECMDERR_E_NOTSUPPORTED</returns>
protected virtual int QueryParameterList(ref Guid guidCmdGroup, uint id, uint options, IntPtr pvaIn, IntPtr pvaOut) {
#if LANGTRACE
Trace.WriteLine(String.Format("QueryParameterList({0},{1})", guidCmdGroup.ToString(), id));
#endif
return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED;
}
/// <internalonly/>
/// <summary>
/// IOleCommandTarget implementation
/// </summary>
public virtual int QueryStatus(ref Guid guidCmdGroup, uint cmds, OLECMD[] prgCmds, IntPtr pCmdText) {
for (uint i = 0; i < cmds; i++) {
int rc = QueryCommandStatus(ref guidCmdGroup, (uint)prgCmds[i].cmdID);
if (rc < 0) return rc;
}
return 0;
}
/// <internalonly/>
public virtual int Exec(ref Guid guidCmdGroup, uint id, uint options, IntPtr pvaIn, IntPtr pvaOut) {
ushort lo = (ushort)(options & (uint)0xffff);
ushort hi = (ushort)(options >> 16);
switch (lo) {
case (ushort)OLECMDEXECOPT.OLECMDEXECOPT_SHOWHELP:
if ((options >> 16) == Microsoft.VisualStudio.Shell.VsMenus.VSCmdOptQueryParameterList) {
return QueryParameterList(ref guidCmdGroup, id, options, pvaIn, pvaOut);
}
break;
case (ushort)OLECMDEXECOPT.OLECMDEXECOPT_PROMPTUSER: // todo
case (ushort)OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER: // todo
return NativeMethods.E_NOTIMPL;
case (ushort)OLECMDEXECOPT.OLECMDEXECOPT_DODEFAULT:
default:
return ExecCommand(ref guidCmdGroup, id, options, pvaIn, pvaOut);
}
return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED;
}
public virtual int ClosePane() {
return this.componentManager.FRevokeComponent(this.componentID);
}
public abstract int CreatePaneWindow(IntPtr hwndParent, int x, int y, int cx, int cy, out IntPtr hwnd);
public virtual int GetDefaultSize(SIZE[] size) {
size[0].cx = 100;
size[0].cy = 100;
return NativeMethods.S_OK;
}
public virtual int LoadViewState(Microsoft.VisualStudio.OLE.Interop.IStream stream) {
return NativeMethods.S_OK;
}
public virtual int SaveViewState(Microsoft.VisualStudio.OLE.Interop.IStream stream) {
return NativeMethods.S_OK;
}
public virtual int SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider site) {
this.site = new Microsoft.VisualStudio.Shell.ServiceProvider (site);
if (this.buffer != null) {
// register our independent view with the IVsTextManager so that it knows
// the user is working with a view over the text buffer. this will trigger
// the text buffer to prompt the user whether to reload the file if it is
// edited outside of the development Environment.
IVsTextManager textManager = (IVsTextManager)this.site.GetService(typeof(SVsTextManager));
// NOTE: NativeMethods.ThrowOnFailure is removed from this method because you are not allowed
// to fail a SetSite call, see debug assert at f:\dd\env\msenv\core\docwp.cpp line 87.
int hr = 0;
if (textManager != null) {
IVsWindowPane windowPane = (IVsWindowPane)this;
hr = textManager.RegisterIndependentView(this, this.buffer);
if (!NativeMethods.Succeeded(hr))
Debug.Assert(false, "RegisterIndependentView failed");
}
}
//register with ComponentManager for Idle processing
this.componentManager = (IOleComponentManager)this.site.GetService(typeof(SOleComponentManager));
if (componentID == 0) {
OLECRINFO[] crinfo = new OLECRINFO[1];
crinfo[0].cbSize = (uint)Marshal.SizeOf(typeof(OLECRINFO));
crinfo[0].grfcrf = (uint)_OLECRF.olecrfNeedIdleTime | (uint)_OLECRF.olecrfNeedPeriodicIdleTime | (uint)_OLECRF.olecrfNeedAllActiveNotifs | (uint)_OLECRF.olecrfNeedSpecActiveNotifs;
crinfo[0].grfcadvf = (uint)_OLECADVF.olecadvfModal | (uint)_OLECADVF.olecadvfRedrawOff | (uint)_OLECADVF.olecadvfWarningsOff;
crinfo[0].uIdleTimeInterval = 1000;
int hr = this.componentManager.FRegisterComponent(this, crinfo, out this.componentID);
if (!NativeMethods.Succeeded(hr))
Debug.Assert(false, "FRegisterComponent failed");
}
return NativeMethods.S_OK;
}
public virtual int TranslateAccelerator(MSG[] msg) {
return (int)NativeMethods.S_FALSE;
}
public virtual int IsSupported(Microsoft.VisualStudio.OLE.Interop.IDataObject data) {
return (int)NativeMethods.S_FALSE;
}
public virtual int ItemPicked(Microsoft.VisualStudio.OLE.Interop.IDataObject data) {
return NativeMethods.S_OK;
}
public virtual int SetInfo() {
return NativeMethods.S_OK;
}
public virtual int CommitPendingEdit(out int fCommitFailed) {
fCommitFailed = 0;
return NativeMethods.S_OK;
}
public virtual int FDoIdle(uint grfidlef) {
return 0;
}
public virtual void Terminate() {
}
public virtual int FPreTranslateMessage(MSG[] msg) {
return 0;
}
public virtual void OnEnterState(uint uStateID, int fEnter) {
}
public virtual void OnAppActivate(int fActive, uint dwOtherThreadID) {
}
public virtual void OnLoseActivation() {
}
public virtual void OnActivationChange(Microsoft.VisualStudio.OLE.Interop.IOleComponent pic, int fSameComponent, OLECRINFO[] pcrinfo, int fHostIsActivating, OLECHOSTINFO[] pchostinfo, uint dwReserved) {
}
public virtual int FContinueMessageLoop(uint uReason, IntPtr pvLoopData, MSG[] pMsgPeeked) {
return 1;
}
public virtual int FQueryTerminate(int fPromptUser) {
return 1;
}
public virtual IntPtr HwndGetWindow(uint dwWhich, uint dwReserved) {
return IntPtr.Zero;
}
public virtual int FReserved1(uint reserved, uint message, IntPtr wParam, IntPtr lParam) {
return 1;
}
}
/// <summary>
/// This class wraps a managed WinForm control and uses that as the editor window.
/// </summary>
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(true)]
public class EditorControl : SimpleEditorView {
Control control;
internal EditorControl(IServiceProvider site, IVsTextLines buffer, Control ctrl) : base(buffer) {
this.control = ctrl;
this.Site = site;
}
protected Control Control {
get { return this.control; }
set { this.control = value; }
}
public override int ClosePane() {
if (control != null) {
control.Dispose();
control = null;
}
return base.ClosePane();
}
public override int CreatePaneWindow(IntPtr hwndParent, int x, int y, int cx, int cy, out IntPtr hwnd) {
control.SuspendLayout();
control.Left = x;
control.Top = y;
control.Width = cx;
control.Height = cy;
control.ResumeLayout();
control.CreateControl();
//HACK: For some VS throws debug asserts if WS_MAXIMIZEBOX is set
//so we'll just turn off this window style here.
int windowStyle = (int)UnsafeNativeMethods.GetWindowLong(this.control.Handle, NativeMethods.GWL_STYLE);
windowStyle = windowStyle & ~(0x00010000); //WS_MAXIMIZEBOX;
NativeMethods.SetWindowLong(this.Control.Handle, NativeMethods.GWL_STYLE, windowStyle);
//End of workaround
NativeMethods.SetParent(control.Handle, hwndParent);
hwnd = control.Handle;
return NativeMethods.S_OK;
}
public override int CommitPendingEdit(out int fCommitFailed) {
fCommitFailed = 0;
return NativeMethods.S_OK;
}
public override int FDoIdle(uint grfidlef) {
return 0;
}
public override void OnAppActivate(int fActive, uint dwOtherThreadID) {
}
public override int FQueryTerminate(int fPromptUser) {
return 1;
}
public override void OnLoseActivation() {
}
public override IntPtr HwndGetWindow(uint dwWhich, uint dwReserved) {
return control.Handle;
}
}
}
| |
using System;
using System.Security.Cryptography;
using ICSharpCode.SharpZipLib.Checksum;
namespace ICSharpCode.SharpZipLib.Encryption
{
/// <summary>
/// PkzipClassic embodies the classic or original encryption facilities used in Pkzip archives.
/// While it has been superceded by more recent and more powerful algorithms, its still in use and
/// is viable for preventing casual snooping
/// </summary>
public abstract class PkzipClassic : SymmetricAlgorithm
{
/// <summary>
/// Generates new encryption keys based on given seed
/// </summary>
/// <param name="seed">The seed value to initialise keys with.</param>
/// <returns>A new key value.</returns>
static public byte[] GenerateKeys(byte[] seed)
{
if (seed == null) {
throw new ArgumentNullException(nameof(seed));
}
if (seed.Length == 0) {
throw new ArgumentException("Length is zero", nameof(seed));
}
uint[] newKeys = {
0x12345678,
0x23456789,
0x34567890
};
for (int i = 0; i < seed.Length; ++i) {
newKeys[0] = Crc32.ComputeCrc32(newKeys[0], seed[i]);
newKeys[1] = newKeys[1] + (byte)newKeys[0];
newKeys[1] = newKeys[1] * 134775813 + 1;
newKeys[2] = Crc32.ComputeCrc32(newKeys[2], (byte)(newKeys[1] >> 24));
}
byte[] result = new byte[12];
result[0] = (byte)(newKeys[0] & 0xff);
result[1] = (byte)((newKeys[0] >> 8) & 0xff);
result[2] = (byte)((newKeys[0] >> 16) & 0xff);
result[3] = (byte)((newKeys[0] >> 24) & 0xff);
result[4] = (byte)(newKeys[1] & 0xff);
result[5] = (byte)((newKeys[1] >> 8) & 0xff);
result[6] = (byte)((newKeys[1] >> 16) & 0xff);
result[7] = (byte)((newKeys[1] >> 24) & 0xff);
result[8] = (byte)(newKeys[2] & 0xff);
result[9] = (byte)((newKeys[2] >> 8) & 0xff);
result[10] = (byte)((newKeys[2] >> 16) & 0xff);
result[11] = (byte)((newKeys[2] >> 24) & 0xff);
return result;
}
}
/// <summary>
/// PkzipClassicCryptoBase provides the low level facilities for encryption
/// and decryption using the PkzipClassic algorithm.
/// </summary>
class PkzipClassicCryptoBase
{
/// <summary>
/// Transform a single byte
/// </summary>
/// <returns>
/// The transformed value
/// </returns>
protected byte TransformByte()
{
uint temp = ((keys[2] & 0xFFFF) | 2);
return (byte)((temp * (temp ^ 1)) >> 8);
}
/// <summary>
/// Set the key schedule for encryption/decryption.
/// </summary>
/// <param name="keyData">The data use to set the keys from.</param>
protected void SetKeys(byte[] keyData)
{
if (keyData == null) {
throw new ArgumentNullException(nameof(keyData));
}
if (keyData.Length != 12) {
throw new InvalidOperationException("Key length is not valid");
}
keys = new uint[3];
keys[0] = (uint)((keyData[3] << 24) | (keyData[2] << 16) | (keyData[1] << 8) | keyData[0]);
keys[1] = (uint)((keyData[7] << 24) | (keyData[6] << 16) | (keyData[5] << 8) | keyData[4]);
keys[2] = (uint)((keyData[11] << 24) | (keyData[10] << 16) | (keyData[9] << 8) | keyData[8]);
}
/// <summary>
/// Update encryption keys
/// </summary>
protected void UpdateKeys(byte ch)
{
keys[0] = Crc32.ComputeCrc32(keys[0], ch);
keys[1] = keys[1] + (byte)keys[0];
keys[1] = keys[1] * 134775813 + 1;
keys[2] = Crc32.ComputeCrc32(keys[2], (byte)(keys[1] >> 24));
}
/// <summary>
/// Reset the internal state.
/// </summary>
protected void Reset()
{
keys[0] = 0;
keys[1] = 0;
keys[2] = 0;
}
#region Instance Fields
uint[] keys;
#endregion
}
/// <summary>
/// PkzipClassic CryptoTransform for encryption.
/// </summary>
class PkzipClassicEncryptCryptoTransform : PkzipClassicCryptoBase, ICryptoTransform
{
/// <summary>
/// Initialise a new instance of <see cref="PkzipClassicEncryptCryptoTransform"></see>
/// </summary>
/// <param name="keyBlock">The key block to use.</param>
internal PkzipClassicEncryptCryptoTransform(byte[] keyBlock)
{
SetKeys(keyBlock);
}
#region ICryptoTransform Members
/// <summary>
/// Transforms the specified region of the specified byte array.
/// </summary>
/// <param name="inputBuffer">The input for which to compute the transform.</param>
/// <param name="inputOffset">The offset into the byte array from which to begin using data.</param>
/// <param name="inputCount">The number of bytes in the byte array to use as data.</param>
/// <returns>The computed transform.</returns>
public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
{
byte[] result = new byte[inputCount];
TransformBlock(inputBuffer, inputOffset, inputCount, result, 0);
return result;
}
/// <summary>
/// Transforms the specified region of the input byte array and copies
/// the resulting transform to the specified region of the output byte array.
/// </summary>
/// <param name="inputBuffer">The input for which to compute the transform.</param>
/// <param name="inputOffset">The offset into the input byte array from which to begin using data.</param>
/// <param name="inputCount">The number of bytes in the input byte array to use as data.</param>
/// <param name="outputBuffer">The output to which to write the transform.</param>
/// <param name="outputOffset">The offset into the output byte array from which to begin writing data.</param>
/// <returns>The number of bytes written.</returns>
public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
for (int i = inputOffset; i < inputOffset + inputCount; ++i) {
byte oldbyte = inputBuffer[i];
outputBuffer[outputOffset++] = (byte)(inputBuffer[i] ^ TransformByte());
UpdateKeys(oldbyte);
}
return inputCount;
}
/// <summary>
/// Gets a value indicating whether the current transform can be reused.
/// </summary>
public bool CanReuseTransform {
get {
return true;
}
}
/// <summary>
/// Gets the size of the input data blocks in bytes.
/// </summary>
public int InputBlockSize {
get {
return 1;
}
}
/// <summary>
/// Gets the size of the output data blocks in bytes.
/// </summary>
public int OutputBlockSize {
get {
return 1;
}
}
/// <summary>
/// Gets a value indicating whether multiple blocks can be transformed.
/// </summary>
public bool CanTransformMultipleBlocks {
get {
return true;
}
}
#endregion
#region IDisposable Members
/// <summary>
/// Cleanup internal state.
/// </summary>
public void Dispose()
{
Reset();
}
#endregion
}
/// <summary>
/// PkzipClassic CryptoTransform for decryption.
/// </summary>
class PkzipClassicDecryptCryptoTransform : PkzipClassicCryptoBase, ICryptoTransform
{
/// <summary>
/// Initialise a new instance of <see cref="PkzipClassicDecryptCryptoTransform"></see>.
/// </summary>
/// <param name="keyBlock">The key block to decrypt with.</param>
internal PkzipClassicDecryptCryptoTransform(byte[] keyBlock)
{
SetKeys(keyBlock);
}
#region ICryptoTransform Members
/// <summary>
/// Transforms the specified region of the specified byte array.
/// </summary>
/// <param name="inputBuffer">The input for which to compute the transform.</param>
/// <param name="inputOffset">The offset into the byte array from which to begin using data.</param>
/// <param name="inputCount">The number of bytes in the byte array to use as data.</param>
/// <returns>The computed transform.</returns>
public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
{
byte[] result = new byte[inputCount];
TransformBlock(inputBuffer, inputOffset, inputCount, result, 0);
return result;
}
/// <summary>
/// Transforms the specified region of the input byte array and copies
/// the resulting transform to the specified region of the output byte array.
/// </summary>
/// <param name="inputBuffer">The input for which to compute the transform.</param>
/// <param name="inputOffset">The offset into the input byte array from which to begin using data.</param>
/// <param name="inputCount">The number of bytes in the input byte array to use as data.</param>
/// <param name="outputBuffer">The output to which to write the transform.</param>
/// <param name="outputOffset">The offset into the output byte array from which to begin writing data.</param>
/// <returns>The number of bytes written.</returns>
public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
for (int i = inputOffset; i < inputOffset + inputCount; ++i) {
var newByte = (byte)(inputBuffer[i] ^ TransformByte());
outputBuffer[outputOffset++] = newByte;
UpdateKeys(newByte);
}
return inputCount;
}
/// <summary>
/// Gets a value indicating whether the current transform can be reused.
/// </summary>
public bool CanReuseTransform {
get {
return true;
}
}
/// <summary>
/// Gets the size of the input data blocks in bytes.
/// </summary>
public int InputBlockSize {
get {
return 1;
}
}
/// <summary>
/// Gets the size of the output data blocks in bytes.
/// </summary>
public int OutputBlockSize {
get {
return 1;
}
}
/// <summary>
/// Gets a value indicating whether multiple blocks can be transformed.
/// </summary>
public bool CanTransformMultipleBlocks {
get {
return true;
}
}
#endregion
#region IDisposable Members
/// <summary>
/// Cleanup internal state.
/// </summary>
public void Dispose()
{
Reset();
}
#endregion
}
/// <summary>
/// Defines a wrapper object to access the Pkzip algorithm.
/// This class cannot be inherited.
/// </summary>
public sealed class PkzipClassicManaged : PkzipClassic
{
/// <summary>
/// Get / set the applicable block size in bits.
/// </summary>
/// <remarks>The only valid block size is 8.</remarks>
public override int BlockSize {
get {
return 8;
}
set {
if (value != 8) {
throw new CryptographicException("Block size is invalid");
}
}
}
/// <summary>
/// Get an array of legal <see cref="KeySizes">key sizes.</see>
/// </summary>
public override KeySizes[] LegalKeySizes {
get {
KeySizes[] keySizes = new KeySizes[1];
keySizes[0] = new KeySizes(12 * 8, 12 * 8, 0);
return keySizes;
}
}
/// <summary>
/// Generate an initial vector.
/// </summary>
public override void GenerateIV()
{
// Do nothing.
}
/// <summary>
/// Get an array of legal <see cref="KeySizes">block sizes</see>.
/// </summary>
public override KeySizes[] LegalBlockSizes {
get {
KeySizes[] keySizes = new KeySizes[1];
keySizes[0] = new KeySizes(1 * 8, 1 * 8, 0);
return keySizes;
}
}
/// <summary>
/// Get / set the key value applicable.
/// </summary>
public override byte[] Key {
get {
if (key_ == null) {
GenerateKey();
}
return (byte[])key_.Clone();
}
set {
if (value == null) {
throw new ArgumentNullException(nameof(value));
}
if (value.Length != 12) {
throw new CryptographicException("Key size is illegal");
}
key_ = (byte[])value.Clone();
}
}
/// <summary>
/// Generate a new random key.
/// </summary>
public override void GenerateKey()
{
key_ = new byte[12];
var rnd = new Random();
rnd.NextBytes(key_);
}
/// <summary>
/// Create an encryptor.
/// </summary>
/// <param name="rgbKey">The key to use for this encryptor.</param>
/// <param name="rgbIV">Initialisation vector for the new encryptor.</param>
/// <returns>Returns a new PkzipClassic encryptor</returns>
public override ICryptoTransform CreateEncryptor(
byte[] rgbKey,
byte[] rgbIV)
{
key_ = rgbKey;
return new PkzipClassicEncryptCryptoTransform(Key);
}
/// <summary>
/// Create a decryptor.
/// </summary>
/// <param name="rgbKey">Keys to use for this new decryptor.</param>
/// <param name="rgbIV">Initialisation vector for the new decryptor.</param>
/// <returns>Returns a new decryptor.</returns>
public override ICryptoTransform CreateDecryptor(
byte[] rgbKey,
byte[] rgbIV)
{
key_ = rgbKey;
return new PkzipClassicDecryptCryptoTransform(Key);
}
#region Instance Fields
byte[] key_;
#endregion
}
}
| |
// NOTE: to match Mesen timings, set idleSynch to true at power on, and set start_up_offset to -3
using System;
using System.Linq;
using BizHawk.Common;
using BizHawk.Emulation.Common;
using BizHawk.Emulation.Cores.Components.M6502;
#pragma warning disable 162
namespace BizHawk.Emulation.Cores.Nintendo.NES
{
public partial class NES : IEmulator, ISoundProvider, ICycleTiming
{
//hardware/state
public MOS6502X<CpuLink> cpu;
public PPU ppu;
public APU apu;
public byte[] ram;
public byte[] CIRAM; //AKA nametables
string game_name = ""; //friendly name exposed to user and used as filename base
CartInfo cart; //the current cart prototype. should be moved into the board, perhaps
internal INESBoard Board; //the board hardware that is currently driving things
EDetectionOrigin origin = EDetectionOrigin.None;
int sprdma_countdown;
public bool _irq_apu; //various irq signals that get merged to the cpu irq pin
/// <summary>clock speed of the main cpu in hz</summary>
public int cpuclockrate { get; private set; }
//user configuration
public int[] palette_compiled = new int[64 * 8];
//variable set when VS system games are running
internal bool _isVS = false;
//some VS games have a ppu that switches 2000 and 2001, so keep trcak of that
public byte _isVS2c05 = 0;
//since prg reg for VS System is set in the controller regs, it is convenient to have it here
//instead of in the board
public byte VS_chr_reg;
public byte VS_prg_reg;
//various VS controls
public byte[] VS_dips = new byte[8];
public byte VS_service = 0;
public byte VS_coin_inserted=0;
public byte VS_ROM_control;
// cheat addr index tracker
// disables all cheats each frame
public int[] cheat_indexes = new int[0x10000];
public byte[] cheat_active = new byte[0x10000];
public int num_cheats;
// new input system
NESControlSettings ControllerSettings; // this is stored internally so that a new change of settings won't replace
IControllerDeck ControllerDeck;
byte latched4016;
private DisplayType _display_type = DisplayType.NTSC;
//Sound config
public void SetVol1(int v) { apu.m_vol = v; }
/// <summary>
/// for debugging only!
/// </summary>
public INESBoard GetBoard()
{
return Board;
}
#region Audio
BlipBuffer blip = new BlipBuffer(4096);
const int blipbuffsize = 4096;
public int old_s = 0;
public bool CanProvideAsync { get { return false; } }
public void SetSyncMode(SyncSoundMode mode)
{
if (mode != SyncSoundMode.Sync)
{
throw new NotSupportedException("Only sync mode is supported");
}
}
public void GetSamplesAsync(short[] samples)
{
throw new NotSupportedException("Async not supported");
}
public SyncSoundMode SyncMode
{
get { return SyncSoundMode.Sync; }
}
public void Dispose()
{
if (blip != null)
{
blip.Dispose();
blip = null;
}
}
public void GetSamplesSync(out short[] samples, out int nsamp)
{
blip.EndFrame(apu.sampleclock);
apu.sampleclock = 0;
nsamp = blip.SamplesAvailable();
samples = new short[nsamp * 2];
blip.ReadSamples(samples, nsamp, true);
// duplicate to stereo
for (int i = 0; i < nsamp * 2; i += 2)
samples[i + 1] = samples[i];
Board.ApplyCustomAudio(samples);
}
public void DiscardSamples()
{
blip.Clear();
apu.sampleclock = 0;
}
#endregion
public void HardReset()
{
cpu = new MOS6502X<CpuLink>(new CpuLink(this))
{
BCD_Enabled = false
};
ppu = new PPU(this);
ram = new byte[0x800];
CIRAM = new byte[0x800];
// wire controllers
// todo: allow changing this
ControllerDeck = ControllerSettings.Instantiate(ppu.LightGunCallback);
// set controller definition first time only
if (ControllerDefinition == null)
{
ControllerDefinition = new ControllerDefinition(ControllerDeck.GetDefinition());
ControllerDefinition.Name = "NES Controller";
// controls other than the deck
ControllerDefinition.BoolButtons.Add("Power");
ControllerDefinition.BoolButtons.Add("Reset");
if (Board is FDS)
{
var b = Board as FDS;
ControllerDefinition.BoolButtons.Add("FDS Eject");
for (int i = 0; i < b.NumSides; i++)
ControllerDefinition.BoolButtons.Add("FDS Insert " + i);
}
if (_isVS)
{
ControllerDefinition.BoolButtons.Add("Insert Coin P1");
ControllerDefinition.BoolButtons.Add("Insert Coin P2");
ControllerDefinition.BoolButtons.Add("Service Switch");
}
}
// Add in the reset timing float control for subneshawk
if (using_reset_timing && (ControllerDefinition.FloatControls.Count() == 0))
{
ControllerDefinition.FloatControls.Add("Reset Cycle");
ControllerDefinition.FloatRanges.Add(new ControllerDefinition.FloatRange(0, 0, 500000));
}
// don't replace the magicSoundProvider on reset, as it's not needed
// if (magicSoundProvider != null) magicSoundProvider.Dispose();
// set up region
switch (_display_type)
{
case Common.DisplayType.PAL:
apu = new APU(this, apu, true);
ppu.region = PPU.Region.PAL;
VsyncNum = 50;
VsyncDen = 1;
cpuclockrate = 1662607;
cpu_sequence = cpu_sequence_PAL;
_display_type = DisplayType.PAL;
ClockRate = 5320342.5;
break;
case Common.DisplayType.NTSC:
apu = new APU(this, apu, false);
ppu.region = PPU.Region.NTSC;
VsyncNum = 39375000;
VsyncDen = 655171;
cpuclockrate = 1789773;
cpu_sequence = cpu_sequence_NTSC;
ClockRate = 5369318.1818181818181818181818182;
break;
// this is in bootgod, but not used at all
case Common.DisplayType.Dendy:
apu = new APU(this, apu, false);
ppu.region = PPU.Region.Dendy;
VsyncNum = 50;
VsyncDen = 1;
cpuclockrate = 1773448;
cpu_sequence = cpu_sequence_NTSC;
_display_type = DisplayType.Dendy;
ClockRate = 5320342.5;
break;
default:
throw new Exception("Unknown displaytype!");
}
blip.SetRates((uint)cpuclockrate, 44100);
BoardSystemHardReset();
// apu has some specific power up bahaviour that we will emulate here
apu.NESHardReset();
if (SyncSettings.InitialWRamStatePattern != null && SyncSettings.InitialWRamStatePattern.Any())
{
for (int i = 0; i < 0x800; i++)
{
ram[i] = SyncSettings.InitialWRamStatePattern[i % SyncSettings.InitialWRamStatePattern.Count];
}
}
else
{
// check fceux's PowerNES and FCEU_MemoryRand function for more information:
// relevant games: Cybernoid; Minna no Taabou no Nakayoshi Daisakusen; Huang Di; and maybe mechanized attack
for (int i = 0; i < 0x800; i++)
{
if ((i & 4) != 0)
{
ram[i] = 0xFF;
}
else
{
ram[i] = 0x00;
}
}
}
SetupMemoryDomains();
// some boards cannot have specific values in RAM upon initialization
// Let's hard code those cases here
// these will be defined through the gameDB exclusively for now.
if (cart.DB_GameInfo!=null)
{
if (cart.DB_GameInfo.Hash == "60FC5FA5B5ACCAF3AEFEBA73FC8BFFD3C4DAE558" // Camerica Golden 5
|| cart.DB_GameInfo.Hash == "BAD382331C30B22A908DA4BFF2759C25113CC26A" // Camerica Golden 5
|| cart.DB_GameInfo.Hash == "40409FEC8249EFDB772E6FFB2DCD41860C6CCA23" // Camerica Pegasus 4-in-1
)
{
ram[0x701] = 0xFF;
}
if (cart.DB_GameInfo.Hash == "68ABE1E49C9E9CCEA978A48232432C252E5912C0") // Dancing Blocks
{
ram[0xEC] = 0;
ram[0xED] = 0;
}
if (cart.DB_GameInfo.Hash == "00C50062A2DECE99580063777590F26A253AAB6B") // Silva Saga
{
for (int i = 0; i < Board.WRAM.Length; i++)
{
Board.WRAM[i] = 0xFF;
}
}
}
}
public long CycleCount => ppu.TotalCycles;
public double ClockRate { get; private set; }
private int VsyncNum { get; set; }
private int VsyncDen { get; set; }
private IController _controller = NullController.Instance;
bool resetSignal;
bool hardResetSignal;
public bool FrameAdvance(IController controller, bool render, bool rendersound)
{
_controller = controller;
if (Tracer.Enabled)
cpu.TraceCallback = (s) => Tracer.Put(s);
else
cpu.TraceCallback = null;
lagged = true;
if (resetSignal)
{
Board.NESSoftReset();
cpu.NESSoftReset();
apu.NESSoftReset();
ppu.NESSoftReset();
}
else if (hardResetSignal)
{
HardReset();
}
Frame++;
//if (resetSignal)
//Controller.UnpressButton("Reset"); TODO fix this
resetSignal = controller.IsPressed("Reset");
hardResetSignal = controller.IsPressed("Power");
if (Board is FDS)
{
var b = Board as FDS;
if (controller.IsPressed("FDS Eject"))
b.Eject();
for (int i = 0; i < b.NumSides; i++)
if (controller.IsPressed("FDS Insert " + i))
b.InsertSide(i);
}
if (_isVS)
{
if (controller.IsPressed("Service Switch"))
VS_service = 1;
else
VS_service = 0;
if (controller.IsPressed("Insert Coin P1"))
VS_coin_inserted |= 1;
else
VS_coin_inserted &= 2;
if (controller.IsPressed("Insert Coin P2"))
VS_coin_inserted |= 2;
else
VS_coin_inserted &= 1;
}
if (ppu.ppudead > 0)
{
while (ppu.ppudead > 0)
{
ppu.NewDeadPPU();
}
}
else
{
// do the vbl ticks seperate, that will save us a few checks that don't happen in active region
while (ppu.do_vbl)
{
ppu.TickPPU_VBL();
}
// now do the rest of the frame
while (ppu.do_active_sl)
{
ppu.TickPPU_active();
}
// now do the pre-NMI lines
while (ppu.do_pre_vbl)
{
ppu.TickPPU_preVBL();
}
}
if (lagged)
{
_lagcount++;
islag = true;
}
else
islag = false;
videoProvider.FillFrameBuffer();
// turn off all cheats
// any cheats still active will be re-applied by the buspoke at the start of the next frame
num_cheats = 0;
return true;
}
// these variables are for subframe input control
public bool controller_was_latched;
public bool frame_is_done;
public bool current_strobe;
public bool new_strobe;
public bool alt_lag;
// variable used with subneshawk to trigger reset at specific cycle after reset
public bool using_reset_timing = false;
// this function will run one step of the ppu
// it will return whether the controller is read or not.
public void do_single_step(IController controller, out bool cont_read, out bool frame_done)
{
_controller = controller;
controller_was_latched = false;
frame_is_done = false;
current_strobe = new_strobe;
if (ppu.ppudead > 0)
{
ppu.NewDeadPPU();
}
else if (ppu.do_vbl)
{
ppu.TickPPU_VBL();
}
else if (ppu.do_active_sl)
{
ppu.TickPPU_active();
}
else if (ppu.do_pre_vbl)
{
ppu.TickPPU_preVBL();
}
cont_read = controller_was_latched;
frame_done = frame_is_done;
}
//PAL:
//sequence of ppu clocks per cpu clock: 3,3,3,3,4
//at least it should be, but something is off with that (start up time?) so it is 3,3,3,4,3 for now
//NTSC:
//sequence of ppu clocks per cpu clock: 3
public ByteBuffer cpu_sequence;
static ByteBuffer cpu_sequence_NTSC = new ByteBuffer(new byte[] { 3, 3, 3, 3, 3 });
static ByteBuffer cpu_sequence_PAL = new ByteBuffer(new byte[] { 3, 3, 3, 4, 3 });
public int cpu_deadcounter;
public int oam_dma_index;
public bool oam_dma_exec = false;
public ushort oam_dma_addr;
public byte oam_dma_byte;
public bool dmc_dma_exec = false;
public bool dmc_realign;
public bool IRQ_delay;
public bool special_case_delay; // very ugly but the only option
public bool do_the_reread;
public byte DB; //old data bus values from previous reads
internal void RunCpuOne()
{
///////////////////////////
// OAM DMA start
///////////////////////////
if (sprdma_countdown > 0)
{
sprdma_countdown--;
if (sprdma_countdown == 0)
{
if (cpu.TotalExecutedCycles % 2 == 0)
{
cpu_deadcounter = 2;
}
else
{
cpu_deadcounter = 1;
}
oam_dma_exec = true;
cpu.RDY = false;
oam_dma_index = 0;
special_case_delay = true;
}
}
if (oam_dma_exec && apu.dmc_dma_countdown != 1 && !dmc_realign)
{
if (cpu_deadcounter == 0)
{
if (oam_dma_index % 2 == 0)
{
oam_dma_byte = ReadMemory(oam_dma_addr);
oam_dma_addr++;
}
else
{
WriteMemory(0x2004, oam_dma_byte);
}
oam_dma_index++;
if (oam_dma_index == 512) oam_dma_exec = false;
}
else
{
cpu_deadcounter--;
}
}
else if (apu.dmc_dma_countdown == 1)
{
dmc_realign = true;
}
else if (dmc_realign)
{
dmc_realign = false;
}
/////////////////////////////
// OAM DMA end
/////////////////////////////
/////////////////////////////
// dmc dma start
/////////////////////////////
if (apu.dmc_dma_countdown > 0)
{
cpu.RDY = false;
dmc_dma_exec = true;
apu.dmc_dma_countdown--;
if (apu.dmc_dma_countdown == 0)
{
apu.RunDMCFetch();
dmc_dma_exec = false;
apu.dmc_dma_countdown = -1;
do_the_reread = true;
}
}
/////////////////////////////
// dmc dma end
/////////////////////////////
apu.RunOneFirst();
if (cpu.RDY && !IRQ_delay)
{
cpu.IRQ = _irq_apu || Board.IRQSignal;
}
else if (special_case_delay || apu.dmc_dma_countdown == 3)
{
cpu.IRQ = _irq_apu || Board.IRQSignal;
special_case_delay = false;
}
cpu.ExecuteOne();
Board.ClockCPU();
int s = apu.EmitSample();
if (s != old_s)
{
blip.AddDelta(apu.sampleclock, s - old_s);
old_s = s;
}
apu.sampleclock++;
apu.RunOneLast();
if (ppu.double_2007_read > 0)
ppu.double_2007_read--;
if (do_the_reread && cpu.RDY)
do_the_reread = false;
if (IRQ_delay)
IRQ_delay = false;
if (!dmc_dma_exec && !oam_dma_exec && !cpu.RDY)
{
cpu.RDY = true;
IRQ_delay = true;
}
}
public byte ReadReg(int addr)
{
byte ret_spec;
switch (addr)
{
case 0x4000:
case 0x4001:
case 0x4002:
case 0x4003:
case 0x4004:
case 0x4005:
case 0x4006:
case 0x4007:
case 0x4008:
case 0x4009:
case 0x400A:
case 0x400B:
case 0x400C:
case 0x400D:
case 0x400E:
case 0x400F:
case 0x4010:
case 0x4011:
case 0x4012:
case 0x4013:
return DB;
//return apu.ReadReg(addr);
case 0x4014: /*OAM DMA*/ break;
case 0x4015: return (byte)((byte)(apu.ReadReg(addr) & 0xDF) + (byte)(DB & 0x20));
case 0x4016:
if (_isVS)
{
byte ret = 0;
ret = read_joyport(0x4016);
ret &= 1;
ret = (byte)(ret | (VS_service << 2) | (VS_dips[0] << 3) | (VS_dips[1] << 4) | (VS_coin_inserted << 5) | (VS_ROM_control<<7));
return ret;
}
else
{
// special hardware glitch case
ret_spec = read_joyport(addr);
if (do_the_reread && ppu.region==PPU.Region.NTSC)
{
ret_spec = read_joyport(addr);
do_the_reread = false;
}
return ret_spec;
}
case 0x4017:
if (_isVS)
{
byte ret = 0;
ret = read_joyport(0x4017);
ret &= 1;
ret = (byte)(ret | (VS_dips[2] << 2) | (VS_dips[3] << 3) | (VS_dips[4] << 4) | (VS_dips[5] << 5) | (VS_dips[6] << 6) | (VS_dips[7] << 7));
return ret;
}
else
{
// special hardware glitch case
ret_spec = read_joyport(addr);
if (do_the_reread && ppu.region == PPU.Region.NTSC)
{
ret_spec = read_joyport(addr);
do_the_reread = false;
}
return ret_spec;
}
default:
//Console.WriteLine("read register: {0:x4}", addr);
break;
}
return DB;
}
public byte PeekReg(int addr)
{
switch (addr)
{
case 0x4000:
case 0x4001:
case 0x4002:
case 0x4003:
case 0x4004:
case 0x4005:
case 0x4006:
case 0x4007:
case 0x4008:
case 0x4009:
case 0x400A:
case 0x400B:
case 0x400C:
case 0x400D:
case 0x400E:
case 0x400F:
case 0x4010:
case 0x4011:
case 0x4012:
case 0x4013:
return apu.PeekReg(addr);
case 0x4014: /*OAM DMA*/ break;
case 0x4015: return apu.PeekReg(addr);
case 0x4016:
case 0x4017:
return peek_joyport(addr);
default:
//Console.WriteLine("read register: {0:x4}", addr);
break;
}
return 0xFF;
}
void WriteReg(int addr, byte val)
{
switch (addr)
{
case 0x4000:
case 0x4001:
case 0x4002:
case 0x4003:
case 0x4004:
case 0x4005:
case 0x4006:
case 0x4007:
case 0x4008:
case 0x4009:
case 0x400A:
case 0x400B:
case 0x400C:
case 0x400D:
case 0x400E:
case 0x400F:
case 0x4010:
case 0x4011:
case 0x4012:
case 0x4013:
apu.WriteReg(addr, val);
break;
case 0x4014:
//schedule a sprite dma event for beginning 1 cycle in the future.
//this receives 2 because thats just the way it works out.
oam_dma_addr = (ushort)(val << 8);
sprdma_countdown = 1;
break;
case 0x4015: apu.WriteReg(addr, val); break;
case 0x4016:
if (_isVS)
{
write_joyport(val);
VS_chr_reg = (byte)((val & 0x4)>>2);
//TODO: does other stuff for dual system
//this is actually different then assignment
VS_prg_reg = (byte)((val & 0x4)>>2);
}
else
{
write_joyport(val);
}
break;
case 0x4017: apu.WriteReg(addr, val); break;
default:
//Console.WriteLine("wrote register: {0:x4} = {1:x2}", addr, val);
break;
}
}
void write_joyport(byte value)
{
var si = new StrobeInfo(latched4016, value);
ControllerDeck.Strobe(si, _controller);
latched4016 = value;
new_strobe = (value & 1) > 0;
if (current_strobe && !new_strobe)
{
controller_was_latched = true;
alt_lag = false;
}
}
byte read_joyport(int addr)
{
InputCallbacks.Call();
lagged = false;
byte ret = 0;
if (_isVS)
{
// for whatever reason, in VS left and right controller have swapped regs
ret = addr == 0x4017 ? ControllerDeck.ReadA(_controller) : ControllerDeck.ReadB(_controller);
}
else
{
ret = addr == 0x4016 ? ControllerDeck.ReadA(_controller) : ControllerDeck.ReadB(_controller);
}
ret &= 0x1f;
ret |= (byte)(0xe0 & DB);
return ret;
}
byte peek_joyport(int addr)
{
// at the moment, the new system doesn't support peeks
return 0;
}
/// <summary>
/// Sets the provided palette as current.
/// Applies the current deemph settings if needed to expand a 64-entry palette to 512
/// </summary>
public void SetPalette(byte[,] pal)
{
int nColors = pal.GetLength(0);
int nElems = pal.GetLength(1);
if (nColors == 512)
{
//just copy the palette directly
for (int c = 0; c < 64 * 8; c++)
{
int r = pal[c, 0];
int g = pal[c, 1];
int b = pal[c, 2];
palette_compiled[c] = (int)unchecked((int)0xFF000000 | (r << 16) | (g << 8) | b);
}
}
else
{
//expand using deemph
for (int i = 0; i < 64 * 8; i++)
{
int d = i >> 6;
int c = i & 63;
int r = pal[c, 0];
int g = pal[c, 1];
int b = pal[c, 2];
Palettes.ApplyDeemphasis(ref r, ref g, ref b, d);
palette_compiled[i] = (int)unchecked((int)0xFF000000 | (r << 16) | (g << 8) | b);
}
}
}
/// <summary>
/// looks up an internal NES pixel value to an rgb int (applying the core's current palette and assuming no deemph)
/// </summary>
public int LookupColor(int pixel)
{
return palette_compiled[pixel];
}
public byte DummyReadMemory(ushort addr) { return 0; }
public void ApplySystemBusPoke(int addr, byte value)
{
if (addr < 0x2000)
{
ram[(addr & 0x7FF)] = value;
}
else if (addr < 0x4000)
{
ppu.WriteReg(addr, value);
}
else if (addr < 0x4020)
{
WriteReg(addr, value);
}
else
{
// apply a cheat to non-writable memory
ApplyCheat(addr, value, null);
}
}
public byte PeekMemory(ushort addr)
{
byte ret;
if (addr >= 0x4020)
{
//easy optimization, since rom reads are so common, move this up (reordering the rest of these elseifs is not easy)
ret = Board.PeekCart(addr);
}
else if (addr < 0x0800)
{
ret = ram[addr];
}
else if (addr < 0x2000)
{
ret = ram[addr & 0x7FF];
}
else if (addr < 0x4000)
{
ret = Board.PeekReg2xxx(addr);
}
else if (addr < 0x4020)
{
ret = PeekReg(addr); //we're not rebasing the register just to keep register names canonical
}
else
{
throw new Exception("Woopsie-doodle!");
ret = 0xFF;
}
return ret;
}
public void ExecFetch(ushort addr)
{
uint flags = (uint)(MemoryCallbackFlags.CPUZero | MemoryCallbackFlags.AccessExecute);
MemoryCallbacks.CallMemoryCallbacks(addr, 0, flags, "System Bus");
}
public byte ReadMemory(ushort addr)
{
byte ret;
if (addr >= 0x8000)
{
//easy optimization, since rom reads are so common, move this up (reordering the rest of these elseifs is not easy)
ret = Board.ReadPRG(addr - 0x8000);
}
else if (addr < 0x0800)
{
ret = ram[addr];
}
else if (addr < 0x2000)
{
ret = ram[addr & 0x7FF];
}
else if (addr < 0x4000)
{
ret = Board.ReadReg2xxx(addr);
}
else if (addr < 0x4020)
{
ret = ReadReg(addr); //we're not rebasing the register just to keep register names canonical
}
else if (addr < 0x6000)
{
ret = Board.ReadEXP(addr - 0x4000);
}
else
{
ret = Board.ReadWRAM(addr - 0x6000);
}
// handle cheats (currently cheats can only freeze read only areas)
// there is no way to distinguish between a memory poke and a memory freeze
if (num_cheats !=0)
{
for (int i = 0; i < num_cheats; i++)
{
if(cheat_indexes[i] == addr)
{
ret = cheat_active[addr];
}
}
}
uint flags = (uint)(MemoryCallbackFlags.CPUZero | MemoryCallbackFlags.AccessRead);
MemoryCallbacks.CallMemoryCallbacks(addr, ret, flags, "System Bus");
DB = ret;
return ret;
}
public void ApplyCheat(int addr, byte value, byte? compare)
{
if (addr <= 0xFFFF)
{
cheat_indexes[num_cheats] = addr;
cheat_active[addr] = value;
num_cheats++;
}
}
public void WriteMemory(ushort addr, byte value)
{
if (addr < 0x0800)
{
ram[addr] = value;
}
else if (addr < 0x2000)
{
ram[addr & 0x7FF] = value;
}
else if (addr < 0x4000)
{
Board.WriteReg2xxx(addr, value);
}
else if (addr < 0x4020)
{
WriteReg(addr, value); //we're not rebasing the register just to keep register names canonical
}
else if (addr < 0x6000)
{
Board.WriteEXP(addr - 0x4000, value);
}
else if (addr < 0x8000)
{
Board.WriteWRAM(addr - 0x6000, value);
}
else
{
Board.WritePRG(addr - 0x8000, value);
}
uint flags = (uint)(MemoryCallbackFlags.CPUZero | MemoryCallbackFlags.AccessWrite | MemoryCallbackFlags.SizeByte);
MemoryCallbacks.CallMemoryCallbacks(addr, value, flags, "System Bus");
}
// the palette for each VS game needs to be chosen explicitly since there are 6 different ones.
public void PickVSPalette(CartInfo cart)
{
switch (cart.palette)
{
case "2C05": SetPalette(Palettes.palette_2c03_2c05); ppu.CurrentLuma = PPU.PaletteLuma2C03; break;
case "2C04-1": SetPalette(Palettes.palette_2c04_001); ppu.CurrentLuma = PPU.PaletteLuma2C04_1; break;
case "2C04-2": SetPalette(Palettes.palette_2c04_002); ppu.CurrentLuma = PPU.PaletteLuma2C04_2; break;
case "2C04-3": SetPalette(Palettes.palette_2c04_003); ppu.CurrentLuma = PPU.PaletteLuma2C04_3; break;
case "2C04-4": SetPalette(Palettes.palette_2c04_004); ppu.CurrentLuma = PPU.PaletteLuma2C04_4; break;
}
//since this will run for every VS game, let's get security setting too
//values below 16 are for the 2c05 PPU
//values 16,32,48 are for Namco games and dealt with in mapper 206
_isVS2c05 = (byte)(cart.vs_security & 15);
}
}
}
| |
#region license
// Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
//
// DO NOT EDIT THIS FILE!
//
// This file was generated automatically by astgen.boo.
//
namespace Boo.Lang.Compiler.Ast
{
using System.Collections;
using System.Runtime.Serialization;
[System.Serializable]
public partial class TryStatement : Statement
{
protected Block _protectedBlock;
protected ExceptionHandlerCollection _exceptionHandlers;
protected Block _failureBlock;
protected Block _ensureBlock;
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public TryStatement CloneNode()
{
return (TryStatement)Clone();
}
/// <summary>
/// <see cref="Node.CleanClone"/>
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public TryStatement CleanClone()
{
return (TryStatement)base.CleanClone();
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public NodeType NodeType
{
get { return NodeType.TryStatement; }
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public void Accept(IAstVisitor visitor)
{
visitor.OnTryStatement(this);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Matches(Node node)
{
if (node == null) return false;
if (NodeType != node.NodeType) return false;
var other = ( TryStatement)node;
if (!Node.Matches(_modifier, other._modifier)) return NoMatch("TryStatement._modifier");
if (!Node.Matches(_protectedBlock, other._protectedBlock)) return NoMatch("TryStatement._protectedBlock");
if (!Node.AllMatch(_exceptionHandlers, other._exceptionHandlers)) return NoMatch("TryStatement._exceptionHandlers");
if (!Node.Matches(_failureBlock, other._failureBlock)) return NoMatch("TryStatement._failureBlock");
if (!Node.Matches(_ensureBlock, other._ensureBlock)) return NoMatch("TryStatement._ensureBlock");
return true;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Replace(Node existing, Node newNode)
{
if (base.Replace(existing, newNode))
{
return true;
}
if (_modifier == existing)
{
this.Modifier = (StatementModifier)newNode;
return true;
}
if (_protectedBlock == existing)
{
this.ProtectedBlock = (Block)newNode;
return true;
}
if (_exceptionHandlers != null)
{
ExceptionHandler item = existing as ExceptionHandler;
if (null != item)
{
ExceptionHandler newItem = (ExceptionHandler)newNode;
if (_exceptionHandlers.Replace(item, newItem))
{
return true;
}
}
}
if (_failureBlock == existing)
{
this.FailureBlock = (Block)newNode;
return true;
}
if (_ensureBlock == existing)
{
this.EnsureBlock = (Block)newNode;
return true;
}
return false;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public object Clone()
{
TryStatement clone = (TryStatement)FormatterServices.GetUninitializedObject(typeof(TryStatement));
clone._lexicalInfo = _lexicalInfo;
clone._endSourceLocation = _endSourceLocation;
clone._documentation = _documentation;
clone._isSynthetic = _isSynthetic;
clone._entity = _entity;
if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone();
if (null != _modifier)
{
clone._modifier = _modifier.Clone() as StatementModifier;
clone._modifier.InitializeParent(clone);
}
if (null != _protectedBlock)
{
clone._protectedBlock = _protectedBlock.Clone() as Block;
clone._protectedBlock.InitializeParent(clone);
}
if (null != _exceptionHandlers)
{
clone._exceptionHandlers = _exceptionHandlers.Clone() as ExceptionHandlerCollection;
clone._exceptionHandlers.InitializeParent(clone);
}
if (null != _failureBlock)
{
clone._failureBlock = _failureBlock.Clone() as Block;
clone._failureBlock.InitializeParent(clone);
}
if (null != _ensureBlock)
{
clone._ensureBlock = _ensureBlock.Clone() as Block;
clone._ensureBlock.InitializeParent(clone);
}
return clone;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override internal void ClearTypeSystemBindings()
{
_annotations = null;
_entity = null;
if (null != _modifier)
{
_modifier.ClearTypeSystemBindings();
}
if (null != _protectedBlock)
{
_protectedBlock.ClearTypeSystemBindings();
}
if (null != _exceptionHandlers)
{
_exceptionHandlers.ClearTypeSystemBindings();
}
if (null != _failureBlock)
{
_failureBlock.ClearTypeSystemBindings();
}
if (null != _ensureBlock)
{
_ensureBlock.ClearTypeSystemBindings();
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public Block ProtectedBlock
{
get
{
if (_protectedBlock == null)
{
_protectedBlock = new Block();
_protectedBlock.InitializeParent(this);
}
return _protectedBlock;
}
set
{
if (_protectedBlock != value)
{
_protectedBlock = value;
if (null != _protectedBlock)
{
_protectedBlock.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlArray]
[System.Xml.Serialization.XmlArrayItem(typeof(ExceptionHandler))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public ExceptionHandlerCollection ExceptionHandlers
{
get { return _exceptionHandlers ?? (_exceptionHandlers = new ExceptionHandlerCollection(this)); }
set
{
if (_exceptionHandlers != value)
{
_exceptionHandlers = value;
if (null != _exceptionHandlers)
{
_exceptionHandlers.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public Block FailureBlock
{
get { return _failureBlock; }
set
{
if (_failureBlock != value)
{
_failureBlock = value;
if (null != _failureBlock)
{
_failureBlock.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public Block EnsureBlock
{
get { return _ensureBlock; }
set
{
if (_ensureBlock != value)
{
_ensureBlock = value;
if (null != _ensureBlock)
{
_ensureBlock.InitializeParent(this);
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Ploeh.AutoFixture.Kernel
{
/// <summary>
/// Selects public static methods that has the same parameters of another method,
/// ignoring optional parameters and return type.
/// </summary>
/// <remarks>
/// <para>
/// The main target of this <see cref="IMethodQuery" /> implementation is to be able to
/// late bind to a method even if it has optional parameters added to it.
/// </para>
/// <para>
/// The order of the methods are based on the match of parameters types of both methods,
/// favoring the method with exactly same parameters to be returned first.
/// </para>
/// </remarks>
public class TemplateMethodQuery : IMethodQuery
{
private readonly MethodInfo template;
private readonly object owner;
/// <summary>
/// Initializes a new instance of the <see cref="TemplateMethodQuery"/> class.
/// </summary>
/// <param name="template">The method info to compare.</param>
public TemplateMethodQuery(MethodInfo template)
{
if (template == null)
throw new ArgumentNullException("template");
this.template = template;
}
/// <summary>
/// Initializes a new instance of the <see cref="TemplateMethodQuery"/> class.
/// </summary>
/// <param name="template">The method info to compare.</param>
/// <param name="owner">The owner.</param>
public TemplateMethodQuery(MethodInfo template, object owner)
{
if (template == null)
throw new ArgumentNullException("template");
if (owner == null)
throw new ArgumentNullException("owner");
this.owner = owner;
this.template = template;
}
/// <summary>
/// The template <see cref="MethodInfo" /> to compare.
/// </summary>
public MethodInfo Template
{
get { return template; }
}
/// <summary>
/// The owner instance of the <see cref="MethodInfo" />.
/// </summary>
public object Owner
{
get { return owner; }
}
/// <summary>
/// Selects the methods for the supplied type similar to <see cref="Template" />.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>
/// All public static methods for <paramref name="type"/>, ordered by the most similar first.
/// </returns>
/// <remarks>
/// <para>
/// The ordering of the returned methods is based on a score that matches the parameters types
/// of the method with the <see cref="Template" /> method parameters. Methods with the highest score
/// are returned before.
/// </para>
/// <para>
/// The score is calculated with the following rules: The methods earns 100 points for each exact
/// match parameter type, it loses 50 points for each hierarchy level down of non-matching parameter
/// type and it loses 1 point for each optional parameter. It also sums the score for the generic type
/// arguments or element type with a 10% weight and will decrease 50 points for the difference between
/// the length of the type arguments array. It also gives 5 points if the type is a class instead of
/// an interface.
/// </para>
/// <para>
/// In case of two methods with an equal score, the ordering is unspecified.
/// </para>
/// </remarks>
public IEnumerable<IMethod> SelectMethods(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
return from method in type.GetMethods()
where method.Name == Template.Name && (Owner != null || method.IsStatic)
let methodParameters = method.GetParameters()
let templateParameters = Template.GetParameters()
where methodParameters.Length >= templateParameters.Length
let score = new LateBindingParameterScore(methodParameters, templateParameters)
orderby score descending
where methodParameters.All(p =>
p.Position >= templateParameters.Length ?
p.IsOptional || p.IsDefined(typeof(ParamArrayAttribute), true) :
Compare(p.ParameterType, templateParameters[p.Position].ParameterType))
select new GenericMethod(method, GetMethodFactory(method));
}
private IMethodFactory GetMethodFactory(MethodInfo method)
{
if (method.IsStatic)
return new MissingParametersSupplyingStaticMethodFactory();
return new MissingParametersSupplyingMethodFactory(Owner);
}
private bool Compare(Type parameterType, Type templateParameterType)
{
if (parameterType.IsAssignableFrom(templateParameterType))
return true;
if (parameterType.IsGenericParameter)
return templateParameterType.IsGenericParameter
&& parameterType.GenericParameterPosition == templateParameterType.GenericParameterPosition;
var genericArguments = GetTypeArguments(parameterType);
var templateGenericArguments = GetTypeArguments(templateParameterType);
if (genericArguments.Length == 0 || genericArguments.Length != templateGenericArguments.Length)
return false;
return genericArguments.Zip(templateGenericArguments, Compare).All(x => x);
}
private static Type[] GetTypeArguments(Type type)
{
return type.HasElementType ?
new[] { type.GetElementType() } :
type.GetGenericArguments();
}
private class LateBindingParameterScore : IComparable<LateBindingParameterScore>
{
private readonly int score;
internal LateBindingParameterScore(IEnumerable<ParameterInfo> methodParameters,
IEnumerable<ParameterInfo> templateParameters)
{
if (methodParameters == null)
throw new ArgumentNullException("methodParameters");
if (templateParameters == null)
throw new ArgumentNullException("templateParameters");
this.score = CalculateScore(methodParameters.Select(p => p.ParameterType),
templateParameters.Select(p => p.ParameterType));
}
public int CompareTo(LateBindingParameterScore other)
{
if (other == null)
return 1;
return this.score.CompareTo(other.score);
}
private static int CalculateScore(IEnumerable<Type> methodParameters,
IEnumerable<Type> templateParameters)
{
var parametersScore = templateParameters.Zip(methodParameters,
(s, m) => CalculateScore(m, s))
.Sum();
var additionalParameters = methodParameters.Count() - templateParameters.Count();
return parametersScore - additionalParameters;
}
private static int CalculateScore(Type methodParameterType, Type templateParameterType)
{
if (methodParameterType == templateParameterType)
return 100;
var hierarchy = GetHierarchy(templateParameterType).ToList();
var matches = methodParameterType.IsClass ?
hierarchy.Count(t => t.IsAssignableFrom(methodParameterType)) :
hierarchy.Count(t => t.GetInterfaces().Any(i => i.IsAssignableFrom(methodParameterType)));
var score = 50 * -(hierarchy.Count - matches);
var methodTypeArguments = GetTypeArguments(methodParameterType);
var templateTypeArguments = GetTypeArguments(templateParameterType);
score += CalculateScore(methodTypeArguments, templateTypeArguments) / 10;
score += 50 * -Math.Abs(methodTypeArguments.Length - templateTypeArguments.Length);
if (methodParameterType.IsClass)
score += 5;
return score;
}
private static IEnumerable<Type> GetHierarchy(Type type)
{
if (!type.IsClass)
foreach (var interfaceType in type.GetInterfaces())
yield return interfaceType;
while (type != null)
{
yield return type;
type = type.BaseType;
}
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Game1.cs
//
// Microsoft Advanced Technology Group
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Device.Location;
using System.IO;
using System.IO.IsolatedStorage;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
namespace Geolocation
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class SampleGame : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
SpriteFont spriteFont;
// Use this class to access Windows Phone location service
GeoCoordinateWatcher geoWatcher;
// Current status of the location service
GeoPositionStatus currentState = GeoPositionStatus.Initializing;
// Text boxes for displaying current and saved geo-location information
TextBox textCurrentGeoLocation;
TextBox textSavedGeoLocation;
// Buttons at the bottom of the screen
Button buttonSaveLocation;
Button buttonToggleNorthUp;
// List of all UI Elements, which facilitates calling .HandleTouch() and .Draw() on the UI elements
List<UIElement> uiElementList = new List<UIElement>();
// Textures for displaying the direction compass on screen
Texture2D texCircle;
Texture2D texArrow;
Texture2D texSpot;
// Isostorage is used to maintain the saved geo-location across app sessions
IsolatedStorageFile isoStore;
const string strDataFile = "data.bin";
// dDistance is the distance between your current location and saved location
double distance = 0;
// dBearing is in what direction the saved location is related to your current location
double bearing = 0;
// Current geo-location
private GeoPosition<GeoCoordinate> currentGeoCoord = null;
private int timesRecieved = 0;
GeoPosition<GeoCoordinate> CurrentGeoCoord
{
get
{
return currentGeoCoord;
}
set
{
currentGeoCoord = value;
if (value != null)
{
++timesRecieved;
textCurrentGeoLocation.Text = "Current location status:\n" + GeoPosToText(currentGeoCoord);
textCurrentGeoLocation.WriteLn(string.Format("Times recieved: {0}", timesRecieved));
}
}
}
// Saved geo-location (which is the current location when you touch textMenuSaveLocation)
private GeoPosition<GeoCoordinate> savedGeoCoord = null;
GeoPosition<GeoCoordinate> SavedGeoCoord
{
get
{
return savedGeoCoord;
}
set
{
savedGeoCoord = value;
if (value != null)
textSavedGeoLocation.Text = "Saved location status:\n" + GeoPosToText(savedGeoCoord);
}
}
/// <summary>
/// Converts geo-location to display friendly string
/// </summary>
static string GeoPosToText( GeoPosition<GeoCoordinate> geoPos )
{
return string.Format("Time: {0}\n" +
"Pos (Latitude, Longitude, Altitude):\n" +
" {1:0.0000}, {2:0.0000}, {3:0.00}\n" +
"Speed: {4:0.000}m/s\n" +
"Course: {5:0.0}, {8}\n" +
"HorizontalAccuracy: {6}m\n" +
"VerticalAccuracy: {7}m\n",
geoPos.Timestamp.ToString(),
geoPos.Location.Latitude, geoPos.Location.Longitude, geoPos.Location.Altitude,
geoPos.Location.Speed,
geoPos.Location.Course,
geoPos.Location.HorizontalAccuracy,
geoPos.Location.VerticalAccuracy,
BearingToStr(geoPos.Location.Course)
);
}
/// <summary>
/// Converts degree angle to radian
/// </summary>
static double DegreeToRadian(double angle)
{
return (angle / 180.0) * Math.PI;
}
/// <summary>
/// Converts radian angle to degree
/// </summary>
static double RadianToDegree(double radian)
{
return (radian / Math.PI) * 180.0;
}
/// <summary>
/// Caculates in what direction the dst location is related to src location, which is called Initial Bearing
/// </summary>
/// <param name="source">Source geo-location</param>
/// <param name="destination">Destination geo-location</param>
/// <returns>Initial Bearing in degrees</returns>
static double InitialBearing(GeoCoordinate source, GeoCoordinate destination)
{
var lat1 = DegreeToRadian(source.Latitude);
var lat2 = DegreeToRadian(destination.Latitude);
var dLon = DegreeToRadian(destination.Longitude - source.Longitude);
var y = Math.Sin(dLon) * Math.Cos(lat2);
var x = Math.Cos(lat1) * Math.Sin(lat2) -
Math.Sin(lat1) * Math.Cos(lat2) * Math.Cos(dLon);
var brng = Math.Atan2(y, x);
return (RadianToDegree(brng) + 360) % 360;
}
/// <summary>
/// Converts bearing (or course) to display friendly directions N, E, S or W
/// </summary>
static string BearingToStr(double course)
{
if (double.IsNaN(course))
return string.Empty;
if ((course >= 0 && course < 45) || (course >= 315 && course < 360))
return "N";
else
if (course >= 45 && course < 135)
return "E";
else
if (course >= 135 && course < 225)
return "S";
else
//if (course >= 225 && course < 315)
return "W";
}
public SampleGame()
{
graphics = new GraphicsDeviceManager(this);
graphics.IsFullScreen = true;
Content.RootDirectory = "Content";
// Frame rate is 30 fps by default for Windows Phone.
TargetElapsedTime = TimeSpan.FromTicks(333333);
// Pre-autoscale settings.
graphics.PreferredBackBufferWidth = 480;
graphics.PreferredBackBufferHeight = 800;
isoStore = IsolatedStorageFile.GetUserStoreForApplication();
// Request high precision location service and start the service
geoWatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
geoWatcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(geoWatcher_StatusChanged);
geoWatcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(geoWatcher_PositionChanged);
geoWatcher.MovementThreshold = 0.5;
geoWatcher.Start();
}
void buttonToggleNorthUp_OnClick(object sender)
{
if (buttonToggleNorthUp.Text == "Toggle: North up")
buttonToggleNorthUp.Text = "Toggle: Your dir up";
else
buttonToggleNorthUp.Text = "Toggle: North up";
}
void buttonSaveLocation_OnClick(object sender)
{
SavedGeoCoord = geoWatcher.Position;
}
void ExitGame(IAsyncResult result)
{
Exit();
}
void geoWatcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
{
currentState = e.Status;
switch (e.Status)
{
case GeoPositionStatus.Disabled:
if (geoWatcher.Permission == GeoPositionPermission.Denied)
{
string[] strings = { "ok" };
Guide.BeginShowMessageBox("Info", "Please turn on geo-location service in the settings tab.", strings, 0, 0, ExitGame, null);
}
else
if (geoWatcher.Permission == GeoPositionPermission.Granted)
{
string[] strings = { "ok" };
Guide.BeginShowMessageBox("Error", "Your device doesn't support geo-location service.", strings, 0, 0, ExitGame, null);
}
break;
case GeoPositionStatus.Ready:
CurrentGeoCoord = geoWatcher.Position;
break;
}
}
void geoWatcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
if (currentState == GeoPositionStatus.Ready)
CurrentGeoCoord = e.Position;
}
protected override void OnActivated(object sender, EventArgs args)
{
// When our app gains focus, load the saved geo location
GeoPosition<GeoCoordinate> temp;
LoadFromIsoStore(strDataFile, out temp);
SavedGeoCoord = temp;
base.OnActivated(sender, args);
}
protected override void OnDeactivated(object sender, EventArgs args)
{
// When our app loses focus, save our "saved geo location"
SaveToIsoStore(strDataFile, SavedGeoCoord);
base.OnDeactivated(sender, args);
}
/// <summary>
/// Write geo location to isolated storage in binary format using the specified filename
/// </summary>
private void SaveToIsoStore(string filename, GeoPosition<GeoCoordinate> posToSave )
{
if (posToSave == null)
return;
string strBaseDir = string.Empty;
string delimStr = "/";
char[] delimiter = delimStr.ToCharArray();
string[] dirsPath = filename.Split(delimiter);
// Recreate the directory structure
for (int i = 0; i < dirsPath.Length - 1; i++)
{
strBaseDir = System.IO.Path.Combine(strBaseDir, dirsPath[i]);
isoStore.CreateDirectory(strBaseDir);
}
// Remove existing file
if (isoStore.FileExists(filename))
{
isoStore.DeleteFile(filename);
}
// Write the file
using (BinaryWriter bw = new BinaryWriter(isoStore.CreateFile(filename)))
{
bw.Write(posToSave.Timestamp.Ticks);
bw.Write(posToSave.Timestamp.Offset.Ticks);
bw.Write(posToSave.Location.Latitude);
bw.Write(posToSave.Location.Longitude);
bw.Write(posToSave.Location.Altitude);
bw.Write(posToSave.Location.HorizontalAccuracy);
bw.Write(posToSave.Location.VerticalAccuracy);
bw.Write(posToSave.Location.Speed);
bw.Write(posToSave.Location.Course);
bw.Close();
}
}
/// <summary>
/// Load geo location from isolated storage
/// </summary>
private void LoadFromIsoStore(string filename, out GeoPosition<GeoCoordinate> posToLoad)
{
posToLoad = null;
if (isoStore.FileExists(filename))
{
using (BinaryReader br = new BinaryReader(isoStore.OpenFile(filename, FileMode.Open)))
{
// Reconstruct the geo-location class using data read from the data file in isostore
if (br.BaseStream.Length == 0)
return;
long timestampTicks = br.ReadInt64();
long timestampOffsetTicks = br.ReadInt64();
TimeSpan ts = new TimeSpan(timestampOffsetTicks);
DateTimeOffset dto = new DateTimeOffset(timestampTicks, ts);
double latitude = br.ReadDouble();
double longitude = br.ReadDouble();
double altitude = br.ReadDouble();
double horizontalAccuracy = br.ReadDouble();
double verticalAccuracy = br.ReadDouble();
double speed = br.ReadDouble();
double course = br.ReadDouble();
GeoCoordinate gc = new GeoCoordinate(latitude, longitude, altitude, horizontalAccuracy, verticalAccuracy, speed, course);
posToLoad = new GeoPosition<GeoCoordinate>(dto, gc);
}
}
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
spriteFont = Content.Load<SpriteFont>("Font");
// TODO: use this.Content to load your game content here
texCircle = Content.Load<Texture2D>("circle");
texArrow = Content.Load<Texture2D>("arrow");
texSpot = Content.Load<Texture2D>("spot");
textCurrentGeoLocation = new TextBox(spriteFont)
{
Position = new Vector2(0, 40),
IsVisible = true
};
uiElementList.Add(textCurrentGeoLocation);
textSavedGeoLocation = new TextBox(spriteFont)
{
Position = new Vector2(0, 270),
IsVisible = true
};
uiElementList.Add(textSavedGeoLocation);
buttonSaveLocation = new Button(GraphicsDevice, spriteFont, "Save location")
{
Position = new Vector2(0, graphics.PreferredBackBufferHeight - 31),
Size = new Vector2(154, 30),
IsVisible = true
};
buttonSaveLocation.OnClick += new Button.ClickEventHandler(buttonSaveLocation_OnClick);
uiElementList.Add(buttonSaveLocation);
buttonToggleNorthUp = new Button(GraphicsDevice, spriteFont, "Toggle: North up")
{
Position = new Vector2(graphics.PreferredBackBufferWidth - 175, graphics.PreferredBackBufferHeight - 31),
Size = new Vector2(174, 30),
IsVisible = true
};
buttonToggleNorthUp.OnClick += new Button.ClickEventHandler(buttonToggleNorthUp_OnClick);
uiElementList.Add(buttonToggleNorthUp);
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
TouchCollection touchCollection = TouchPanel.GetState();
for (int t = 0; t < touchCollection.Count; t++)
{
for (int b = 0; b < uiElementList.Count; b++)
{
uiElementList[b].HandleTouch(touchCollection[t]);
}
}
if (SavedGeoCoord != null && CurrentGeoCoord != null)
{
distance = CurrentGeoCoord.Location.GetDistanceTo(SavedGeoCoord.Location);
bearing = InitialBearing(CurrentGeoCoord.Location, SavedGeoCoord.Location);
}
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
spriteBatch.DrawString(spriteFont, currentState.ToString(), new Vector2(0, 0), Color.White);
if (SavedGeoCoord != null && CurrentGeoCoord != null)
{
spriteBatch.DrawString(spriteFont,
string.Format("Distance: {0:0.00}meters, {1:0.00}feet\n" +
"Speed: {2:0.00}meters/s, {3:0.00}km/h, {4:0.00}mph",
distance,
distance*3.2808399,
CurrentGeoCoord.Location.Speed,
CurrentGeoCoord.Location.Speed * 3.6,
CurrentGeoCoord.Location.Speed * 3.6 * 0.621371192),
new Vector2(0, 480), Color.White);
if (buttonToggleNorthUp.Text == "Toggle: North up")
{
// North up mode
spriteBatch.Draw(texCircle,
new Vector2((graphics.PreferredBackBufferWidth - texCircle.Width) / 2, graphics.PreferredBackBufferHeight - texCircle.Height - 10),
Color.White);
spriteBatch.Draw(texArrow, new Rectangle((graphics.PreferredBackBufferWidth) / 2, graphics.PreferredBackBufferHeight - texCircle.Height / 2 - 10, texCircle.Width, texCircle.Height),
null, Color.White,
(float)DegreeToRadian(CurrentGeoCoord.Location.Course), // Your current movement direction
new Vector2(128, 128), SpriteEffects.None, 0);
spriteBatch.Draw(texSpot, new Rectangle((graphics.PreferredBackBufferWidth) / 2, graphics.PreferredBackBufferHeight - texCircle.Height / 2 - 10, texCircle.Width, texCircle.Height),
null, Color.White,
(float)DegreeToRadian(bearing), // In what direction your saved location is related to your current location
new Vector2(128, 128), SpriteEffects.None, 0);
}
else
{
// Your direction up mode
// Every thing is the same as above except the all angles are being shifted by (-curGeoCoord.Location.Course),
// so that your movement direction is always pointing up
spriteBatch.Draw(texCircle, new Rectangle((graphics.PreferredBackBufferWidth) / 2, graphics.PreferredBackBufferHeight - texCircle.Height / 2 - 10, texCircle.Width, texCircle.Height),
null, Color.White,
-(float)DegreeToRadian(CurrentGeoCoord.Location.Course), new Vector2(128, 128), SpriteEffects.None, 0);
spriteBatch.Draw(texArrow, new Rectangle((graphics.PreferredBackBufferWidth) / 2, graphics.PreferredBackBufferHeight - texCircle.Height / 2 - 10, texCircle.Width, texCircle.Height),
null, Color.White,
0,
new Vector2(128, 128), SpriteEffects.None, 0);
spriteBatch.Draw(texSpot, new Rectangle((graphics.PreferredBackBufferWidth) / 2, graphics.PreferredBackBufferHeight - texCircle.Height / 2 - 10, texCircle.Width, texCircle.Height),
null, Color.White,
(float)DegreeToRadian(bearing)-(float)DegreeToRadian(CurrentGeoCoord.Location.Course),
new Vector2(128, 128), SpriteEffects.None, 0);
}
}
spriteBatch.End();
// Some ui elements combine 3D geometry with text so they can't render within a SpriteBatch.Begin/End section.
for (int b = 0; b < uiElementList.Count; b++)
{
uiElementList[b].Draw(spriteBatch);
}
base.Draw(gameTime);
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/spanner/v1/result_set.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 Google.Cloud.Spanner.V1 {
/// <summary>Holder for reflection information generated from google/spanner/v1/result_set.proto</summary>
public static partial class ResultSetReflection {
#region Descriptor
/// <summary>File descriptor for google/spanner/v1/result_set.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ResultSetReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiJnb29nbGUvc3Bhbm5lci92MS9yZXN1bHRfc2V0LnByb3RvEhFnb29nbGUu",
"c3Bhbm5lci52MRocZ29vZ2xlL2FwaS9hbm5vdGF0aW9ucy5wcm90bxocZ29v",
"Z2xlL3Byb3RvYnVmL3N0cnVjdC5wcm90bxoiZ29vZ2xlL3NwYW5uZXIvdjEv",
"cXVlcnlfcGxhbi5wcm90bxojZ29vZ2xlL3NwYW5uZXIvdjEvdHJhbnNhY3Rp",
"b24ucHJvdG8aHGdvb2dsZS9zcGFubmVyL3YxL3R5cGUucHJvdG8inwEKCVJl",
"c3VsdFNldBI2CghtZXRhZGF0YRgBIAEoCzIkLmdvb2dsZS5zcGFubmVyLnYx",
"LlJlc3VsdFNldE1ldGFkYXRhEigKBHJvd3MYAiADKAsyGi5nb29nbGUucHJv",
"dG9idWYuTGlzdFZhbHVlEjAKBXN0YXRzGAMgASgLMiEuZ29vZ2xlLnNwYW5u",
"ZXIudjEuUmVzdWx0U2V0U3RhdHMi0QEKEFBhcnRpYWxSZXN1bHRTZXQSNgoI",
"bWV0YWRhdGEYASABKAsyJC5nb29nbGUuc3Bhbm5lci52MS5SZXN1bHRTZXRN",
"ZXRhZGF0YRImCgZ2YWx1ZXMYAiADKAsyFi5nb29nbGUucHJvdG9idWYuVmFs",
"dWUSFQoNY2h1bmtlZF92YWx1ZRgDIAEoCBIUCgxyZXN1bWVfdG9rZW4YBCAB",
"KAwSMAoFc3RhdHMYBSABKAsyIS5nb29nbGUuc3Bhbm5lci52MS5SZXN1bHRT",
"ZXRTdGF0cyJ5ChFSZXN1bHRTZXRNZXRhZGF0YRIvCghyb3dfdHlwZRgBIAEo",
"CzIdLmdvb2dsZS5zcGFubmVyLnYxLlN0cnVjdFR5cGUSMwoLdHJhbnNhY3Rp",
"b24YAiABKAsyHi5nb29nbGUuc3Bhbm5lci52MS5UcmFuc2FjdGlvbiJwCg5S",
"ZXN1bHRTZXRTdGF0cxIwCgpxdWVyeV9wbGFuGAEgASgLMhwuZ29vZ2xlLnNw",
"YW5uZXIudjEuUXVlcnlQbGFuEiwKC3F1ZXJ5X3N0YXRzGAIgASgLMhcuZ29v",
"Z2xlLnByb3RvYnVmLlN0cnVjdEJ9ChVjb20uZ29vZ2xlLnNwYW5uZXIudjFC",
"DlJlc3VsdFNldFByb3RvUAFaOGdvb2dsZS5nb2xhbmcub3JnL2dlbnByb3Rv",
"L2dvb2dsZWFwaXMvc3Bhbm5lci92MTtzcGFubmVyqgIXR29vZ2xlLkNsb3Vk",
"LlNwYW5uZXIuVjFiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.StructReflection.Descriptor, global::Google.Cloud.Spanner.V1.QueryPlanReflection.Descriptor, global::Google.Cloud.Spanner.V1.TransactionReflection.Descriptor, global::Google.Cloud.Spanner.V1.TypeReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Spanner.V1.ResultSet), global::Google.Cloud.Spanner.V1.ResultSet.Parser, new[]{ "Metadata", "Rows", "Stats" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Spanner.V1.PartialResultSet), global::Google.Cloud.Spanner.V1.PartialResultSet.Parser, new[]{ "Metadata", "Values", "ChunkedValue", "ResumeToken", "Stats" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Spanner.V1.ResultSetMetadata), global::Google.Cloud.Spanner.V1.ResultSetMetadata.Parser, new[]{ "RowType", "Transaction" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Spanner.V1.ResultSetStats), global::Google.Cloud.Spanner.V1.ResultSetStats.Parser, new[]{ "QueryPlan", "QueryStats" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Results from [Read][google.spanner.v1.Spanner.Read] or
/// [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql].
/// </summary>
public sealed partial class ResultSet : pb::IMessage<ResultSet> {
private static readonly pb::MessageParser<ResultSet> _parser = new pb::MessageParser<ResultSet>(() => new ResultSet());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ResultSet> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Spanner.V1.ResultSetReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ResultSet() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ResultSet(ResultSet other) : this() {
Metadata = other.metadata_ != null ? other.Metadata.Clone() : null;
rows_ = other.rows_.Clone();
Stats = other.stats_ != null ? other.Stats.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ResultSet Clone() {
return new ResultSet(this);
}
/// <summary>Field number for the "metadata" field.</summary>
public const int MetadataFieldNumber = 1;
private global::Google.Cloud.Spanner.V1.ResultSetMetadata metadata_;
/// <summary>
/// Metadata about the result set, such as row type information.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Spanner.V1.ResultSetMetadata Metadata {
get { return metadata_; }
set {
metadata_ = value;
}
}
/// <summary>Field number for the "rows" field.</summary>
public const int RowsFieldNumber = 2;
private static readonly pb::FieldCodec<global::Google.Protobuf.WellKnownTypes.ListValue> _repeated_rows_codec
= pb::FieldCodec.ForMessage(18, global::Google.Protobuf.WellKnownTypes.ListValue.Parser);
private readonly pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.ListValue> rows_ = new pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.ListValue>();
/// <summary>
/// Each element in `rows` is a row whose format is defined by
/// [metadata.row_type][google.spanner.v1.ResultSetMetadata.row_type]. The ith element
/// in each row matches the ith field in
/// [metadata.row_type][google.spanner.v1.ResultSetMetadata.row_type]. Elements are
/// encoded based on type as described
/// [here][google.spanner.v1.TypeCode].
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.ListValue> Rows {
get { return rows_; }
}
/// <summary>Field number for the "stats" field.</summary>
public const int StatsFieldNumber = 3;
private global::Google.Cloud.Spanner.V1.ResultSetStats stats_;
/// <summary>
/// Query plan and execution statistics for the query that produced this
/// result set. These can be requested by setting
/// [ExecuteSqlRequest.query_mode][google.spanner.v1.ExecuteSqlRequest.query_mode].
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Spanner.V1.ResultSetStats Stats {
get { return stats_; }
set {
stats_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ResultSet);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ResultSet other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Metadata, other.Metadata)) return false;
if(!rows_.Equals(other.rows_)) return false;
if (!object.Equals(Stats, other.Stats)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (metadata_ != null) hash ^= Metadata.GetHashCode();
hash ^= rows_.GetHashCode();
if (stats_ != null) hash ^= Stats.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) {
if (metadata_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Metadata);
}
rows_.WriteTo(output, _repeated_rows_codec);
if (stats_ != null) {
output.WriteRawTag(26);
output.WriteMessage(Stats);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (metadata_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Metadata);
}
size += rows_.CalculateSize(_repeated_rows_codec);
if (stats_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Stats);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ResultSet other) {
if (other == null) {
return;
}
if (other.metadata_ != null) {
if (metadata_ == null) {
metadata_ = new global::Google.Cloud.Spanner.V1.ResultSetMetadata();
}
Metadata.MergeFrom(other.Metadata);
}
rows_.Add(other.rows_);
if (other.stats_ != null) {
if (stats_ == null) {
stats_ = new global::Google.Cloud.Spanner.V1.ResultSetStats();
}
Stats.MergeFrom(other.Stats);
}
}
[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: {
if (metadata_ == null) {
metadata_ = new global::Google.Cloud.Spanner.V1.ResultSetMetadata();
}
input.ReadMessage(metadata_);
break;
}
case 18: {
rows_.AddEntriesFrom(input, _repeated_rows_codec);
break;
}
case 26: {
if (stats_ == null) {
stats_ = new global::Google.Cloud.Spanner.V1.ResultSetStats();
}
input.ReadMessage(stats_);
break;
}
}
}
}
}
/// <summary>
/// Partial results from a streaming read or SQL query. Streaming reads and
/// SQL queries better tolerate large result sets, large rows, and large
/// values, but are a little trickier to consume.
/// </summary>
public sealed partial class PartialResultSet : pb::IMessage<PartialResultSet> {
private static readonly pb::MessageParser<PartialResultSet> _parser = new pb::MessageParser<PartialResultSet>(() => new PartialResultSet());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PartialResultSet> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Spanner.V1.ResultSetReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PartialResultSet() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PartialResultSet(PartialResultSet other) : this() {
Metadata = other.metadata_ != null ? other.Metadata.Clone() : null;
values_ = other.values_.Clone();
chunkedValue_ = other.chunkedValue_;
resumeToken_ = other.resumeToken_;
Stats = other.stats_ != null ? other.Stats.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PartialResultSet Clone() {
return new PartialResultSet(this);
}
/// <summary>Field number for the "metadata" field.</summary>
public const int MetadataFieldNumber = 1;
private global::Google.Cloud.Spanner.V1.ResultSetMetadata metadata_;
/// <summary>
/// Metadata about the result set, such as row type information.
/// Only present in the first response.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Spanner.V1.ResultSetMetadata Metadata {
get { return metadata_; }
set {
metadata_ = value;
}
}
/// <summary>Field number for the "values" field.</summary>
public const int ValuesFieldNumber = 2;
private static readonly pb::FieldCodec<global::Google.Protobuf.WellKnownTypes.Value> _repeated_values_codec
= pb::FieldCodec.ForMessage(18, global::Google.Protobuf.WellKnownTypes.Value.Parser);
private readonly pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Value> values_ = new pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Value>();
/// <summary>
/// A streamed result set consists of a stream of values, which might
/// be split into many `PartialResultSet` messages to accommodate
/// large rows and/or large values. Every N complete values defines a
/// row, where N is equal to the number of entries in
/// [metadata.row_type.fields][google.spanner.v1.StructType.fields].
///
/// Most values are encoded based on type as described
/// [here][google.spanner.v1.TypeCode].
///
/// It is possible that the last value in values is "chunked",
/// meaning that the rest of the value is sent in subsequent
/// `PartialResultSet`(s). This is denoted by the [chunked_value][google.spanner.v1.PartialResultSet.chunked_value]
/// field. Two or more chunked values can be merged to form a
/// complete value as follows:
///
/// * `bool/number/null`: cannot be chunked
/// * `string`: concatenate the strings
/// * `list`: concatenate the lists. If the last element in a list is a
/// `string`, `list`, or `object`, merge it with the first element in
/// the next list by applying these rules recursively.
/// * `object`: concatenate the (field name, field value) pairs. If a
/// field name is duplicated, then apply these rules recursively
/// to merge the field values.
///
/// Some examples of merging:
///
/// # Strings are concatenated.
/// "foo", "bar" => "foobar"
///
/// # Lists of non-strings are concatenated.
/// [2, 3], [4] => [2, 3, 4]
///
/// # Lists are concatenated, but the last and first elements are merged
/// # because they are strings.
/// ["a", "b"], ["c", "d"] => ["a", "bc", "d"]
///
/// # Lists are concatenated, but the last and first elements are merged
/// # because they are lists. Recursively, the last and first elements
/// # of the inner lists are merged because they are strings.
/// ["a", ["b", "c"]], [["d"], "e"] => ["a", ["b", "cd"], "e"]
///
/// # Non-overlapping object fields are combined.
/// {"a": "1"}, {"b": "2"} => {"a": "1", "b": 2"}
///
/// # Overlapping object fields are merged.
/// {"a": "1"}, {"a": "2"} => {"a": "12"}
///
/// # Examples of merging objects containing lists of strings.
/// {"a": ["1"]}, {"a": ["2"]} => {"a": ["12"]}
///
/// For a more complete example, suppose a streaming SQL query is
/// yielding a result set whose rows contain a single string
/// field. The following `PartialResultSet`s might be yielded:
///
/// {
/// "metadata": { ... }
/// "values": ["Hello", "W"]
/// "chunked_value": true
/// "resume_token": "Af65..."
/// }
/// {
/// "values": ["orl"]
/// "chunked_value": true
/// "resume_token": "Bqp2..."
/// }
/// {
/// "values": ["d"]
/// "resume_token": "Zx1B..."
/// }
///
/// This sequence of `PartialResultSet`s encodes two rows, one
/// containing the field value `"Hello"`, and a second containing the
/// field value `"World" = "W" + "orl" + "d"`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Value> Values {
get { return values_; }
}
/// <summary>Field number for the "chunked_value" field.</summary>
public const int ChunkedValueFieldNumber = 3;
private bool chunkedValue_;
/// <summary>
/// If true, then the final value in [values][google.spanner.v1.PartialResultSet.values] is chunked, and must
/// be combined with more values from subsequent `PartialResultSet`s
/// to obtain a complete field value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool ChunkedValue {
get { return chunkedValue_; }
set {
chunkedValue_ = value;
}
}
/// <summary>Field number for the "resume_token" field.</summary>
public const int ResumeTokenFieldNumber = 4;
private pb::ByteString resumeToken_ = pb::ByteString.Empty;
/// <summary>
/// Streaming calls might be interrupted for a variety of reasons, such
/// as TCP connection loss. If this occurs, the stream of results can
/// be resumed by re-sending the original request and including
/// `resume_token`. Note that executing any other transaction in the
/// same session invalidates the token.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pb::ByteString ResumeToken {
get { return resumeToken_; }
set {
resumeToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "stats" field.</summary>
public const int StatsFieldNumber = 5;
private global::Google.Cloud.Spanner.V1.ResultSetStats stats_;
/// <summary>
/// Query plan and execution statistics for the query that produced this
/// streaming result set. These can be requested by setting
/// [ExecuteSqlRequest.query_mode][google.spanner.v1.ExecuteSqlRequest.query_mode] and are sent
/// only once with the last response in the stream.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Spanner.V1.ResultSetStats Stats {
get { return stats_; }
set {
stats_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PartialResultSet);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PartialResultSet other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Metadata, other.Metadata)) return false;
if(!values_.Equals(other.values_)) return false;
if (ChunkedValue != other.ChunkedValue) return false;
if (ResumeToken != other.ResumeToken) return false;
if (!object.Equals(Stats, other.Stats)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (metadata_ != null) hash ^= Metadata.GetHashCode();
hash ^= values_.GetHashCode();
if (ChunkedValue != false) hash ^= ChunkedValue.GetHashCode();
if (ResumeToken.Length != 0) hash ^= ResumeToken.GetHashCode();
if (stats_ != null) hash ^= Stats.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) {
if (metadata_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Metadata);
}
values_.WriteTo(output, _repeated_values_codec);
if (ChunkedValue != false) {
output.WriteRawTag(24);
output.WriteBool(ChunkedValue);
}
if (ResumeToken.Length != 0) {
output.WriteRawTag(34);
output.WriteBytes(ResumeToken);
}
if (stats_ != null) {
output.WriteRawTag(42);
output.WriteMessage(Stats);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (metadata_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Metadata);
}
size += values_.CalculateSize(_repeated_values_codec);
if (ChunkedValue != false) {
size += 1 + 1;
}
if (ResumeToken.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeBytesSize(ResumeToken);
}
if (stats_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Stats);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PartialResultSet other) {
if (other == null) {
return;
}
if (other.metadata_ != null) {
if (metadata_ == null) {
metadata_ = new global::Google.Cloud.Spanner.V1.ResultSetMetadata();
}
Metadata.MergeFrom(other.Metadata);
}
values_.Add(other.values_);
if (other.ChunkedValue != false) {
ChunkedValue = other.ChunkedValue;
}
if (other.ResumeToken.Length != 0) {
ResumeToken = other.ResumeToken;
}
if (other.stats_ != null) {
if (stats_ == null) {
stats_ = new global::Google.Cloud.Spanner.V1.ResultSetStats();
}
Stats.MergeFrom(other.Stats);
}
}
[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: {
if (metadata_ == null) {
metadata_ = new global::Google.Cloud.Spanner.V1.ResultSetMetadata();
}
input.ReadMessage(metadata_);
break;
}
case 18: {
values_.AddEntriesFrom(input, _repeated_values_codec);
break;
}
case 24: {
ChunkedValue = input.ReadBool();
break;
}
case 34: {
ResumeToken = input.ReadBytes();
break;
}
case 42: {
if (stats_ == null) {
stats_ = new global::Google.Cloud.Spanner.V1.ResultSetStats();
}
input.ReadMessage(stats_);
break;
}
}
}
}
}
/// <summary>
/// Metadata about a [ResultSet][google.spanner.v1.ResultSet] or [PartialResultSet][google.spanner.v1.PartialResultSet].
/// </summary>
public sealed partial class ResultSetMetadata : pb::IMessage<ResultSetMetadata> {
private static readonly pb::MessageParser<ResultSetMetadata> _parser = new pb::MessageParser<ResultSetMetadata>(() => new ResultSetMetadata());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ResultSetMetadata> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Spanner.V1.ResultSetReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ResultSetMetadata() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ResultSetMetadata(ResultSetMetadata other) : this() {
RowType = other.rowType_ != null ? other.RowType.Clone() : null;
Transaction = other.transaction_ != null ? other.Transaction.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ResultSetMetadata Clone() {
return new ResultSetMetadata(this);
}
/// <summary>Field number for the "row_type" field.</summary>
public const int RowTypeFieldNumber = 1;
private global::Google.Cloud.Spanner.V1.StructType rowType_;
/// <summary>
/// Indicates the field names and types for the rows in the result
/// set. For example, a SQL query like `"SELECT UserId, UserName FROM
/// Users"` could return a `row_type` value like:
///
/// "fields": [
/// { "name": "UserId", "type": { "code": "INT64" } },
/// { "name": "UserName", "type": { "code": "STRING" } },
/// ]
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Spanner.V1.StructType RowType {
get { return rowType_; }
set {
rowType_ = value;
}
}
/// <summary>Field number for the "transaction" field.</summary>
public const int TransactionFieldNumber = 2;
private global::Google.Cloud.Spanner.V1.Transaction transaction_;
/// <summary>
/// If the read or SQL query began a transaction as a side-effect, the
/// information about the new transaction is yielded here.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Spanner.V1.Transaction Transaction {
get { return transaction_; }
set {
transaction_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ResultSetMetadata);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ResultSetMetadata other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(RowType, other.RowType)) return false;
if (!object.Equals(Transaction, other.Transaction)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (rowType_ != null) hash ^= RowType.GetHashCode();
if (transaction_ != null) hash ^= Transaction.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) {
if (rowType_ != null) {
output.WriteRawTag(10);
output.WriteMessage(RowType);
}
if (transaction_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Transaction);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (rowType_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(RowType);
}
if (transaction_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Transaction);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ResultSetMetadata other) {
if (other == null) {
return;
}
if (other.rowType_ != null) {
if (rowType_ == null) {
rowType_ = new global::Google.Cloud.Spanner.V1.StructType();
}
RowType.MergeFrom(other.RowType);
}
if (other.transaction_ != null) {
if (transaction_ == null) {
transaction_ = new global::Google.Cloud.Spanner.V1.Transaction();
}
Transaction.MergeFrom(other.Transaction);
}
}
[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: {
if (rowType_ == null) {
rowType_ = new global::Google.Cloud.Spanner.V1.StructType();
}
input.ReadMessage(rowType_);
break;
}
case 18: {
if (transaction_ == null) {
transaction_ = new global::Google.Cloud.Spanner.V1.Transaction();
}
input.ReadMessage(transaction_);
break;
}
}
}
}
}
/// <summary>
/// Additional statistics about a [ResultSet][google.spanner.v1.ResultSet] or [PartialResultSet][google.spanner.v1.PartialResultSet].
/// </summary>
public sealed partial class ResultSetStats : pb::IMessage<ResultSetStats> {
private static readonly pb::MessageParser<ResultSetStats> _parser = new pb::MessageParser<ResultSetStats>(() => new ResultSetStats());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ResultSetStats> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Spanner.V1.ResultSetReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ResultSetStats() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ResultSetStats(ResultSetStats other) : this() {
QueryPlan = other.queryPlan_ != null ? other.QueryPlan.Clone() : null;
QueryStats = other.queryStats_ != null ? other.QueryStats.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ResultSetStats Clone() {
return new ResultSetStats(this);
}
/// <summary>Field number for the "query_plan" field.</summary>
public const int QueryPlanFieldNumber = 1;
private global::Google.Cloud.Spanner.V1.QueryPlan queryPlan_;
/// <summary>
/// [QueryPlan][google.spanner.v1.QueryPlan] for the query associated with this result.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Spanner.V1.QueryPlan QueryPlan {
get { return queryPlan_; }
set {
queryPlan_ = value;
}
}
/// <summary>Field number for the "query_stats" field.</summary>
public const int QueryStatsFieldNumber = 2;
private global::Google.Protobuf.WellKnownTypes.Struct queryStats_;
/// <summary>
/// Aggregated statistics from the execution of the query. Only present when
/// the query is profiled. For example, a query could return the statistics as
/// follows:
///
/// {
/// "rows_returned": "3",
/// "elapsed_time": "1.22 secs",
/// "cpu_time": "1.19 secs"
/// }
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Struct QueryStats {
get { return queryStats_; }
set {
queryStats_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ResultSetStats);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ResultSetStats other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(QueryPlan, other.QueryPlan)) return false;
if (!object.Equals(QueryStats, other.QueryStats)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (queryPlan_ != null) hash ^= QueryPlan.GetHashCode();
if (queryStats_ != null) hash ^= QueryStats.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) {
if (queryPlan_ != null) {
output.WriteRawTag(10);
output.WriteMessage(QueryPlan);
}
if (queryStats_ != null) {
output.WriteRawTag(18);
output.WriteMessage(QueryStats);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (queryPlan_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(QueryPlan);
}
if (queryStats_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(QueryStats);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ResultSetStats other) {
if (other == null) {
return;
}
if (other.queryPlan_ != null) {
if (queryPlan_ == null) {
queryPlan_ = new global::Google.Cloud.Spanner.V1.QueryPlan();
}
QueryPlan.MergeFrom(other.QueryPlan);
}
if (other.queryStats_ != null) {
if (queryStats_ == null) {
queryStats_ = new global::Google.Protobuf.WellKnownTypes.Struct();
}
QueryStats.MergeFrom(other.QueryStats);
}
}
[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: {
if (queryPlan_ == null) {
queryPlan_ = new global::Google.Cloud.Spanner.V1.QueryPlan();
}
input.ReadMessage(queryPlan_);
break;
}
case 18: {
if (queryStats_ == null) {
queryStats_ = new global::Google.Protobuf.WellKnownTypes.Struct();
}
input.ReadMessage(queryStats_);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Mepham.Forum.Api.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.